Java教程

matplotlib作图不显示3D图,怎么办?

本文主要是介绍matplotlib作图不显示3D图,怎么办?,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

大家好,我是Python进阶者。

一、前言

前几天在Python白银交流群【Kim】问了一个Python作图的问题,问题如下:他不显示3D图咋办?

代码如下:

from sklearn.linear_model import LogisticRegression
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 加载数据
data = load_breast_cancer()
X, y = data['data'][:,:2], data['target']

# 求出两个维度对应的数据在逻辑回归算法下的最优解
lr = LogisticRegression(fit_intercept=False)    # 是否计算截距项
lr.fit(X, y)
# 分别把两个维度所对应的参数w1和w2取出来
theta1 = lr.coef_[0, 0]
theta2 = lr.coef_[0, 1]
print(theta1)
print(theta2)

def p_theta_function(features, w1, w2):
    """
    已知w1和w2的情况下,传进来数据X,返回数据的y_predict
    :param features:xi=(x1, x2)
    :param w1:
    :param w2:
    :return:  y_pred
    """
    # z = $\theta^Tx=w1*x1+w2*x2$
    z = w1 * features[0] + w2 * features[1]
    return 1 / (1 + np.exp(-z))

def loss_function(sample_features, sample_labels, w1, w2):
    """
    传入一份已知数据,如果已知w1和w2,计算对应这份数据的loss损失
    :param sample_features:
    :param sample_labels:
    :param w1:
    :param w2:
    :return:
    """
    result = 0
    # 遍历数据集中的每一条样本,并且计算每条样本的损失,加到result身上得到整体数据集
    for feature, label in zip(sample_features, sample_labels):
        # 计算一条样本的y_pred
        p_result = p_theta_function(feature, w1, w2)
        loss_result = -1 * label * np.log(p_result) - (1 - label) * np.log(1 - p_result)
        result += loss_result
    return result

theta1_space = np.linspace(theta1-0.6, theta1+0.6, 50)
theta2_space = np.linspace(theta2-0.6, theta2+0.6, 50)
result1 = np.array([loss_function(X, y, i, theta2) for i in theta1_space])
result2 = np.array([loss_function(X, y, theta1, i) for i in theta2_space])

fig1 = plt.figure(figsize=(8, 6))
plt.subplot(221)
plt.plot(theta1_space, result1)

plt.subplot(222)
plt.plot(theta2_space, result2)

plt.subplot(223)
theta1_grid, theta2_grid = np.meshgrid(theta1_space, theta2_space)
loss_grid = loss_function(X, y, theta1_grid, theta2_grid)
plt.contour(theta1_grid, theta2_grid, loss_grid)

plt.subplot(224)
plt. contour(theta1_grid, theta2_grid, loss_grid, 30)

fig2 = plt.figure()
ax = Axes3D(fig2)
ax.plot_surface(theta1_grid, theta2_grid, loss_grid)

plt.show()

二、实现过程

这里【莫生气】给了个思路如下:试试看windows下跑跑?

后来【瑜亮老师】给跑了出来,结果如下图所示:

image.png

总共有两张图。粉丝反馈确实有两张图,Mac机器下,平面图没问题,3d不行。后来发现是电脑配置太低了,加载需要时间,有时候有的电脑不一定出得来结果。

【瑜亮老师】的plt是3.5的。运行后会有一个提示,只是提醒版本的变化,图是能正常出的。后来发现Axes3D(fig) 的写法在plt3.6中就不能运行了,你的是3.9版本的所以无法出图。我的是3.5因此可以,但是提示版本更改。按照楼上大佬的代码,3.5也可以正常出图,且无提示。

如果你也有类似这种Python相关的小问题,欢迎随时来交流群学习交流哦,有问必答!

三、总结

大家好,我是Python进阶者。这篇文章主要盘点了一个Python正则表达式的问题,文中针对该问题,给出了具体的解析和代码实现,帮助粉丝顺利解决了问题。

最后感谢粉丝【Kim】提出的问题,感谢【瑜亮老师】给出的思路,感谢【莫生气】等人参与学习交流。

【提问补充】温馨提示,大家在群里提问的时候。可以注意下面几点:如果涉及到大文件数据,可以数据脱敏后,发点demo数据来(小文件的意思),然后贴点代码(可以复制的那种),记得发报错截图(截全)。代码不多的话,直接发代码文字即可,代码超过50行这样的话,发个.py文件就行。

image.png

这篇关于matplotlib作图不显示3D图,怎么办?的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!