Skip to main content
 首页 » 编程设计

python之预测问题与 sciklearn ValueError : operands could not be broadcast together with shapes

2024年12月31日10luoye11

我正在尝试绘制多个分类器的决策边界。但是我无法运行:

Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 

没有错误信息。

请帮助我发现我做错了什么?

这是我的代码:

pas = 0.02     
x_min, x_max = iris.data[:,0].min()-1, iris.data[:,0].max()+1 
y_min, y_max = iris.data[:,1].min()-1, iris.data[:,1].max()+1 
xx, yy = np.meshgrid( 
    np.arange(x_min, x_max, pas), 
    np.arange(y_min, y_max, pas)) 
 
for clf, subfig in zip(classifieurs, subfigs.reshape(-1)): 
    # TODO Q2B 
    # Entraînez le classifieur 
    clf.fit(iris.data, iris.target) 
 
    # TODO Q2B 
    # Obtenez et affichez son erreur (1 - accuracy) 
    # Stockez la valeur de cette erreur dans la variable err 
    err = 1 - accuracy_score(clf.predict(iris.data), iris.target) 
    print("Taux d'erreur pour", clf.__class__.__name__, "est de:", err*100, "%") 
 
    # TODO Q2B 
    # Utilisez la grille que vous avez créée plus haut 
    # pour afficher les régions de décision, de même 
    # que les points colorés selon leur vraie classe 
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]); 
    Z = Z.reshape(x.shape) 
    subfig.contourf(x, y, Z, cmap=plt.cm.RdYlBu) 
 
    # Identification des axes et des méthodes 
    subfig.set_xlabel(data.feature_names[f1]) 
    subfig.set_ylabel(data.feature_names[f2]) 
    subfig.set_title(clf.__class__.__name__) 

请您参考如下方法:

您正在尝试绘制决策面,对吗?


您收到此错误是因为您首先使用以下方法拟合分类器 clf:

clf.fit(iris.data, iris.target) 

现在,iris.data 包含 4 个特征/变量:

print(iris.data.shape) 
(150, 4) 

接下来,您尝试使用仅包含 2 个变量/特征的数据进行预测:

Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 
 
print(np.c_[xx.ravel(), yy.ravel()].shape) 
(61600, 2) 

如何解决这个问题

要解决此问题,最初使用 2 个特征。

示例:

import numpy as np 
import matplotlib.pyplot as plt 
from sklearn import svm, datasets 
 
iris = datasets.load_iris() 
X = iris.data[:, :2] 
Y = iris.target 
 
h = .02  # step size in the mesh 
 
# we create an instance of SVM and fit out data. 
clf = svm.SVC(kernel='linear') 
clf.fit(X, Y) 
 
# Plot the decision boundary. For that, we will assign a color to each 
# point in the mesh [x_min, x_max]x[y_min, y_max]. 
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) 
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) 
 
# Put the result into a color plot 
Z = Z.reshape(xx.shape) 
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) 
 
# Plot also the training points 
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, edgecolors='k') 
plt.title('3-Class classification using Support Vector Machine') 
plt.axis('tight') 
plt.show()