python - 如何在附加数据上训练 (k-NN) 模型(为了绘制学习曲线)

标签 python performance machine-learning scikit-learn knn

我正在玩MNIST database为此,我想绘制各种学习算法的学习曲线。为了解决这个问题,让我们考虑一下 k-NN 算法。

我使用 mnist 包导入数据,并将其转换为 numpy.ndarray 对象。

import numpy as np
import matplotlib.pyplot as plt
from mnist import MNIST
mndata = MNIST('./data')

images_train, labels_train = mndata.load_training()
images_test, labels_test = mndata.load_testing()

labels_train = labels_train.tolist()
labels_test = labels_test.tolist()

X_train = np.array(images_train)
y_train = np.array(labels_train)
X_test = np.array(images_test)
y_test = np.array(labels_test)

但是,它在训练集中包含 60.000 个示例,因此对于我的计算机来说太多了。我想绘制学习曲线,看看进一步的培训是否有意义。

import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier

start_time = time.time()

training_range = range(500, 1500, 100)
test_size = 1000

training_accuracy = []
test_accuracy = []

for train_size in training_range:
    X_train_small = X_train[:train_size]
    y_train_small = y_train[:train_size]
    X_test_small = X_test[:test_size]
    y_test_small = y_test[:test_size]

    clf = KNeighborsClassifier(n_neighbors=3)
    clf.fit(X_train_small, y_train_small)
    training_accuracy.append(clf.score(X_train_small, y_train_small))
    test_accuracy.append(clf.score(X_test_small, y_test_small))

plt.plot(training_range, training_accuracy, label="training accuracy")
plt.plot(training_range, test_accuracy, label="test accuracy")
plt.ylabel("Accuracy")
plt.xlabel("Training size")
plt.title("Learning curve")
plt.legend()
plt.show()

输出:

enter image description here

绘制这个简单的图表需要一分多钟的时间,它最好地显示了仅对 1500 个元素进行训练的准确性。

主要问题是程序多次运行 clf.fit(X_train_small, y_train_small) 并每次都从头开始重新计算所有内容。

Question. Is there a way to preserve already learned data and just "train up" on the new one?

我想答案对于任意算法来说都不是,但 k-NN 的工作方式原则上应该是可能的(这只是我的观点)。

最佳答案

正如 Vivek Kumar 所说,只有能够调用 partial_fit() 方法的算法才能实现您想要的功能,例如 linear_model.Perceptronlinear_model。 SGDClassifier

为什么 KNN 没有部分拟合?因为当你想到 KNN 时,它在训练阶段没有任何努力,它是一种惰性算法。所有的努力都花在测试阶段。它需要完整的数据集来决定。由于它需要完整的训练集才能做出决定,因此一次给出一个训练数据是没有意义的。

关于python - 如何在附加数据上训练 (k-NN) 模型(为了绘制学习曲线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49942452/

相关文章:

java - Java 中创建了多少个 String 对象?

python-3.x - 通过Wit.ai运行mysql查询

python - ssh/登录到网络上的构建服务器并注销

python - 对大型 scipy 稀疏矩阵进行快速列访问

performance - Erlang 性能 - 参数传递/内联

machine-learning - 如何在svm(scikit)中提取和传输学习参数?

python - tensorflow.contrib.learn.ExportStrategy 示例

python - 当我的 friend 尝试使用我的可执行文件时,如何避免出现 "Windows protected your PC"问题?

python - Python中的多线程诅咒输出

python - python : None type given, 中递归函数的返回和赋值需要一个 int 值