Keras (一): Fashion MNIST

本文介绍了使用Keras在Fashion MNIST数据集上构建的CNN模型,通过手动下载数据并解析,实现了91.99%的测试集准确率和92.24%的训练集准确率,利用Dropout层有效防止了过拟合。对比了不同网络结构对模型性能的影响,强调了CNN、Pooling层和Dropout层在图像识别中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备工作

我自己在学的时候发现使用 tensorflow 提供的 API 来下载数据集时没有网速 (不管有没有梯子), 所以我决定手动下载数据集然后再自行解析.

工程目录

  • fashion
    • fashion.py
    • mnilist_loader.py
    • data
      • fashion
        • t10k-images-idx3-ubyte.gz
        • t10k-labels-idx1-ubyte.gz
        • train-labels-idx1-ubyte.gz
        • train-images-idx3-ubyte.gz

数据文件可在 MINIST github 上自行下载

mnist_loader.py

用来读取并解析数据文件

def load_mnist(path, kind='train'):
    import os
    import gzip
    import numpy as np

    """Load MNIST data from `path`"""
    labels_path = os.path.join(path,
                               '%s-labels-idx1-ubyte.gz'
                               % kind)
    images_path = os.path.join(path,
                               '%s-images-idx3-ubyte.gz'
                               % kind)

    with gzip.open(labels_path, 'rb') as lbpath:
        labels = np.frombuffer(lbpath.read(), dtype=np.uint8,
                               offset=8)

    with gzip.open(images_path, 'rb') as imgpath:
        images = np.frombuffer(imgpath.read(), dtype=np.uint8,
                               offset=16).reshape(len(labels), 784)

    return images, labels

我的模型

fashion.py

import tensorflow as tf 
import mnist_loader as ml 
from tensorflow import keras
import numpy as np 


x_train, y_train = ml.load_mnist('data/fashion', 'train')
x_test, y_test = ml.load_mnist('data/fashion', 't10k')

x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)

x_train = x_train / 255.0
x_test = x_test / 255.0

model = keras.Sequential([
    keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    keras.layers.MaxPooling2D((2, 2)),
    keras.layers.Conv2D(64, (3, 3), activation='relu'),
    keras.layers.Flatten(),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(64, activation='relu'),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(10
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值