• TensorFlow手动加载数据集(以mnist为例)


    在进行Mnist手写识别的项目中,出现了Mnist数据集下载出错的问题,报出以下错误:
    Exception: URL fetch failure on https://s3.amazonaws.com/img-datasets/mnist.npz: None – [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

    MNIST数据集包含四个gz文件。这些文件分别包含训练集图像、训练集标签、测试集图像和测试集标签。

    你可以从官方网站下载这些文件。以下是MNIST数据集的官方网站链接:http://yann.lecun.com/exdb/mnist/

    在该网站上,你可以找到以下四个文件:

    • train-images-idx3-ubyte.gz:训练集图像
    • train-labels-idx1-ubyte.gz:训练集标签
    • t10k-images-idx3-ubyte.gz:测试集图像
    • t10k-labels-idx1-ubyte.gz:测试集标签
      你可以下载这些文件,并将它们保存在本地路径中。然后,你可以使用适当的库(如gzip和numpy)来解压和加载这些文件,以获取MNIST数据集的特征和标签。

    以下是一个示例代码,演示如何加载MNIST数据集的图像和标签:

    import gzip
    import numpy as np
    
    def load_mnist_images(path):
        with gzip.open(path, 'rb') as f:
            # 跳过文件头
            f.read(16)
            # 读取图像数据
            buf = f.read()
            # 将字节数据转换为numpy数组
            data = np.frombuffer(buf, dtype=np.uint8)
            # 重新整形为图像数组
            data = data.reshape(-1, 28, 28)
            return data
    
    def load_mnist_labels(path):
        with gzip.open(path, 'rb') as f:
            # 跳过文件头
            f.read(8)
            # 读取标签数据
            buf = f.read()
            # 将字节数据转换为numpy数组
            labels = np.frombuffer(buf, dtype=np.uint8)
            return labels
    
    # 指定文件路径
    train_images_path = 'path_to_train-images-idx3-ubyte.gz'
    train_labels_path = 'path_to_train-labels-idx1-ubyte.gz'
    test_images_path = 'path_to_t10k-images-idx3-ubyte.gz'
    test_labels_path = 'path_to_t10k-labels-idx1-ubyte.gz'
    
    # 加载训练集图像和标签
    train_images = load_mnist_images(train_images_path)
    train_labels = load_mnist_labels(train_labels_path)
    
    # 加载测试集图像和标签
    test_images = load_mnist_images(test_images_path)
    test_labels = load_mnist_labels(test_labels_path)
    
    # 打印数据集信息
    print("训练集样本数量:", train_images.shape[0])
    print("测试集样本数量:", test_images.shape[0])
    print("输入特征形状:", train_images[0].shape)
    print("标签形状:", train_labels.shape)
    
    # 进行模型训练和评估的代码可以继续编写...
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
  • 相关阅读:
    嵌入式linux sqlite3读写demo
    从地址中如何提取或者识别街道?支持模糊地址
    大数据挖掘决策树计算过程
    局域网远程yum源制做
    GeoServer+Postgis发布存储在Postgis中的栅格数据
    Qt(C++)面试题 | 精选25项常问
    Qt第八章:安装Qt Creator教程
    四川翌加:横拍和竖拍抖音短视频哪个更好
    IM6ULL学习总结(四-七-1)输入系统应用编程
    c++ 小游戏(2种)
  • 原文地址:https://blog.csdn.net/baidu_39621090/article/details/133877873