我正在学习Sebastian Rashka的德文书籍《用Python进行机器学习》。我使用的是在Windows系统上的Anaconda和Spyder(包括IPython控制台)。
在第3章中,他提到了基于“感知器模型”的算法。按照作者的指示,代码应该如下所示:
from sklearn.metrics import accuracy_scoreprint('Korrektklassifizierungsrate: %.2f' % accuracy_score(y_test, y_pred))from matplotlib.colors import ListedColormapdef plot_decision_region(X, y, classifier, resolution=0.02): # 设置标记和颜色 markers = ('s', 'x', 'o', '^', 'v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap = ListedColormap(colors[:len(np.unique(y))]) # 绘制决策边界 x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, \ resolution), np.arange(x2_min, x2_max, resolution)) Z = classifier.predict(np.array([xx1.ravel(), \ xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap), plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) # 绘制所有样本 for idx, cl in enumerate(np.unique(y)): plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl) # 高亮显示测试数据集的样本 if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:, 1], c='', alpha=1.0, linewidths=1, marker='o' s=55, label='test set') X_combined_std = np.vstack((X_train_std, X_test_std))y_combined = np.hstack((y_train, y_test))plot_decision_regions(X=X_combined_std, y=y_combined, classifier=ppn, test_idx=range(105,150))plt.xlabel('Länge des Blütenblatts [standardisiert]')plt.ylabel('Breite des Blütenblatts [standardisiert]')plt.legend(loc='upper left')plt.show()
File "<ipython-input-1-e576c1f255dd>", line 19 plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap), ^IndentationError: unexpected indent
所以,我不确定默认设置是什么。我非常希望能理解这个错误,如果有人能帮我解决,我将不胜感激。是否可能与cmap=cmap这个等式有关?
回答:
将第19到21行的缩进取消。
Z = Z.reshape(xx1.shape)plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap),plt.xlim(xx1.min(), xx1.max())plt.ylim(xx2.min(), xx2.max())