简体   繁体   English

Python TypeError:+不支持的操作数类型:'NoneType'和'str'

[英]Python TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

Hi I have a kNN implementation in Python and I am getting some syntax errors given below. 嗨,我在Python中有一个kNN实现,并且在下面给出了一些语法错误。 The code is given later in the post. 该代码在后面的文章中给出。

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'

I am running Python 3. Can anyone tell me what to edit in the code so the I get the correct outputs? 我正在运行Python3。有人可以告诉我在代码中进行哪些编辑,以便获得正确的输出吗?

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()

Check your print statements, your attempting to concatenate a print statement with a string. 检查您的打印语句,试图将打印语句与字符串连接起来。

Your print statements should be: 您的打印声明应为:

print("Train set: " + repr(len(trainingSet)))
print("Test set: " + repr(len(testSet)))

Your print statement is incorrect. 您的打印声明不正确。 If you are looking to concatenate strings for printing, you are not doing it correctly. 如果要串联字符串以进行打印,则说明操作不正确。

To take one of your print statements as an example: 以其中一个打印语句为例:

print ("Train set: ") + repr(len(trainingSet))

Firstly, you do not need to take the repr of the length of your trainingSet . 首先,您不需要repr您的trainingSet的长度。 The repr gives the string representation of an object. repr给出了对象的字符串表示形式。 In your case, you are calling len(trainingSet) . 就您而言,您正在调用len(trainingSet) So you are actually getting back an integer. 因此,您实际上是在获取整数。 Technically, you can call repr on this, but there really is no need to do this for what you are trying to achieve with just wanting to show the length of your structure. 从技术上讲,您可以对此进行调用repr ,但是对于您只想显示结构的长度而要实现的目标,确实不需要这样做。

Secondly, You are not setting this to your print statement properly, what you should is put your len(trainingSet) inside your print function and use string formatting. 其次,您没有将其正确设置为打印语句,应将len(trainingSet)放入打印函数中并使用字符串格式。 So, you want this: 因此,您需要这样做:

print ("Train set: {}".format(len(trainingSet)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:+= 不支持的操作数类型:&#39;NoneType&#39; 和 &#39;str&#39; - TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str' TypeError:%支持的操作数类型:&#39;NoneType&#39;和&#39;str&#39; - TypeError: unsupported operand type(s) for %: 'NoneType' and 'str' 类型错误:+ 不支持的操作数类型:“NoneType”和“str” - TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' TypeError:+不支持的操作数类型:“ NoneType”和“ str” - TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' TypeError:&:不支持的操作数类型:“ NoneType”和“ str” - TypeError: unsupported operand type(s) for &: 'NoneType' and 'str' python2 :: TypeError:+:&#39;NoneType&#39;和&#39;str&#39;不受支持的操作数类型 - python2::TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' Python TypeError:+不支持的操作数类型:&#39;NoneType&#39;和&#39;str&#39; - Python TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' Python错误-TypeError:+:&#39;NoneType&#39;和&#39;str&#39;不支持的操作数类型 - Python error - TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' TypeError:+的不支持的操作数类型:在执行python脚本时为“ NoneType”和“ str” - TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' in executing python script CSV阅读器:TypeError:+不支持的操作数类型:“ NoneType”和“ str” - CSV Reader: TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM