Tensorflow学习第11篇-全连接网络 2020-10-31

一、前言

本文主要是对另一个博主的博客以及代码进行解读:https://blog.csdn.net/LQ_qing/article/details/99623008

具体的案例就是手写全连接MNIST数据集

具体原理的解读这边就不开展了,可以直接查看上面的网址。

二、代码部分解读

以下代码是原博主的代码,本文仅添加部分注释

import  tensorflow as tf
from    tensorflow import keras
from    tensorflow.keras import datasets
import  os
 
# 设置后台打印日志等级 避免后台打印一些无用的信息
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 
# 利用Tensorflow2中的接口加载mnist数据集
(x, y), (x_test, y_test) = datasets.mnist.load_data()
 
# 对数据进行预处理:返回x,y
def preprocess(x, y):
    x = tf.cast(x, dtype=tf.float32) / 255.    # 类型转换,归一化处理
    y = tf.cast(y, dtype=tf.int32)            # 
    return x,y
 
# 构建dataset对象,方便对数据的打乱,批处理等超操作
# tf.data.Dataset.from_tensor_slices((x,y)):多个特征对应一个标签,组合成一个tuple
train_db = tf.data.Dataset.from_tensor_slices((x,y)).shuffle(1000).batch(128)  # shuffle函数:该函数的作用就是打乱数据顺序
train_db = train_db.map(preprocess) # 对每个批处理(128个数据)归一化处理
test_db = tf.data.Dataset.from_tensor_slices((x_test,y_test)).batch(128)     # batch函数:主要是对数据分组:每组128个数据
test_db = test_db.map(preprocess)   # 对每个批处理(128个数据)归一化处理
 
# 构建模型中会用到的权重
w1 = tf.Variable(tf.random.truncated_normal([784, 256], stddev=0.1))  # stddev:截断前正态分布的标准偏差,默认为1.0
b1 = tf.Variable(tf.zeros([256]))   # tf.Variable(initializer,name),参数initializer是初始化参数,name是可自定义的变量名称
w2 = tf.Variable(tf.random.truncated_normal([256, 128], stddev=0.1))  # [256, 128] :shape
b2 = tf.Variable(tf.zeros([128]))    # 128个0.
w3 = tf.Variable(tf.random.truncated_normal([128, 10], stddev=0.1)) #详解 https://blog.csdn.net/qq_39894692/article/details/101635922
b3 = tf.Variable(tf.zeros([10]))

# 学习率
lr = 1e-3
 
# epoch表示整个训练集循环的次数 这里循环100次
for epoch in range(100):
    # step表示当前训练到了第几个Batch
    for step, (x, y) in enumerate(train_db):
        # 把训练集128个数据全部进行打平操作
        x = tf.reshape(x, [-1, 28*28])
        # 构建模型并计算梯度
        with tf.GradientTape() as tape: # tf.Variable
            # 三层非线性模型搭建
            h1 = x@w1 + tf.broadcast_to(b1, [x.shape[0], 256])  # tf.broadcast_to: 将b1的[256,]由转换成128*256
            h1 = tf.nn.relu(h1)
            h2 = h1@w2 + b2            # 此部分的b2为什么不适用tf.broadcast_to函数?
            h2 = tf.nn.relu(h2)
            out = h2@w3 + b3
            # 可以看到,由于每个层都要连接:出现了很多的参数,参数个数较多
 
            # 把标签转化成one_hot编码 
            y_onehot = tf.one_hot(y, depth=10) # 详解:https://blog.csdn.net/fang_chuan/article/details/88559930
 
            # 计算MSE
            loss = tf.square(y_onehot - out)  #tf.square()是对a里的每一个元素求平方
            loss = tf.reduce_mean(loss)   # 计算所有元素的均值;
 
        # 计算梯度
        grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3]) # 对loss求导,w1, b1, w2, b2, w3, b3都是偏导
        
        # w = w - lr * w_grad
        # 利用上述公式进行权重的更新
        w1.assign_sub(lr * grads[0])
        b1.assign_sub(lr * grads[1])
        w2.assign_sub(lr * grads[2])
        b2.assign_sub(lr * grads[3])
        w3.assign_sub(lr * grads[4])
        b3.assign_sub(lr * grads[5])
 
        # 每训练100个Batch 打印一下当前的loss
        if step % 100 == 0:
            print(epoch, step, 'loss:', float(loss))
 
    # 每训练完一次数据集 测试一下准确率
    total_correct, total_num = 0, 0
    for step, (x,y) in enumerate(test_db):

        x = tf.reshape(x, [-1, 28*28])
 
        h1 = tf.nn.relu(x@w1 + b1)  # tf.nn.relu()函数是将大于0的数保持不变,小于0的数置为0
        h2 = tf.nn.relu(h1@w2 + b2)
        out = h2@w3 +b3
        # 把输出值映射到[0~1]之间
        prob = tf.nn.softmax(out, axis=1)  # 详解: https://blog.csdn.net/wgj99991111/article/details/83586508
        # 获取概率最大值得索引位置
        pred = tf.argmax(prob, axis=1)    # 详解:https://blog.csdn.net/u012300744/article/details/81240580
        pred = tf.cast(pred, dtype=tf.int32)
        
        correct = tf.cast(tf.equal(pred, y), dtype=tf.int32) # 逐个元素进行判断,如果相等就是True,不相等,就是False
        correct = tf.reduce_sum(correct)
        # 获取每一个batch中的正确率和batch大小
        total_correct += int(correct)
        total_num += x.shape[0]
    # 计算总的正确率
    acc = total_correct / total_num
    print('test acc:', acc)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值