【问题标题】:KNN doesn't classify correctlyKNN 没有正确分类
【发布时间】:2018-07-26 14:46:17
【问题描述】:

我正在 python 中构建自己的 1-NN 分类器,因为我需要在某些操作中达到最大速度来测试它,因为我想在遗传算法中使用它,并且每毫秒对速度很重要。

我正在尝试使用 numpy 在我的 KNN 类中实现一个留一法测试,但我通过该测试获得了大约 50% 的成功率。我尝试使用相同的 scikit learn knn 并留下大约 97% 的成功率。

这是我的 KNN 课程:

class KNN(object):
"""Documentation for KNK-clasifier"""
def __init__(self):
    super(KNN, self).__init__()
    # self.args = args

def fit(self, entrenamiento, clases):
    self.entrenamiento = np.asarray(entrenamiento)
    self.n_examples = len(self.entrenamiento)
    self.n_features = len(self.entrenamiento[1])
    self.clases = np.asarray(clases)
    self.createDistenceMatrix()

def createDistenceMatrix(self):
    self.distances = np.zeros([len(self.entrenamiento),
                               len(self.entrenamiento),
                               len(self.entrenamiento[1])])
    for i in range(self.n_examples):
        for j in range(self.n_examples):
            if i is not j:
                self.distances[i][j] = self.distance(self.entrenamiento[i],
                                                     self.entrenamiento[j])
            else:
                self.distances[i][j] = np.full(len(self.entrenamiento[1]),
                                               10000.0)

def distance(self, x, y):
    return (x-y)*(x-y)

def predict(self, test, pesos=None):
    dist = 100000
    class_index = 0
    for i in range(self.n_examples):
        aux = self.distance(self.entrenamiento[i], test)
        if pesos is not None:
            aux = pesos*aux

        if aux < dist:
            dist = aux
            class_index = i

    return self.clases[class_index]

def leave_one_out(self, pesos=None):
    # DONE: solo tengo que buscar el minimo de cada columna
    dist = np.zeros(self.n_examples)
    aciertos = 0
    for i in range(self.n_examples):
        for j in range(self.n_examples):
            if pesos is not None:
                dist[i] = np.linalg.norm(
                    np.multiply(self.distances[i][j], pesos))
            else:
                dist[i] = np.linalg.norm(self.distances[i][j])

        if self.clases[i] == self.clases[np.argmin(dist)]:
            aciertos = aciertos + 1

    return 100*(aciertos/self.n_examples)

createDistanceMatrix 为所有特征预先计算所有可能的 x,y 距离并将其保存到向量中。这个向量将乘以一个重量向量。这个向量代表我试图解决的特征权重学习问题。我花了两天时间试图找出错误在哪里,但我可以找到,但是我的分类器并没有给我很好的分类百分比。

对于 sklearn knn,这是我正在测试的遗漏:

    aciertos = 0
    knn = neighbors.KNeighborsClassifier(n_neighbors=1)
    start = time.clock()
    for i in range(len(train)):
        knn.fit(train[1:], cls[1:])
        if knn.predict(train[0])[0] == cls[0]:
            aciertos = aciertos + 1
        train[0], train[-1] = train[-1], train[0]
        cls[0], cls[-1] = cls[-1], cls[0]
    end = time.clock()
    print(str(end - start) + " segundos")
    print(str(100*(aciertos/len(train))))

使用我自己的分类器的相同代码返回相似的成功百分比。

【问题讨论】:

  • 你为什么要实施已经实施的?使用带有快速 python 解释器的 sklearn。
  • 快速python解释器是什么意思?我在想我的 knn 实现在我的特定测试中会更快,那么你建议如何做遗漏呢? @JuanAntonioGomezMoriano

标签: python-3.x numpy genetic-algorithm knn


【解决方案1】:

我不知道你是否解决了你的问题,但你的距离看起来不对?

这是来自斯坦福 cs231n 的算法:

【讨论】:

    猜你喜欢
    • 2019-01-27
    • 2012-11-17
    • 2016-06-16
    • 2020-01-14
    • 2013-03-08
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多