資料集:MNIST
損失函數:交叉熵
激活函數:relu
代碼如下:
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 = 100
n_batch = mnist.train.num_examples//batch_size
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
weights_L1 = tf.Variable(tf.zeros([784,200]))
biases_L1 = tf.Variable(tf.random_normal([200]))
wx_plus_b_L1 = tf.matmul(x,weights_L1) + biases_L1
L1 = tf.nn.relu(wx_plus_b_L1)
weights_L2 = tf.Variable(tf.random_normal([200,50]))
biases_L2 = tf.Variable(tf.random_normal([50]))
wx_plus_b_L2 = tf.matmul(L1,weights_L2) + biases_L2
L2 = tf.nn.relu(wx_plus_b_L2)
weights_L3 = tf.Variable(tf.zeros([50,10]))
biases_L3 = tf.Variable(tf.zeros([10]))
wx_plus_b_L3 = tf.matmul(L2,weights_L3) + biases_L3
predictions = tf.nn.softmax(wx_plus_b_L3)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=predictions))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
correct_predictions = tf.equal(tf.argmax(y,1),tf.argmax(predictions,1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions,tf.float32))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(51):
for batch in range(n_batch):
batch_x,batch_y = mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_x,y:batch_y})
acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
print('Iter ' + str(epoch) + ',Testing Acccuracy: ' + str(acc))