KNN算法:“ int”对象不可下标

时间:2019-03-06 15:47:21

标签: python python-3.x knn

我已经有一段时间没有使用python了,很难找到解决该问题的方法。 我尝试更改欧几里得距离函数的方程式,但效果不好。也许我看不到解决问题的方法。

这是我的代码:

from math import sqrt
import csv
from random import shuffle
import numpy as np
import numpy
import matplotlib.pyplot as plt
import operator
import math


iris = datasets.load_iris() 

X = iris.data
y = iris.target



def euclideanDistance(id1, id2):
    for x in range(len(id1)-1):
        dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
    return dist

data1 = [2, 2, 2, 'a']
data2 = [4, 4, 4, 'b']
distance = euclideanDistance(data1, data2)
print(distance)

def mykNN(X, y, x_):
    distance = []
    neighbour = []

    for i in range(len(X)):
        d = euclideanDistance(X[i], x_ )
        distance.append((X[i], d))
    distance.sort(key=operator.itemgetter(1))

    for r in range(k):
        options.append(distance[r][0])
    options = neighbour
    return neighbour

k=3

y_ = mykNN(X, y,k)
print(y_)

无论我如何更改我的功能,都会出现此错误。

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-85-2a5bfc4a796d> in <module>
     42 k=3
     43 
---> 44 y_ = mykNN(X, y,k)
     45 print(y_)
     46 

<ipython-input-85-2a5bfc4a796d> in mykNN(X, y, x_)
     31 
     32     for i in range(len(X)):
---> 33         d = euclideanDistance(X[i], x_ )
     34         distance.append((X[i], d))
     35     distance.sort(key=operator.itemgetter(1))

<ipython-input-85-2a5bfc4a796d> in euclideanDistance(id1, id2)
     18 def euclideanDistance(id1, id2):
     19     for x in range(len(id1)-1):
---> 20         dist = np.sqrt(np.sum((int(id2[x]) - int(id1[x]))**2))
     21     return dist
     22 

TypeError: 'int' object is not subscriptable

感谢您的回应,这一直困扰着我。

谢谢。

1 个答案:

答案 0 :(得分:1)

好吧,错误告诉您在euclideanDistance()中,id1id2(或两者)都是整数,因为这是您要为其索引的两个标识符线。要遵循以下步骤:

  • 您设置了k = 3
  • 您致电mykNN(X, y, k),这意味着在mykNN()中,x_ == 3
  • 您致电euclideanDistance(X[i], x_),这意味着在euclideanDistance()中,id2 == 3
  • 您尝试在指示的行上为id2编制索引。整数不能被索引,因此是例外。

这就是导致您出错的原因。由于我不确定您的代码到底在做什么,因此我无法直接推荐修复程序。