全连接网络一步步实现手写体数字分类——基于TensorFlow的FC

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

def Full_Connected():
    #读取数据
    mnist = input_data.read_data_sets("mnist_data/", one_hot = True)
    #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、建立一个全连接层的神经网络 w[784,10]  b[10]  
    with tf.variable_scope("fc_model"):
        #随机初始化权重和偏置
        weight=tf.Variable(tf.random_normal([784,10],mean=0.0,stddev=1.0,name="w"))
        bias=tf.Variable(tf.constant(0.0),[10])
        #预测None个样本的输出结果matrix [None,784] *[784,10]+[10]=[None,10]
        y_predict=tf.matmul(x,weight)+bias
    #3、求出所有样本的损失,然后求平均值    
    with tf.variable_scope("soft_cross"):
        #求平均交叉熵损失
        loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_predict))

    with tf.variable_scope("opmizer"):
        train_op=tf.train.GradientDescentOptimizer(0.1).minimize(loss)

    #5、计算准确率
    with tf.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.Session() as sess:
         #初始化变量
        sess.run(init_op)
        #训练1000次
        for i in range(1000):
            mnist_x,mnist_y=mnist.train.next_batch(50)
            sess.run(train_op,feed_dict={x:mnist_x,y_true:mnist_y})
            #每50步打印一次结果
            if i %50==0:
                print("训练第%d步,准确率为:%f"%(i,sess.run(accuracy,feed_dict={x:mnist_x,y_true:mnist_y})))
    return None
        
if __name__=="__main__":
    Full_Connected()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值