import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets
import os
'''载入mnist database数据集'''
(x,y),_ =datasets.mnist.load_data()
# 设置x为Tensor的32位float型数据,x的指从[0,255]=>[0,1],目的就是类似于one_hot操作,见下注释
x=tf.convert_to_tensor(x,dtype=tf.float32)/255.
# 设置y为tensor的32位int型数据
y=tf.convert_to_tensor(y,dtype=tf.int32)
# x的格式为[图片数量(个),height,width]=[60k,28,28]
# y的格式为[60k]
print(x.shape,y.shape,x.dtype,y.dtype)
# 输出结果(60000, 28, 28) (60000,) <dtype: 'float32'> <dtype: 'int32'>
'''
tf.reduce_min 函数
reduce_min(
input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None
)
'''
print(tf.reduce_min(x),tf.reduce_max(x))
print(tf.reduce_min(y),tf.reduce_max(y))
'''输出结果
tf.Tensor(0.0, shape=(), dtype=float32) tf.Tensor(255.0, shape=(), dtype=float32)
******[0-255]表示一张图片由256个样本片组成
tf.Tensor(0, shape=(), dtype=int32) tf.Tensor(9, shape=(), dtype=int32)
******[0-9]表示手写数字0-9总共10种。
'''
'''
iter() 函数
>>>lst = [1, 2, 3]
>>> for i in iter(lst):
... print(i)
...
1
2
3'''
'''
next() 函数
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration就退出循环
break
'''
# 创建数据集batch (以128个为准),方便取样
# 数据集对象实例化:
train_db=tf.data.Dataset.from_tensor_slices((x,y)).batch(128)
#iter() 函数用来生成迭代器。
train_iter=iter(train_db)
# next()返回迭代器的下一个项目。
sample=next(train_iter)
print('batch:', sample[0].shape, sample[1].shape)
# 输出结果 batch: (128, 28, 28) (128,)
TensorFlow2.0——4、前向传播(张量)(mnist数据集)关于手写数字识别
最新推荐文章于 2021-04-18 14:38:50 发布