【发布时间】:2015-05-30 15:45:21
【问题描述】:
我正在编写代码来对测试和训练数据矩阵执行 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
当我运行代码时,我在该行遇到类型错误
k_values.append((sortedLabels[x]))
我得到 TypeError: 'Nonetype' object has no attribute 'getitem' 我不确定为什么。
非常感谢任何帮助!
【问题讨论】:
-
labeled.sort()对列表就地进行排序并返回None。所以sortedLables是None。 -
@MartijnPieters 这应该是一个答案:)
-
@Nizil:我已经在 other 问题中以更一般的方式回答了这个问题。 :-)
-
当然可以!!我不敢相信我没有看到,非常感谢大家:)
标签: python list append typeerror knn