python - k 最近邻算法 python

标签 python algorithm

这是我的 k 最近邻算法的代码:

import numpy as np

from EuclideanDistance import EuclideanDistance

dataset = np.loadtxt('C:\Users\Toshiba\Documents\machine learning\RealEstate.csv',      delimiter=',', usecols=(2,3,4,5))
p1 = ()

def normalizeToZscores(data):
    '''Normalizes the variables to z-scores'''
    zScores = list()
for s in data:
    zScore = (s - np.mean(data))/np.std(data)
    zScores.append(zScore) 
    return np.asarray(zScores)

def InOutBudget(data):
    '''Decides whether a particular house is within
    or outside the budget of $153000 and assigns values of 1 and 0 respectively'''
    data2 = list()
    for i in data:
        if (i > 153000): data2.append(0)
        else: data2.append(1) 
    return np.array(data2)

classes = dataset[:,0]
classes = classes.reshape((dataset.shape[0],1))
classes = InOutBudget(classes)

data = dataset[:20,:]
data = normalizeToZscores(data)

p1s = dataset[20:400,:]

def measureDis(data, p1):
    listD = []
    for x in data:
    D = EuclideanDistance(x, p1)
    listD.append(D)
return listD




def most_common(lst):
    '''Finds the most frequently occuring element of a list.
    It will be used to predict a class based on the classification
    of the k-nearest neighbours'''
    return max(set(lst), key=lst.count)

def findKnn(k):
    '''K nearest neighbours algorithm'''
    knns = list()
    errors = list()
    #for i in k:
    for p1 in p1s:
        # Create a list of tuples containing distance and class,
        # Then sort them by shortest distance
        tuples = zip(measureDis(data,p1), classes[20:400])
        tuples = sorted(tuples)
        knn = tuples[:k]
        print knn
        knn = [x[1] for x in knn]
        knn = most_common(knn)
        knns = knns.append(knn)
        print knn
        error = np.abs(knn - p1)
        errors = errors.append(error)
    errorsNum = np.sum(errors)

    return knns

但我不断得到:

Traceback (most recent call last):
File "C:\Users\Toshiba\workspace\assignment5\src\knn2.py", line 76, in <module> knn = findKnn(k)    
File "C:\Users\Toshiba\workspace\assignment5\src\knn2.py", line 64, in findKnn knns = knns.append(knn)
AttributeError: 'NoneType' object has no attribute 'append'

我知道代码很业余,但有人可以帮我解决这个问题吗?

最佳答案

list.append 不返回列表。简单地做:

knns.append(knn)

代替:

knns = knns.append(knn)

关于python - k 最近邻算法 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20052041/

相关文章:

python - 如何确定由网格单元组成的任意形状的角/顶点单元

algorithm - 位排列的通用算法

garbage-collection - 您如何管理临时目录以确保在程序关闭时将其删除?

python - cv2.imwrite() 系统错误 : <built-in function imwrite> returned NULL without setting an error

python - “phantomjs”可执行文件可能具有错误的权限

javascript - 给出给定字符串数组所需的最小笔画的函数

C字符串转换

algorithm - 算法运行时间T(n)

python - 如何删除列表列表中的最后一个元素?

python - vim:.vimrc 无法正确加载 python 文件