IndexError: 索引过多

2 投票
4 回答
40250 浏览
提问于 2025-04-17 15:23

我正在尝试使用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 

4 个回答

0

获取 r 和 t 的数组索引是错误的。使用下面的代码:

  t = fileCSVTraining[:, 1-0:]  

这样我得到了所需的训练数据,除了预测那一列。

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)

因为预测函数需要一组样本(一个二维数组,格式是 (n_new_samples, n_features)),而不是单个样本。

4

根据评论,我觉得你想要的是:

fileCSVTraining = genfromtxt('TrainingData.csv')

然后,要获取“前6行”,你可以使用

t = fileCSVTraining[:6, :]

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

我怀疑你用数组索引来获取 r 的方式也不太对。

撰写回答