1. 程式人生 > >Tensorflow實現最簡單的神經網路

Tensorflow實現最簡單的神經網路

程式程式碼:

#匯入相應模組
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