Python 此代码是否可以识别MNIST集合?(K-NN方法)

Python 此代码是否可以识别MNIST集合?(K-NN方法),python,machine-learning,scikit-learn,knn,mnist,Python,Machine Learning,Scikit Learn,Knn,Mnist,我不确定下面的代码是否会执行,因为它已经在“计算预测”上停留了很长时间。如果它不起作用,我应该改变什么 import struct import matplotlib.pyplot as plt import numpy as np import os from scipy.special import expit from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_sco

我不确定下面的代码是否会执行,因为它已经在“计算预测”上停留了很长时间。如果它不起作用,我应该改变什么

import struct
import matplotlib.pyplot as plt
import numpy as np
import os
from scipy.special import expit
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score



clf = KNeighborsClassifier()

def load_data():
    with open('train-labels-idx1-ubyte', 'rb') as labels:
        magic, n = struct.unpack('>II', labels.read(8))
        train_labels = np.fromfile(labels, dtype=np.uint8)
    with open('train-images-idx3-ubyte', 'rb') as imgs:
        magic, num, nrows, ncols = struct.unpack('>IIII', imgs.read(16))
        train_images = np.fromfile(imgs, dtype=np.uint8).reshape(num, 784)
    with open('t10k-labels-idx1-ubyte', 'rb') as labels:
        magic, n = struct.unpack('>II', labels.read(8))
        test_labels = np.fromfile(labels, dtype=np.uint8)
    with open('t10k-images-idx3-ubyte', 'rb') as imgs:
        magic, num, nrows, ncols = struct.unpack('>IIII', imgs.read(16))
        test_images = np.fromfile(imgs, dtype=np.uint8).reshape(num, 784)
    return train_images, train_labels, test_images, test_labels


def knn(train_x, train_y, test_x, test_y):
    clf.fit(train_x, train_y)
    print("Compute predictions")
    predicted = clf.predict(test_x)
    print("Accuracy: ", accuracy_score(test_y, predicted))

train_x, train_y, test_x, test_y = load_data()
knn(train_x, train_y, test_x, test_y)
长期以来,它一直停留在“计算预测”上

我建议您在使用整个数据集运行之前,使用一组非常有限的数据来测试一切是否正常。这样可以确保代码是有意义的

一旦测试了代码,就可以安全地继续使用整个数据集进行训练

这样,您就可以很容易地辨别出代码是否因为某些代码问题或仅仅因为数据量而花费了很长时间(也许代码还可以,但您可能会意识到,比如说,对于10个示例,它花费的时间比您愿意/可以等待的时间长,因此您可以相应地进行调整——否则,您正在处理的太多了)


话虽如此,如果代码还可以,但时间太长,作为Soumya,我也建议尝试在Colab上运行。你有一些很好的硬件,最多12小时的会话,还有让你的电脑免费测试其他代码的优势

knn的计算可能需要很长的时间,尤其是当你给它更多的图像时。试着给它输入更少的训练数据点好吧……那么代码是对的吗?看起来它运行得很好谢谢你这么多你可以使用google colab的gpu来更快地预测时间感谢很多代码运行得非常完美,尝试了不同的算法来提高速度,并且工作得非常完美:)@Kiaan1204不客气!如果它帮助并解决了您的问题,请将答案标记为已接受。