卷积神经网络数据识别

代码实现:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os

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

# 定义一个初始化权重的函数
def weight_varibles(shape):
    w = tf.Variable(tf.random_normal(shape=shape,mean=0.0,stddev=1.0))
    return w

#定义一个初始化偏置的函数
def bias_varibles(shape):
    b = tf.Variable(tf.constant(0.0,shape=shape))
    return b

def model():
    """
    自定义的卷积模型
    :return:
    """
    # 1.准备数据的占位符 x [None,784] y_true[None,10]
    with tf.variable_scope("data"):
        x = tf.placeholder(tf.float32, [None,784])
        y_true = tf.placeholder(tf.int32, [None,10])

    # 2.一卷积层 卷积 激活 池化  5,5,1,32个     激活 tf.nn.relu  池化
    with tf.variable_scope("conv1"):
        # 随机初始化权重
        w_conv1 = weight_varibles([5,5,1,32])

        # 随机生成偏置
        b_conv1 = bias_varibles([32])

        # 对x进行形状的改变[None,784] 改变成思维数组 [None,28,28,1]
        x_reshape = tf.reshape(x,[-1,28,28,1])

        x_relu = tf.nn.relu(tf.nn.conv2d(x_reshape,w_conv1,strides=[1,1,1,1],padding="SAME") + b_conv1)

        # 池化 2*2 strides2 [None,28,28,32] -->[None,14,14,32]
        x_pool1 = tf.nn.max_pool(x_relu,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")

    # 3 二层卷积
    with tf.variable_scope("conv2"):
        # 随机初始化权重 权重[5,5,32,64] 偏置[64]
        w_conv2 = weight_varibles([5,5,32,64])
        b_conv2 = bias_varibles([64])

        #对卷积的激活与池化
        # 卷积由 [None,14,14,32]  ----->[None,14,14,64]
        x_relu2 = tf.nn.relu(tf.nn.conv2d(x_pool1,w_conv2,strides=[1,1,1,1],padding="SAME") + b_conv2)

        # 池化 2*2 strides 2,[None,14,14,64] --->[None,7,7,64]
        x_pool2 = tf.nn.max_pool(x_relu2,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")

    # 4 全连接层 [None,7,7,64] --->[None,7*7*64]*[7*7*64,10]+[10] =[None,10]
    with tf.variable_scope(""):
        #随机初始化权重和偏置
        w_fc = weight_varibles([7 * 7 * 64, 10])
        b_fc = bias_varibles([10])

        # 修改形状[None,7,7,64] --->[None,7*7*64]
        x_fc_reshape = tf.reshape(x_pool2,[-1,7*7*64])

        #进行矩阵运算 获得每个样本的10个结果
        y_predict = tf.matmul(x_fc_reshape,w_fc) + b_fc

    return x,y_true,y_predict

def cunv_fc():
    # 获取真实的数据
    mnist = input_data.read_data_sets("./mnist/input_data/",one_hot=True)
    #定义模型得出输出
    x,y_true,y_predict = model()

    # 求出所有样本的损失 求平均值
    with tf.compat.v1.variable_scope("soft_cross"):
        # 计算平均交叉熵损失
        loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y_predict))

    # 梯度下降求出损失
    with tf.compat.v1.variable_scope("optimizer"):
        train_op = tf.compat.v1.train.GradientDescentOptimizer(0.1).minimize(loss)

    # 计算准确率
    with tf.compat.v1.variable_scope("acc"):
        equal_list = tf.equal(tf.argmax(y_true, 1), tf.argmax(y_predict, 1))
        # 转换样本类型 和求平均值
        accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))

    #  定义一个初始化的变量op
    init_op = tf.global_variables_initializer()

    #开启会话运行
    with tf.compat.v1.Session() as sess:
        # 初始化变量
        sess.run(init_op)

        # 迭代步数去训练 更新参数预测
        for i in range(1000):
            # 取出真实的特征值和目标值
            mnist_x, mnist_y = mnist.train.next_batch(50)

            # 运行train_op训练
            sess.run(train_op, feed_dict={x: mnist_x, y_true: mnist_y})


            print("训练第%d次,准确率为%f" % (i, sess.run(accuracy, feed_dict={x: mnist_x, y_true: mnist_y})))


if __name__ == '__main__':
    cunv_fc()
原文地址:https://www.cnblogs.com/wen-kang/p/11127772.html