错误是这样的:
Traceback (most recent call last):
File "NearestCentroid.py", line 53, in <module>
clf.fit(X_train.todense(),y_train)
File "/usr/local/lib/python2.7/dist-packages/scikit_learn-0.13.1-py2.7-linux-i686.egg/sklearn/neighbors/nearest_centroid.py", line 115, in fit
variance = np.array(np.power(X - self.centroids_[y], 2))
IndexError: arrays used as indices must be of integer (or boolean) type
代码是这样的:
distancemetric=['euclidean','l2']
for mtrc in distancemetric:
for shrkthrshld in [None]:
#shrkthrshld=0
#while (shrkthrshld <=1.0):
clf = NearestCentroid(metric=mtrc,shrink_threshold=shrkthrshld)
clf.fit(X_train.todense(),y_train)
y_predicted = clf.predict(X_test.todense())
我正在使用scikit-learn
包,X-train
,y_train
采用LIBSVM格式,X
是功能:值对,y_train
是目标/标签,X_train
采用CSR matric格式,shrink_threshold
不支持CSR稀疏矩阵,因此我将.todense()
添加到X_train
,然后我收到此错误,任何人都可以提供帮助我解决这个问题?非常感谢!
答案 0 :(得分:23)
我在使用Pystruct pystruct.learners.OneSlackSSVM
时遇到了类似的问题。
之所以发生,是因为我的训练标签是漂浮物,而不是整数。就我而言,这是因为我用np.ones初始化了标签,没有指定dtype = np.int8。希望它有所帮助。
答案 1 :(得分:4)
通常情况下,索引数组应该通过创建它的方式明确integer
类型,但是在传递空列表的情况下,变为默认float
,这可能不是由程序员考虑。例如:
>>> np.array(xrange(1))
>>> array([0]) #integer type as expected
>>> np.array(xrange(0))
>>> array([], dtype=float64) #does not generalize to the empty list
因此,应该总是明确地定义数组构造函数中的dtype
。
答案 2 :(得分:0)
有时候您的数据是整数,并且所有事情都是正确的,但是它发生了,因为您的数据系列之一是一个空数组,因此您可以使用以下条件:
if len(X_train.todense())> 0: