需求:手写数字识别
数据集:tensorflow自带数据集(下载四个.gz并解压)
流程:1、准备数据;2、数据占位符;3、建立模型,随机初始化权重和偏置;4、计算平均损失值;5、梯度下降优化。
code:
#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# Author : rusi_
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.slim.python.slim.nets.inception_v3 import inception_v3_base
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def minst_test():
"""
单层网络,手写数字预测
:return:
"""
# 获取数据
mnist = input_data.read_data_sets(r"E:\mac_obj_file\mnist", one_hot=True)
# 建立数据占位符
with tf.variable_scope("data"):
x = tf.placeholder(tf.float32, [None, 784])
y_true = tf.placeholder(tf.float32, [None, 10])
# 建立一个简单的全连接层神经网络模型
with tf.variable_scope("model"):
w = tf.Variable(tf.random_normal([784, 10], mean=0, stddev=1.0), name="w")
b = tf.Variable(tf.constant(0.0, shape=[10]))
y_predict = tf.matmul(x, w) + b
# 损失函数
with tf.variable_scope("loss"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))
# 优化:梯度下降
with tf.variable_scope("optimizer"):
train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# 计算准确率
with tf.variable_scope("accuracy"):
# one-hot
equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))
accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))
# 事件可视化
# 收集变量
tf.summary.scalar("losses", loss)
tf.summary.scalar("acc", accuracy)
tf.summary.histogram("weightes", w)
tf.summary.histogram("biases", b)
# 合并变量的op
merged = tf.summary.merge_all()
# 保存模型的实例
saver = tf.train.Saver()
# 定义一个初始化变量的op
init_op = tf.global_variables_initializer()
# run
with tf.Session() as sess:
sess.run(init_op)
# 写手
file_writer = tf.summary.FileWriter("./obj_file/minst_test/", graph=sess.graph)
# 打开保存了的模型
if os.path.exists("./ckpt/minst_test/checkpoint"):
saver.restore(sess, "./ckpt/minst_test/model")
for i in range(2000):
mnist_x, mnist_y = mnist.train.next_batch(50)
sess.run(train_op, feed_dict={x: mnist_x, y_true: mnist_y})
# 写入
summary_ = sess.run(merged, feed_dict={x: mnist_x, y_true: mnist_y})
file_writer.add_summary(summary_, i)
print(f"训练第:{i}步,准确率:{sess.run(accuracy, feed_dict={x: mnist_x, y_true: mnist_y})}")
# 保存模型
saver.save(sess, "./ckpt/minst_test/model")
if __name__ == '__main__':
minst_test()
# tensorboard --logdir="./obj_file/minst_test/" 查看优化状况