Python:“ValueError:使用sklearn设置带序列的数组元素”

时间:2017-10-13 01:31:20

标签: python numpy scipy

这是一行:

from sklearn import tree


X = [[181,80,44], [177, 70, 43], [160, 60, 38], 154, 54, 37],
[166,64,40], [190,90,47], [175,64,39],[177,70,40],[159,55,37],
[171,75,42],[181,85,43]

Y = ['male', 'female', 'female', 'female', 'male', 'male', 'male',
'female', 'male', 'female', 'male']

clf = tree.DecisionTreeClassifier()

clf = clf.fit(X,Y)

prediction = clf.predict([[182,78,43]])

print (prediction)

结果:

Traceback (most recent call last):


File "C:\Python\code\test.py", line 14, in <module>
clf = clf.fit(X,Y)
File "C:\Python\lib\site-packages\sklearn\tree\tree.py", line 790, in fit
X_idx_sorted=X_idx_sorted)
File "C:\Python\lib\site-packages\sklearn\tree\tree.py", line 116, in fit
X = check_array(X, dtype=DTYPE, accept_sparse="csc")
File "C:\Python\lib\site-packages\sklearn\utils\validation.py", line 402, 

in check_array
array = np.array(array, dtype=dtype, order=order, copy=copy)
in check_array
array = np.array(array, dtype=dtype, order=order, copy=copy)
ValueError: setting an array element with a sequence.
[Finished in 0.5s]

预期结果:

应显示通过身体测量预测的性别:"182,78,43"

示例:男性或女性

在Sublime上使用sklearn,numpy + mkl和scipy运行Python 3.6。

代码最初来自:https://www.youtube.com/watch?v=T5pRlIbr6gg。 整个youtube评论部分没有答案。 感谢如果在这里找到答案,找不到任何答案。

1 个答案:

答案 0 :(得分:1)

如果这真的是你的代码,那么问题就从一开始就开始了:

X = [[181,80,44], [177, 70, 43], [160, 60, 38], 154, 54, 37], 
[166,64,40], [190,90,47], [175,64,39],[177,70,40],[159,55,37],
[171,75,42],[181,85,43]

创造了一些远离可用的东西:

print(X)
# ([[181, 80, 44], [177, 70, 43], [160, 60, 38], 154, 54, 37],)

所以每个方向都有一个括号要添加(如果你不清楚的话:阅读sklearn关于数据格式的文档:2d-shape of shape(n_samples,n_features);还要考虑读一些numpy的介绍,其中字形来自 - &gt;内部一切都是基于numpy的):

X = [[181,80,44], [177, 70, 43], [160, 60, 38], [154, 54, 37],  # before 154
[166,64,40], [190,90,47], [175,64,39],[177,70,40],[159,55,37],
[171,75,42],[181,85,43]]                                        # at end

我必须承认:这是应该立即找到的东西,我无法理解为什么有人会花时间为SO创建帖子,但不花时间去检查简单数组创建的语法。

公平地说:我认为它最初不会通过语法检查(这实际上是一个奇怪的结构)。

编辑:公平#2:链接视频真的那么糟糕......我不确定该怎么想(很好地使用DTree来完成这项任务)已经疯了,甚至LinearRegression似乎更可行了!)

是的,代码在完成上述修改后预测male