tensorflow开发 之数字识别文件读取


点击查看 (人工智能) 系列文章


mnist文件读取

  目前 tenserflow 2.0版本已经取消了examples的模块,当然,还可以自己下载后将整个文件夹放在tensorflow目录下继续使用,不过官方已经推荐了新的用法,还是建议直接用新用法。

1.0 旧用法报错

在这里插入图片描述

2.0 推荐用法

在这里插入图片描述

从执行结果看到:

  1. tensorflow版本是2.6.0
  2. 从storage.googleapis.com下载文件用时2s
  3. 下载的训练数据有6万个,测试数据有1万个;其中训练图片样本为28*28数据,标签为1维数值
读取函数解析
tf.kera.datasets.mnist.load_data(path='')
参数Path:
	本地缓存Mnist数据集(mnist.npz)的相对路径(~/.kera/datasets/),如果windows系统,则可能是(C:\\Users\\用户名\\)
返回值:
	Numpy数组元组,具体为“(x_train, y_train),(x_test, y_test)”,即从前到后依次为训练集的图片和标签,测试集的图片和标签
下载本地缓存

在这里插入图片描述

数据显示

将前20个数据,使用4*5的矩阵显示出来:
在这里插入图片描述

源码

# author: suoxd123@126.com
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('./mnist/dataset')
# author: suoxd123@126.com
import tensorflow as tf

print(tf.__version__)
# 读取数据
mnist = tf.keras.datasets.mnist
(imgTrain, labelTrain),(imgTest, labelTest) = mnist.load_data(path='mnist.npz')

# 显示数据基本信息
print(imgTrain.shape, imgTest.shape)
print(labelTrain.shape, labelTest.shape)
# author: suoxd123@126.com
import matplotlib.pyplot as plt

# 显示图片
fig = plt.figure()
for i in range(20):
    plt.subplot(4,5, i+1)
    plt.tight_layout()  #自动适配子图尺寸
    plt.imshow(imgTrain[i], cmap='binary')
    plt.title("Label:{}".format(labelTrain[i]))
    plt.xticks([])  # 删除坐标标记
    plt.yticks([])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个使用TensorFlow实现手写数字识别的示例代码: ```python import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 读取MNIST数据集 mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 构建模型 x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b) y_ = tf.placeholder(tf.float32, [None, 10]) # 定义损失函数和优化器 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # 训练模型 sess = tf.InteractiveSession() tf.global_variables_initializer().run() for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # 评估模型 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) ``` 该代码使用了一个简单的全连接神经网络模型,输入为784维的向量,输出为10维的向量(对应10个数字)。使用交叉熵作为损失函数,使用批量梯度下降算法进行优化。在训练1000个epoch后,打印出在测试集上的精度。 当然,这只是一个简单的示例,实际上可以使用更复杂的神经网络结构,加入正则化、dropout等技巧来提高模型的性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

放羊郎

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

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

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

打赏作者

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

抵扣说明:

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

余额充值