我正在编写代码来对测试和训练数据的矩阵执行k-NN搜索。有三个正在讨论的矩阵:测试数据、训练数据和一列矩阵,它包含训练数据的每一行向量的相应类。我定义了一个函数,当给出距离矩阵的行时,将每个距离与一个类配对,并返回k个最小距离及其类。这里是函数
def closest(distanceRow, classes, k):
labeled = []
for x in range(distanceRow.shape[0]):
# | each element in the row corresponds to the distance between one training vector
# | and one test vector. Each distance is paired with its respective training
# | vector class.
labeled.append((classes[x][0], distanceRow[x]))
# | The list of pairs is sorted based on distance.
sortedLabels = labeled.sort(key=operator.itemgetter(1))
k_values = []
# | k values are then taken from the beginning of the sorted list, giving us our k nearest
# | neighbours and their distance.
for x in range(k):
k_values.append((sortedLabels[x]))
return k_values
当我运行代码时,我在行中得到一个类型错误
^{pr2}$我得到TypeError:“Nonetype”对象没有属性“getitem”,我不知道为什么。在
非常感谢任何帮助!在
list.sort()
不返回任何内容(如here)所示。在必须先调用
your_list.sort()
,然后用your_list
执行操作。在相关问题 更多 >
编程相关推荐