TensorFlow2.0——4、前向传播(张量)(mnist数据集)关于手写数字识别

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,)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值