【问题标题】:Change size of train and test set from MNIST Dataset从 MNIST 数据集中更改训练集和测试集的大小
【发布时间】:2019-06-16 10:13:01
【问题描述】:

我正在使用 MNIST 和 Keras 来学习 CNN。我正在下载 Keras API 下的 MNIST 手写数字数据库,如下所示。数据集已经分成 60.000 张图像用于训练和 10.000 张图像用于测试(请参阅 Dataset - Keras Documentation)。

from keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()

如何加入训练集和测试集,然后将它们分成 70% 用于训练和 30% 用于测试?

【问题讨论】:

    标签: python keras mnist


    【解决方案1】:

    mnist.load_data 中没有这样的论点。相反,您可以通过numpy 连接数据,然后通过sklearn(或numpy)拆分:

    from keras.datasets import mnist
    import numpy as np
    from sklearn.model_selection import train_test_split
    
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    x = np.concatenate((x_train, x_test))
    y = np.concatenate((y_train, y_test))
    
    train_size = 0.7
    x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=train_size, random_seed=2019)
    

    为重现性设置随机种子。

    通过numpy(如果你不使用sklearn):

    # do the same concatenation
    np.random.seed(2019)
    train_size = 0.7
    index = np.random.rand(len(x)) < train_size  # boolean index
    x_train, x_test = x[index], x[~index]  # index and it's negation
    y_train, y_test = y[index], y[~index]
    

    您将获得大约所需大小的数组(~210xx 而不是 21000 测试大小)。

    mnist.load_data 的源代码看起来这个函数只是从一个已经拆分为 60000 / 10000 测试的 URL 中获取这些数据,所以只有一个连接解决方​​法。

    您还可以从 http://yann.lecun.com/exdb/mnist/ 下载 MNIST 数据集并手动对其进行预处理,然后将其连接起来(根据需要)。但是,据我了解,它被分为 60000 个用于训练的示例和 10000 个用于测试的示例,因为这种拆分用于标准基准测试。

    【讨论】:

    • 感谢您的回答。我知道拆分是标准的,但我正在为一个大学项目工作,该项目需要使用不同大小的训练/测试集来查看这种变化对结果的影响。
    猜你喜欢
    • 2013-06-18
    • 2015-04-21
    • 2016-06-08
    • 2012-07-06
    • 1970-01-01
    • 2022-10-23
    • 2019-01-14
    • 2017-11-01
    • 2020-01-21
    相关资源
    最近更新 更多