【问题标题】:IndexError: too many indicesIndexError:索引过多
【发布时间】:2013-01-25 11:01:31
【问题描述】:

我正在尝试在 scikit-learn 中使用一种算法来根据大量输入预测输出。我似乎收到了错误“太多索引”返回,但不知道为什么。

CSV 文件训练:

 1.1    0.2 0.1 0   0.12    0.1
 1.4    0.2 0.1 0.1 0.14    0.1
 0.1    0.1 0.1 0   0.26    0.1
 24.5   0.1 0   0.1 0.14    0.1
 0.1    0.1 0.1 0   0.25    0.1

代码:

    fileCSVTraining = genfromtxt('TrainingData.csv', delimiter=',', dtype=None)

    #Define first 6 rows of data as the features
    t = fileCSVTraining[:, 6:]

    #Define which column to put prediction in
    r = fileCSVTraining[:, 0-6:]    
    #Create and train classifier 
    x, y = r, t
    clf = LinearSVC()
    clf = clf.fit(x, y)     
    #New data to predict
    X_new = [1.0, 2.1, 3.0, 2.4, 2.1]
    b = clf.predict(X_new)

错误:

 t = fileCSVTraining[:, 6:]
 IndexError: too many indices 

【问题讨论】:

  • 我认为如果您尝试在二维中索引一维数组,则会发生此错误,但不完全确定
  • 也许不是问题,但您在读取文件时使用delimiter=',',虽然值是用空格分隔的
  • 好像和CSV文件中的小数点有关

标签: python numpy scikit-learn


【解决方案1】:

基于 cmets,我认为你想要:

fileCSVTraining = genfromtxt('TrainingData.csv')

然后,要获得“前 6 行”,您可以使用

t = fileCSVTraining[:6, :]

(我假设您的实际数据文件比您显示的要长。您的示例只有 5 行。)

我怀疑您使用数组索引来获取 r 也是不正确的。

【讨论】:

    【解决方案2】:

    请打印xy变量,您可能会看到为什么数据无效并相应地修复。

    还为最后一行:

    X_new = [1.0, 2.1, 3.0, 2.4, 2.1]
    b = clf.predict(X_new)
    

    应该是:

    X_new = [[1.0, 2.1, 3.0, 2.4, 2.1]]
    b = clf.predict(X_new)
    

    预测期望采样的集合(2D (n_new_samples, n_features)),而不是单个样本。

    【讨论】:

      【解决方案3】:

      获取 r 和 t 的数组索引不正确。使用:

        t = fileCSVTraining[:, 1-0:]  
      

      为我提供所需的训练数据,留下预测列。

      【讨论】:

        【解决方案4】:

        指定 dtype=float 也很重要,因为“无”将允许将整数(如果您的数据中有的话)包含在数组中,这将强制一维数组而不是二维数组。如图所示,索引不适用于一维。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-26
          • 2019-07-17
          • 2020-09-14
          • 2020-04-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多