vik*_*kky 1 python matplotlib scikit-learn
我正在尝试在 scikit learn 中绘制逻辑回归的决策边界
features_train_df : 650 columns, 5250 rows
features_test_df : 650 columns, 1750 rows
class_train_df = 1 column (class to be predicted), 5250 rows
class_test_df = 1 column (class to be predicted), 1750 rows
Run Code Online (Sandbox Code Playgroud)
分类器代码;
tuned_logreg = LogisticRegression(penalty = 'l2', tol = 0.0001,C = 0.1,max_iter = 100,class_weight = "balanced")
tuned_logreg.fit(x_train[sorted_important_features_list[0:650]].values, y_train['loss'].values)
y_pred_3 = tuned_logreg.predict(x_test[sorted_important_features_list[0:650]].values)
Run Code Online (Sandbox Code Playgroud)
我得到了分类器代码的正确输出。
在网上得到这个代码:
code:
X = features_train_df.values
# evenly sampled points
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 50),
np.linspace(y_min, y_max, 50))
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
#plot background colors
ax = plt.gca()
Z = tuned_logreg.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
Z = Z.reshape(xx.shape)
cs = ax.contourf(xx, yy, Z, cmap='RdBu', alpha=.5)
cs2 = ax.contour(xx, yy, Z, cmap='RdBu', alpha=.5)
plt.clabel(cs2, fmt = '%2.1f', colors = 'k', fontsize=14)
# Plot the points
ax.plot(Xtrain[ytrain == 0, 0], Xtrain[ytrain == 0, 1], 'ro', label='Class 1')
ax.plot(Xtrain[ytrain == 1, 0], Xtrain[ytrain == 1, 1], 'bo', label='Class 2')
# make legend
plt.legend(loc='upper left', scatterpoints=1, numpoints=1)
Run Code Online (Sandbox Code Playgroud)
错误:
ValueError: X has 2 features per sample; expecting 650
Run Code Online (Sandbox Code Playgroud)
请建议我哪里出错了
小智 5
此外,您可以使用学习模型的内部值:
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
import matplotlib.pyplot as plt
X, y = make_classification(200, 2, 2, 0, weights=[.5, .5], random_state=15)
clf = LogisticRegression().fit(X, y)
points_x=[x/10. for x in range(-50,+50)]
line_bias = clf.intercept_
line_w = clf.coef_.T
points_y=[(line_w[0]*x+line_bias)/(-1*line_w[1]) for x in points_x]
plt.plot(points_x, points_y)
plt.scatter(X[:,0], X[:,1],c=y)
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6716 次 |
| 最近记录: |