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数据集的图像和标签:

python 复制代码
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)

# 进行模型训练和评估的代码可以继续编写...
相关推荐
code_pgf2 分钟前
Jetson Orin NX 16G设备上配置AI服务自动启动的方案,包括Ollama、llama-server和OpenClaw Gateway三个组件
数据库·人工智能·安全·gateway·边缘计算·llama
前端付豪4 分钟前
实现 AI 回复支持 Markdown 渲染
前端·人工智能·markdown
数智大号5 分钟前
北京InfoComm China 2026高峰会议紧密契合国家“十五五”规划,人工智能引领科技未
人工智能
码路飞5 分钟前
Mistral Small 4 上手实测:119B 参数只激活 6B,开源模型卷到这地步了?
人工智能·llm
用户4815930195916 分钟前
为什么 Claude Code 值得深入学
人工智能
七夜zippoe6 分钟前
边缘计算:Python在IoT中的应用
python·物联网·esp32·边缘计算·iot
2301_818419017 分钟前
Python虚拟环境(venv)完全指南:隔离项目依赖
jvm·数据库·python
蒸汽求职7 分钟前
蒸汽教育求职分享:2026年数据工程师就业优势分析与职业发展路径指南
数据库·人工智能·面试·求职招聘·美国求职
火山引擎开发者社区8 分钟前
重磅发布|Scale‑SWE 构造 10 万级真实 SWE 数据集,火山引擎沙箱底座重塑代码智能体训练
人工智能
MgArcher8 分钟前
python基础:使用list和tuple
python