Python 用作索引的数组必须是整数(或布尔)类型

Python 用作索引的数组必须是整数(或布尔)类型,python,scikit-learn,Python,Scikit Learn,错误如下: 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_

错误如下:

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())
回溯(最近一次呼叫最后一次):
文件“NearestCentroid.py”,第53行,在
clf.fit(X_系列todense(),y_系列)
文件“/usr/local/lib/python2.7/dist packages/scikit_learn-0.13.1-py2.7-linux-i686.egg/sklearn/neights/neights_centroid.py”,第115行
方差=np.数组(np.幂(X-自质心,2))
索引器错误:用作索引的数组必须是整数(或布尔)类型
代码如下:

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())
distancemetric=['euclidean','l2']
地铁公司的距离度量:
对于[None]中的shrkthrshld:
#shrkthrshld=0

#而(shrkthrshld我在使用Pystruct
Pystruct.learners.OneSlackSSVM时遇到了类似的问题


这是因为我的训练标签是浮点数,而不是整数。在我的例子中,这是因为我用np.ones初始化了标签,而没有指定dtype=np.int8。希望这能有所帮助。

通常情况下,索引数组的创建方式应该是明确的
整数
类型,但在传递空列表的情况下,成为默认的
浮点值
,程序员可能不会考虑这种情况。例如:

>>> 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

有时数据是整数,每件事都是正确的,但这是因为其中一个数据系列是空数组,所以可以使用以下条件:

if len(X_train.todense())> 0:

y\u train
的值是多少?空数组不会抛出错误-它们只返回一个空数组