使用K邻近算法改进约会网站配对效果——文本文件解析到numpy,问题及解决记录
def file2matrix(filename):
#打开文件并得到文件行数
fr = open(filename)
arrayOLines = fr.readlines() # 一次读取整个文件,自动将文件内容分析成一个行的列表
numberOfLines = len(arrayOLines) # get the number of lines in the file
#创建返回的numPy矩阵
returnMat = np.zeros((numberOfLines,3)) # 文件有几行就是几行,设置为3列(可调)
classLabelVector = [] # 存储位置
fr = open(filename)
index = 0
#解析文件数据到列表
for line in fr.readlines():
line = line.strip() # 使用函数line.strip()截取掉所有的回车字符(去掉首尾空格)
listFromLine = line.split('\t') # 使用tab字符\t将上一步得到的整行数据分割成一个元素列表
returnMat[index,:] = listFromLine[0:3] # #前3个列表元素是所需特征,取出填充returnMat
#是1 or 2 or 3,填入得到分类标签向量
classLabelVector.append(int(listFromLine[-1])) #使用索引值-1表示列表中的最后一列元素,明确列表中存储的元素值为整型int(否则python语言默认字符串处理)
index += 1 # 继续迭代
return returnMat,classLabelVector
datingDataMat,datingLabels = file2matrix('./datingTestSet.txt')
1. 运行classLabelVector.append(int(listFromLine[-1]))时报错。报错:invalid literal for int() with base 10: 'largeDoses'
错误原因:原datingTestSet.txt的第4列为字符串型,而非1,2,3类。运行时把字符串转换为整型,出现错误。
修改方案:
方法一:增加一个列表对应:
labels = {'didntLike':1,'smallDoses':2,'largeDoses':3} #新增字典对应
classLabelVector.append(labels[listFromLine[-1]]) int改为labels[]
def file2matrix(filename):
#打开文件并得到文件行数
fr = open(filename)
arrayOLines = fr.readlines() # 一次读取整个文件,自动将文件内容分析成一个行的列表
numberOfLines = len(arrayOLines) # get the number of lines in the file
#创建返回的numPy矩阵
returnMat = np.zeros((numberOfLines,3)) # 文件有几行就是几行,设置为3列(可调)
classLabelVector = [] # 存储位置
fr = open(filename)
index = 0
#解析文件数据到列表
for line in fr.readlines():
line = line.strip() # 使用函数line.strip()截取掉所有的回车字符(去掉首尾空格)
listFromLine = line.split('\t') # 使用tab字符\t将上一步得到的整行数据分割成一个元素列表
returnMat[index,:] = listFromLine[0:3] # 把分割好的数据放至数据集,其中index是该样本数据的下标,就是放到第几行
#是1 or 2 or 3,填入得到分类标签向量
labels = {'didntLike':1,'smallDoses':2,'largeDoses':3} #新增一个列表对应
classLabelVector.append(labels[listFromLine[-1]]) #去掉int
index += 1 # 继续迭代
return returnMat,classLabelVector
datingDataMat,datingLabels = file2matrix('./datingTestSet.txt')
方法二:定义的函数不变,更换代码示例的数据,导入'datingTestSet2.txt'
datingDataMat,datingLabels = file2matrix('./datingTestSet2.txt')
最终结果:
>>> datingDataMat
array([[ 4.09200000e+04, 8.32697600e+00, 9.53952000e-01],
[ 1.44880000e+04, 7.15346900e+00, 1.67390400e+00],
[ 2.60520000e+04, 1.44187100e+00, 8.05124000e-01],
...,
[ 2.65750000e+04, 1.06501020e+01, 8.66627000e-01],
[ 4.81110000e+04, 9.13452800e+00, 7.28045000e-01],
[ 4.37570000e+04, 7.88260100e+00, 1.33244600e+00]])
>>> datingLabels[:20]
[3, 2, 1, 1, 1, 1, 3, 3, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 2, 3]