绘制具有3个特征的Binary Logistic回归

时间:2018-07-06 09:36:24

标签: python logistic-regression graph-visualization

我为二进制分类建立了逻辑回归模型。我正在尝试开发可视化效果,但是无法。 我可以使用两个功能来做到这一点,但是我的模型使用了三个功能,因此很难将其转换为3d图形。 以下是我尝试过但无法正常工作的代码。如果有人可以指导我,我将不胜感激。我希望能够可视化我的结果。我还是可视化图形的新手。

from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2, X3 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 2].min() - 1, stop = X_set[:, 2].max() + 1, step = 0.01))
plt.contourf(X1, X2, X3, classifier.predict(np.array([X1.ravel(), X2.ravel(), X3.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
plt.ylim(X3.min(), X3.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('Recency')
plt.ylabel('Frequency')
plt.zlabel('Monetary')
plt.legend()
plt.show()

1 个答案:

答案 0 :(得分:0)

plt.contourf(x,y,z)对于可视化两个特征(x,y)和一个取决于这两个特征的预测函数会很好地工作。预测z必须是2D数组。使用三个功能,您可以修复其中之一,然后使用plt.contourf()进行2D等高线图绘制。要获得更完整的图片,请重复此操作,将功能固定为另一个值和/或固定其他功能之一。

或使用散点图绘制3D训练集: https://matplotlib.org/2.1.1/gallery/mplot3d/scatter3d.html

对于四个可能的结果,可以使用不同的标记可视化真实标签和预测标签:(true = 1,pred = 1),(true = 1,pred = 0),(true = 0,pred = 1)和( true = 0,pred = 0)。