gpt4 book ai didi

python - scikit-learn 查询数据维度必须匹配训练数据维度

转载 作者:太空狗 更新时间:2023-10-30 00:10:32 24 4
gpt4 key购买 nike

我正在尝试使用来自 scikit 学习网站的这段代码:

http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html

我正在使用自己的数据。我的问题是,我有两个以上的功能。如果我想将特征从 2 个“扩展”到 3 个或 4 个....

我得到:

“查询数据维度必须匹配训练数据维度”

def machine():
with open("test.txt",'r') as csvr:

reader= csv.reader(csvr,delimiter='\t')

for i,row in enumerate(reader):

if i==0:
pass
elif '' in row[2:]:
pass
else:
liste.append(map(float,row[2:]))

a = np.array(liste)
h = .02
names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Decision Tree",
"Random Forest", "AdaBoost", "Naive Bayes", "LDA", "QDA"]
classifiers = [
KNeighborsClassifier(1),
SVC(kernel="linear", C=0.025),
SVC(gamma=2, C=1),
DecisionTreeClassifier(max_depth=5),
RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
AdaBoostClassifier(),
GaussianNB(),
LDA(),
QDA()]



X = a[:,:3]
y = np.ravel(a[:,13])

linearly_separable = (X, y)
datasets =[linearly_separable]
figure = plt.figure(figsize=(27, 9))
i = 1

for ds in datasets:
X, y = ds

X = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.4)

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.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))

cm = plt.cm.RdBu
cm_bright = ListedColormap(['#FF0000', '#0000FF'])
ax = plt.subplot(len(datasets), len(classifiers) + 1, i)

ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)

ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright, alpha=0.6)
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xticks(())
ax.set_yticks(())
i += 1

for name, clf in zip(names, classifiers):
ax = plt.subplot(len(datasets), len(classifiers) + 1, i)
print clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
print y.shape, X.shape
if hasattr(clf, "decision_function"):
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
print Z
else:
Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]


Z = Z.reshape(xx.shape)

ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)
ax.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cm_bright)

ax.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cm_bright,
alpha=0.6)

ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(name)
ax.text(xx.max() - .3, yy.min() + .3, ('%.2f' % score).lstrip('0'),
size=15, horizontalalignment='right')
i += 1

figure.subplots_adjust(left=.02, right=.98)
plt.show()

在本例中,我使用了三个特征。我在代码中做错了什么,是 X_train 和 X_test 数据的问题吗?只有两个功能,一切都很好。

我的 X 值:

(array([[ 1.,  1.,  0.],
[ 1., 0., 0.],
[ 1., 0., 0.],
[ 1., 0., 0.],
[ 1., 1., 0.],
[ 1., 0., 0.],
[ 1., 0., 0.],
[ 3., 3., 0.],
[ 1., 1., 0.],
[ 1., 1., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 4., 4., 2.],
[ 0., 0., 0.],
[ 6., 3., 0.],
[ 5., 3., 2.],
[ 2., 2., 0.],
[ 4., 4., 2.],
[ 2., 1., 0.],
[ 2., 2., 0.]]), array([ 1., 1., 1., 1., 0., 1., 1., 0., 1., 1., 0., 1., 1.,
1., 1., 1., 0., 1., 1., 0., 1., 0., 1., 1.]))

第一个数组是 X 数组,第二个数组是 y(目标)数组。

我很抱歉错误的格式 = 错误:

        Traceback (most recent call last):

File "allM.py", line 144, in <module>
mainplot(namePlot,1,2)
File "allM.py", line 117, in mainplot

Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]

File "/usr/local/lib/python2.7/dist-packages/sklearn/neighbors/classification.py", line 191, in predict_proba
neigh_dist, neigh_ind = self.kneighbors(X)

File "/usr/local/lib/python2.7/dist-packages/sklearn/neighbors/base.py", line 332, in kneighbors
return_distance=return_distance)

File "binary_tree.pxi", line 1298, in sklearn.neighbors.kd_tree.BinaryTree.query (sklearn/neighbors/kd_tree.c:10433)

ValueError: query data dimension must match training data dimension

这是没有将他放入数据集“ds”的X数组。

[[ 1.  1.  0.][ 1.  0.  0.][ 1.  0.  0.][ 1.  0.  0.][ 1.  1.  0.][ 1.  0.  0.][ 1.  0.  0.][ 3.  3.  0.][ 1.  1.  0.][ 1.  1.  0.][ 0.  0.  0.][ 0.  0.  0.][ 0.  0.  0.][ 0.  0.  0.][ 0.  0.  0.][ 0.  0.  0.][ 4.  4.  2.][ 0.  0.  0.][ 6.  3.  0.][ 5.  3.  2.][ 2.  2.  0.][ 4.  4.  2.][ 2.  1.  0.][ 2.  2.  0.]]

最佳答案

发生这种情况是因为 clf.predict_proba() 需要一个数组,其中每一行的元素数与训练数据中的行数相同——换句话说,输入的形状为 (num_rows, 3).

当您使用二维范例时,这是有效的,因为 np.c_[xx.ravel(), yy.ravel()] 的结果是一个包含两个元素行的数组:

print np.c_[xx.ravel(), yy.ravel()].shape
(45738, 2)

这些范例有两个元素,因为它们是由 np.meshgrid 创建的,示例代码使用它来创建一组输入以覆盖二维空间,这将很好地绘制。尝试将包含三项行的数组传递给 clf.predict_proba,事情应该会正常进行。

如果您想重现这段特定的示例代码,您必须创建一个 3D 网格,如 this 中所述。关于SO的问题。您还将以 3D 形式绘制结果,其中 mplot3d将作为一个很好的起点,尽管基于我在示例代码中对绘图的(公认的简短)外观,我怀疑这可能比它的值(value)更麻烦。我真的不确定这些图的 3D 模拟看起来如何。

关于python - scikit-learn 查询数据维度必须匹配训练数据维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29948156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com