在练习机器学习的时候遇到了一个小问题,花费了挺长时间,故记录下
源码
IndexError: too many indices for array
注意,一维数组的切片是list[x],二维数组的切片是list[x,y],搞错了就会报错。
·
注意,一维数组的切片是list[x],二维数组的切片是list[x,y],搞错了就会报错。
from numpy import *
def file2matrix(filename):
fr = open(filename)
arrayOLines = fr.readlines()
numberOFLines = len(arrayOLines)
returnMat = zeros(numberOFLines)
classLabelVector = []
index = 0
for line in arrayOLines:
line = line.strip()
listFromLine = line.split('\t')
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index+=1
return returnMat, classLabelVector
file2matrix('datingTestSet2.txt')
运行报错:IndexError: too many indices for array
在百度上找了半天错误,咋就索引太多了呢,索引多还不行了?然后在stackoverflow上看到了另一个人也遇到了这个错误,有大神在下面评论
You are getting this error because you are making target array ‘y’ 2-D which is actually needed to be 1-D to pass in cross validation function.
These two cases are different:1. y=numpy.zeros(shape=(len(list),1))
2. y=numpy.zeros(shape=(len(list)))
果然问题在这里,初始化数组是一维的,应该是二维的(照着代码打都会错,汗!)将returnMat = zeros(numberOFLines)
改成returnMat = zeros((numberOFLines,3))
就OK了
更多推荐
所有评论(0)