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))

你可能感兴趣的:(tensorflow)