【问题标题】:heatmap for logistic regression逻辑回归的热图
【发布时间】:2016-01-07 09:48:00
【问题描述】:

所以,

我是 python 新手,我的代码有点问题

X_train, Y_train, Xtest, ytest = pickle.load(open("data.p", "rb"))

h = 100
x_min, x_max = X_train.min() - 1, X_train.max() + 1
y_min, y_max = X_train.min() - 1, X_train.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

logreg = linear_model.LogisticRegression(C=1.0, penalty='l2', tol=1e-6).fit(X_train, Y_train)

grid_data = np.c_[xx.ravel(), yy.ravel()]
Z = logreg.predict_proba(grid_data)[:,1]
Z = Z.reshape(xx.shape)

yhat = logreg.predict_proba(Xtest)[:,1]
r = scipy.stats.pearsonr(yhat, ytest)[0]

plt.imshow(Z, extent=[xx.min(), xx.max(), yy.max(), yy.min()])

plt.plot(Xtest[ytest==0, 0], Xtest[ytest==0, 1], 'co')
plt.plot(Xtest[ytest==1, 0], Xtest[ytest==1, 1], 'ro')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title('r=' + str(r))

plt.show()

当我使用大小为 x:2 的数据文件运行此代码时,它可以完美运行

但我也有超过 2 列的数据。

确切地说是 12,因为那个 python 向我发送了这个错误

Z = logreg.predict_proba(grid_data)[:,1]
  File "D:\IDE\Anaconda\lib\site-packages\sklearn\linear_model\logistic.py", line 128, in predict_proba
    return self._predict_proba_lr(X)
  File "D:\IDE\Anaconda\lib\site-packages\sklearn\linear_model\base.py", line 229, in _predict_proba_lr
    prob = self.decision_function(X)
  File "D:\IDE\Anaconda\lib\site-packages\sklearn\linear_model\base.py", line 196, in decision_function
    % (X.shape[1], n_features))
ValueError: X has 2 features per sample; expecting 12

不知何故,我需要将 grid_data 设置为 12 列?!但是不知道怎么弄

编辑:

添加其余代码

【问题讨论】:

  • 我认为您无法轻松地在 12 维输入空间上可视化预测结果。相反,您可以例如修复 10 个输入并绘制剩余两个输入的 2D 平面。也许其他人对此主题有更多提示。

标签: python scikit-learn prediction logistic-regression


【解决方案1】:

您的模型适合 12 维数据(X_train.shape 为 (N, 12)), 并且您正在尝试对二维数据进行预测(查看grid_data 的形状)。当模型适合 12D 特征时,预测 2D 特征的值是没有意义的。

我猜您的数据作为该网格中的特征存在,因此您可以执行最近邻之类的操作,以从 X_train 检索所有网格点的最近输入点(如果您的数据正好位于网格上,那么查找应该减少到正确索引它),然后将输出预测与网格点相关联。

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 1970-01-01
    • 2020-01-31
    • 2020-09-25
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 2021-11-11
    • 2018-01-26
    相关资源
    最近更新 更多