深入浅出机器学习MNIST实战(二)

上篇文章采用的是TensorFlow2.0接口函数,这里讲解一下自定义函数。

加载数据

(x, y), (x_test, y_test) = datasets.mnist.load_data()

转换成张量并且将数据归一化到0~1

x = tf.convert_to_tensor(x, dtype=tf.float32) / 255.
y = tf.convert_to_tensor(y, dtype=tf.int32)

x_test = tf.convert_to_tensor(x_test, dtype=tf.float32) / 255.
y_test = tf.convert_to_tensor(y_test, dtype=tf.int32)

构建Dataset数据集

train_db = tf.data.Dataset.from_tensor_slices((x, y))

将顺序打散,避免出现训练按照最开始训练相同的对象

train_db = train_db.shuffle(10000)  #打散训练

设置batch,一次训练多少

train_db = train_db.batch(batch_size)

测试对象只需要构建Dataset,不要打散,和batch

test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
train_iter = iter(train_db) #采样一个 Batch,
sample = next(train_iter)
print ('x_batch_size:',sample[0].shape,  'y_batch_size:', sample[1].shape)

创建三层全连接层的权重和偏置

w1 = tf.Variable(tf.random.truncated_normal([784, 512], stddev=0.1))  # stddev 设置标准差 防止梯度弥散
b1 = tf.Variable(tf.zeros([512]))
w2 = tf.Variable(tf.random.truncated_normal([512, 256], stddev=0.1))
b2 = tf.Variable(tf.zeros([256]))
w3 = tf.Variable(tf.random.truncated_normal([256, 10], stddev=0.1))
b3 = tf.Variable(tf.zeros([10]))

循环迭代

for epoch in range(10):
    for step, (x, y) in enumerate(train_db):

梯度前向计算

with tf.GradientTape() as tape:  # 默认跟踪 tf.Variable 变量,梯度记录器
    # x: [b, 28*28]
    # h1 = x@w1 + b1
    # [b, 784]@[784, 512] + [512] => [b, 512] + [512] => [b, 512] + [b, 512]
    h1 = x@w1+tf.broadcast_to(b1, [x.shape[0], 512])  #broadcast_to  可以省略
    h1 = tf.nn.relu(h1)
    # [b, 512] => [b, 256]
    h2 = h1@w2 + b2
    h2 = tf.nn.relu(h2)
    # [b, 256] => [b, 10]
    out = h2@w3 + b3

计算loss

y_onehot = tf.one_hot(y, depth=10)

# mse = mean(sum(y-out)^2)
# [b, 10]
loss = tf.square(y_onehot - out) #平方
loss = tf.reduce_mean(loss)   #平均值

更新权重和偏置

grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])  #自动求导函数,求出梯度信息
# print(grads)
# w1 = w1 - lr * w1_grad
w1.assign_sub(lr * grads[0])   # 原地更新  继续为 Variable 变量
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])

预处理待识别图片

img = cv2.imread("./bmp_mnist/2.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

rows,cols= img.shape[0:2]

for i  in range(rows):  #反转一下黑白
    for j in range(rows):
        img[i][j] = 255-img[i][j]
        #print(i,j)

img = np.array(img,dtype=float64)  #将剔除尾巴上的shape dtype
img = np.reshape(img,(-1,784))  #将28*28变成1*784
img = tf.keras.utils.normalize(img, axis=1)#归一化处理


x = tf.convert_to_tensor(img, dtype=tf.float32)

识别前向计算

h1 = x @ w1 + b1  # 第一层
h1 = tf.nn.relu(h1)
h2 = h1 @ w2 + b2  # 第二层
h2 = tf.nn.relu(h2)
out = h2 @ w3 + b3  # 输出层

pred = tf.argmax(out, axis=1)  # 选取概率最大的类别
pred = tf.cast(pred, tf.int32)
print(pred)

这里的@代表矩阵相乘

 

上面的梯度前向计算 fit函数已经实现

完整代码

import tensorflow as tf
from tensorflow.keras import datasets
import os ,sys
import cv2
import numpy as np

from numpy import float32,float64

import configparser

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# load minst data
# x: [60k, 28, 28],
# y: [60k]

(x, y), (x_test, y_test) = datasets.mnist.load_data()
# x: [0~255] => [0~1.]
x = tf.convert_to_tensor(x, dtype=tf.float32) / 255.
y = tf.convert_to_tensor(y, dtype=tf.int32)

x_test = tf.convert_to_tensor(x_test, dtype=tf.float32) / 255.
y_test = tf.convert_to_tensor(y_test, dtype=tf.int32)

print (x.shape, y.shape, x.dtype, y.dtype)
print (x_test.shape, y_test.shape, x_test.dtype, y_test.dtype)
print (tf.reduce_min(x), tf.reduce_max(x))
print (tf.reduce_min(y), tf.reduce_max(y))

batch_size = 20
#train_db = tf.data.Dataset.from_tensor_slices((x,y)).batch(batch_size)
train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.shuffle(10000)  #打散训练
train_db = train_db.batch(batch_size)

test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))


