tensorfow使用基礎(3)--MNiST--1

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

#導入數據
data = mnist.input_data.read_data_sets("MNIST_data", one_hot=True)
batch_size = 100
n_batch = data.train.num_examples // batch_size

"""
構建網絡結構,其結構爲[784, 10]
"""
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])

w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

z = tf.matmul(x, w) + b
z_plus = tf.nn.tanh(z)

loss = tf.reduce_mean(tf.square(z_plus - y))
train = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(z_plus, 1))#argmax返回一維張量中最大的值所在的位置
#求準確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for epochs in range(20):
        for i in range(n_batch):
            batch_x, batch_y = data.train.next_batch(batch_size=batch_size)
            sess.run(train, feed_dict={x:batch_x,y:batch_y})
        acc = sess.run(accuracy, feed_dict={x: data.test.images, y: data.test.labels})
        print("Iter " + str(epochs) + ",Testing Accuracy " + str(acc))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章