您好我在Python中有一个kNN实现,我得到一些语法错误,如下所示。该代码稍后在帖子中给出。
Traceback (most recent call last):
File "C:\Users\user\Desktop\knn test\knn.py", line 76, in <module>
main()
File "C:\Users\user\Desktop\knn test\knn.py", line 63, in main
print ("Train set: ") + repr(len(trainingSet))
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
我正在运行Python 3.任何人都可以告诉我在代码中编辑什么,以便我得到正确的输出?
import csv
import random
import math
import operator
def loadDataset(filename, split, trainingSet=[] , testSet=[]):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)-1):
for y in range(4):
dataset[x][y] = float(dataset[x][y])
if random.random() < split:
trainingSet.append(dataset[x])
else:
testSet.append(dataset[x])
def euclideanDistance(instance1, instance2, length):
distance = 0
for x in range(length):
distance += pow((instance1[x] - instance2[x]), 2)
return math.sqrt(distance)
def getNeighbors(trainingSet, testInstance, k):
distances = []
length = len(testInstance)-1
for x in range(len(trainingSet)):
dist = euclideanDistance(testInstance, trainingSet[x], length)
distances.append((trainingSet[x], dist))
distances.sort(key=operator.itemgetter(1))
neighbors = []
for x in range(k):
neighbors.append(distances[x][0])
return neighbors
def getResponse(neighbors):
classVotes = {}
for x in range(len(neighbors)):
response = neighbors[x][-1]
if response in classVotes:
classVotes[response] += 1
else:
classVotes[response] = 1
sortedVotes = sorted(classVotes.iteritems(), key=operator.itemgetter(1), reverse=True)
return sortedVotes[0][0]
def getAccuracy(testSet, predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x][-1] == predictions[x]:
correct += 1
return (correct/float(len(testSet))) * 100.0
def main():
# prepare data
trainingSet=[]
testSet=[]
split = 0.67
loadDataset('C:/Users/user/Desktop/knn test/text.txt', split, trainingSet, testSet)
print ("Train set: ") + repr(len(trainingSet))
print ("Test set: ") + repr(len(testSet))
# generate predictions
predictions=[]
k = 3
for x in range(len(testSet)):
neighbors = getNeighbors(trainingSet, testSet[x], k)
result = getResponse(neighbors)
predictions.append(result)
print('> predicted=' + repr(result) + ', actual=' + repr(testSet[x][-1]))
accuracy = getAccuracy(testSet, predictions)
print('Accuracy: ' + repr(accuracy) + '%')
main()
答案 0 :(得分:1)
检查你的print语句,试图用字符串连接print语句。
您的打印声明应为:
print("Train set: " + repr(len(trainingSet)))
print("Test set: " + repr(len(testSet)))
答案 1 :(得分:1)
您的打印声明不正确。如果您希望连接字符串以进行打印,则表明您没有正确执行此操作。
以一个打印语句为例:
print ("Train set: ") + repr(len(trainingSet))
首先,您无需占用repr
长度的trainingSet
。 repr
给出了对象的字符串表示。在您的情况下,您正在呼叫len(trainingSet)
。所以你实际上得到了一个整数。从技术上讲,你可以在这上面调用repr
,但实际上没有必要为你想要显示你的结构长度而想要实现的目标。
其次,您没有正确地将此设置为您的打印语句,您应该将len(trainingSet)
放入打印功能并使用字符串格式。所以,你想要这个:
print ("Train set: {}".format(len(trainingSet)))