train_iter = iter(train_db) #采样一个 Batch,
sample = next(train_iter)
print ('x_batch_size:',sample[0].shape,  'y_batch_size:', sample[1].shape)


# [b, 784] => [b, 512] => [b, 256] => [b, 10]
# w:[in_dim, out_dim], b:[dim_out]

w1 = tf.Variable(tf.random.truncated_normal([784, 512], stddev=0.1))  # stddev 设置标准差 防止梯度弥散
b1 = tf.Variable(tf.zeros([512]))
w2 = tf.Variable(tf.random.truncated_normal([512, 256], stddev=0.1))
b2 = tf.Variable(tf.zeros([256]))
w3 = tf.Variable(tf.random.truncated_normal([256, 10], stddev=0.1))
b3 = tf.Variable(tf.zeros([10]))

lr = 1e-3

for epoch in range(10):
    for step, (x, y) in enumerate(train_db):
        # x:[b, 28, 28]
        # y: [b]

        # [b, 28, 28] => [b, 28*28]
        x = tf.reshape(x, [-1,28*28])

        with tf.GradientTape() as tape:  # 默认跟踪 tf.Variable 变量,梯度记录器
            # x: [b, 28*28]
            # h1 = x@w1 + b1
            # [b, 784]@[784, 512] + [512] => [b, 512] + [512] => [b, 512] + [b, 512]
            h1 = x@w1+tf.broadcast_to(b1, [x.shape[0], 512])  #broadcast_to  可以省略
            h1 = tf.nn.relu(h1)
            # [b, 512] => [b, 256]
            h2 = h1@w2 + b2
            h2 = tf.nn.relu(h2)
            # [b, 256] => [b, 10]
            out = h2@w3 + b3

            # compute loss
            # out: [b, 10]
            # y: [b] => [b, 10]

            y_onehot = tf.one_hot(y, depth=10)

            # mse = mean(sum(y-out)^2)
            # [b, 10]
            loss = tf.square(y_onehot - out) #平方
            loss = tf.reduce_mean(loss)   #平均值

        # compute gradients

        grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3])  #自动求导函数,求出梯度信息
        # print(grads)
        # w1 = w1 - lr * w1_grad
        w1.assign_sub(lr * grads[0])   # 原地更新  继续为 Variable 变量
        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])

        #grads = tape.gradient(loss, model.trainable_variables)
        # w' = w - lr * grad,更新网络参数
        #optimizer.apply_gradients(zip(grads, model.trainable_variables))

        if step%100 == 0:
            print ('epoch:', epoch, 'step:', step, 'loss:', float(loss))


total_correct =0
total =0;

img = cv2.imread("./bmp_mnist/2.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

rows,cols= img.shape[0:2]

for i  in range(rows):  #反转一下黑白
    for j in range(rows):
        img[i][j] = 255-img[i][j]
        #print(i,j)

img = np.array(img,dtype=float64)  #将剔除尾巴上的shape dtype
img = np.reshape(img,(-1,784))  #将28*28变成1*784
img = tf.keras.utils.normalize(img, axis=1)#归一化处理


x = tf.convert_to_tensor(img, dtype=tf.float32)

h1 = x @ w1 + b1  # 第一层
h1 = tf.nn.relu(h1)
h2 = h1 @ w2 + b2  # 第二层
h2 = tf.nn.relu(h2)
out = h2 @ w3 + b3  # 输出层

pred = tf.argmax(out, axis=1)  # 选取概率最大的类别
pred = tf.cast(pred, tf.int32)
print(pred)
sys.exit()

for x, y in test_db: # 对测验集迭代一遍
    x = tf.reshape(x, [-1, 28 * 28])
    total +=1
    print(x.shape,y.shape)

    h1 = x @ w1 + b1 # 第一层
    h1 = tf.nn.relu(h1)
    h2 = h1 @ w2 + b2 # 第二层
    h2 = tf.nn.relu(h2)
    out = h2 @ w3 + b3 # 输出层

    pred = tf.argmax(out, axis=1)  # 选取概率最大的类别
    pred = tf.cast(pred,tf.int32)

    correct = tf.equal(pred, y)  # 比较预测值与真实值

    total_correct += tf.reduce_sum(tf.cast(correct,dtype=tf.int32)).numpy()
    break
print(step, 'Evaluate Acc:', total_correct/total)

 

下篇文章介绍卷积神经网络,提高mnist识别准确度

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页