Tensorflow实现最简单的神经网络

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/PoGeN1/article/details/84632602

程序代码:

#导入相应模块
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#读入数据
mnist = input_data.read_data_sets('MNIST_data',one_hot=True)
#设置参数
batch_size=120#批大小
n_batch=mnist.train.num_examples//batch_size#总共有多少批次
#placeholder
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])
#初始化权重偏置
Weight=tf.Variable(tf.zeros([784,10]))
biases=tf.Variable(tf.zeros([10]))
#前向过程
prediction=tf.nn.softmax(tf.matmul(x,Weight)+biases)
#定义一个loss
loss=tf.reduce_mean(tf.square(y-prediction))
# 交叉熵写法:loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#梯度下降法
train=tf.train.GradientDescentOptimizer(0.2).minimize(loss)
init=tf.global_variables_initializer()
#预测精度
current_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
accuracy=tf.reduce_mean(tf.cast(current_prediction,tf.float32))

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(21):
        for _ in range(n_batch):
            batch_xs,batch_ys=mnist.train.next_batch(batch_size)
            sess.run(train,feed_dict={x:batch_xs,y:batch_ys})
        acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print('Iter:',str(epoch),'accuracy:',str(acc))

输出结果:

Iter: 0 accuracy: 0.8215
Iter: 1 accuracy: 0.8891
Iter: 2 accuracy: 0.898
Iter: 3 accuracy: 0.9033
Iter: 4 accuracy: 0.9055
Iter: 5 accuracy: 0.9076
Iter: 6 accuracy: 0.9102
Iter: 7 accuracy: 0.9129
Iter: 8 accuracy: 0.9135
Iter: 9 accuracy: 0.9135
Iter: 10 accuracy: 0.9149
Iter: 11 accuracy: 0.9152
Iter: 12 accuracy: 0.9175
Iter: 13 accuracy: 0.9185
Iter: 14 accuracy: 0.9187
Iter: 15 accuracy: 0.919
Iter: 16 accuracy: 0.9195
Iter: 17 accuracy: 0.9201
Iter: 18 accuracy: 0.9197
Iter: 19 accuracy: 0.9208
Iter: 20 accuracy: 0.9209

猜你喜欢

转载自blog.csdn.net/PoGeN1/article/details/84632602