对自制的数据集进行识别

本文介绍了一种手动读取MNIST手写数据集的方法,并使用TensorFlow搭建了一个简单的神经网络模型进行训练。通过定义函数从原始文件中加载训练和测试数据,再进行归一化等预处理步骤,最后利用模型完成对手写数字的识别任务。
部署运行你感兴趣的模型镜像

例如,我们经常会使用Mnist手写数据集,而我们经常使用的方式就是利用一下代码进行应用:

mnist = tf.keras.datasets.mnist
(x_train,y_train),(x_test,y_test)=mnist.load_data()

这次我们自己写一个函数来对文件进行读取,返回目标值与特征值。

import tensorflow as tf
from PIL import Image
import numpy as np
import os

train_path = 'E:/深度学习下数据/train-images.idx3-ubyte'
train_txt = 'E:/深度学习下数据/train-labels.idx1-ubyte'
x_train_savepath = 'E:/深度学习下数据/mnist_x_train.npy'  # 训练集存储文件
y_train_savepath = 'E:/深度学习下数据/mnist_y_train.npy'  # 训练集标签存储文件

test_path = 'E:/深度学习下数据/t10k-images.idx3-ubyte'
test_txt = 'E:/深度学习下数据/t10k-labels.idx1-ubyte'
x_test_savepath = 'E:/深度学习下数据/mnist_x_test.npy'
y_test_savepath = 'E:/深度学习下数据/mnist_y_test.npy'

def generateds(path, txt):
    f = open(txt, 'r')
    contents = f.readlines()  # 读取文件中所有的行
    f.close()
    x, y_ = [], []  # 建立空列表
    for content in contents:  # 逐行取出
        value = content.split()  # 以空格分开,图片路径为value[0],标签文件为value【1】,存入列表
        image_path = path + value[0]  # 拼出图片的路径和文件名
        img = Image.open(image_path)
        img = np.array(img.convert('L'))  # 图片变为8为宽灰度值的np.array格式
        img = img/255.  # 数据归一化实现预处理
        x.append(img)  # 归一化后的数据贴到列表x
        y_.append(value[1])  # 夫i异化后的标签贴到列表y_
        print("loading:", + content)  # 打印状态提示

        x = np.array(x)  # 变为np.array格式
        y_ = np.array(y_)
        y_ = y_.astype(np.int64)  # 变为64位整数
        return x, y_


if os.path.exists(x_train_savepath) and os.path.exists(y_train_savepath)\
            and os.path.exists(x_test_savepath) and os.path.exists(y_test_savepath):
    print("_______________________Load Datasets_____________________")
    x_train_save = np.load(x_train_savepath)
    y_train = np.load(y_train_savepath)
    x_test_save = np.load(x_test_savepath)
    y_test = np.load(y_test_savepath)

    x_train = np.reshape(x_train_save, (len(x_train_save), 28, 28))
    x_test = np.reshape(x_test_save, len(x_test_save), 28, 28)
else:
    print("_______________________Generate Datasets__________________")
    x_train, y_train = generateds(train_path, train_txt)
    x_test, y_test = generateds(test_path, test_txt)

    print("_______________________Sava Datasets______________________")

    x_train_save = np.reshape(x_train, (len(x_train), -1))
    x_test_save = np.reshape(x_test,(len(x_test), -1))
    np.save(x_train_savepath, x_train_save)
    np.save(y_train_savepath, y_train)
    np.save(x_test_savepath, x_test_save)
    np.save(y_test_savepath, y_test)


model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])

model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)

model.summary()

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI炮灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值