【问题标题】:Arrays used as indices must be of integer (or boolean) type用作索引的数组必须是整数(或布尔)类型
【发布时间】:2013-06-30 19:18:40
【问题描述】:

错误是这样的:

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-trainy_train 是 LIBSVM 格式,X 是特征:值对,y_train 是目标/标签,X_train 是 CSR 矩阵格式,shrink_threshold 不支持 CSR 稀疏矩阵,所以我将.todense() 添加到X_train,然后出现此错误,谁能帮我解决这个问题?非常感谢!

【问题讨论】:

  • y_train 的值是多少?

标签: python scikit-learn


【解决方案1】:

我在使用 Pystruct pystruct.learners.OneSlackSSVM 时遇到了类似的问题。

发生这种情况是因为我的训练标签是浮点数,而不是整数。就我而言,这是因为我使用 np.ones 初始化了标签,而没有指定 dtype=np.int8。希望对您有所帮助。

【讨论】:

    【解决方案2】:

    经常发生索引数组在创建时应该明确为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

    【讨论】:

      【解决方案3】:

      有时你的数据是整数,每件事都是正确的,但它发生是因为你的数据系列之一是一个空数组,所以你可以使用这个条件:

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

      【讨论】:

      • 空数组不会抛出错误——它们只是返回一个空数组
      猜你喜欢
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      相关资源
      最近更新 更多