神经网络3:神经网络学习 1

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

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
sess = tf.Session()

xs = tf.placeholder(shape=[None, 784], dtype=tf.float32)
ys = tf.placeholder(shape=[None, 10], dtype=tf.float32)


def add_layer(input_data, in_size, out_size, activation_func=None):
    Weights = tf.Variable(tf.random_normal(shape=[in_size, out_size]))
    biases = tf.Variable(tf.zeros(shape=[1, out_size]) + 0.1)
    W_plus_b = tf.matmul(input_data, Weights) + biases
    if activation_func is None:
        outputs = W_plus_b
    else:
        outputs = activation_func(W_plus_b)
    return outputs


def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs})
    correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return result


prediction = add_layer(xs, 784, 10, activation_func=tf.nn.softmax)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess.run(tf.global_variables_initializer())

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
    if i % 50 == 0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))

 

posted @ 2018-08-14 00:41  Lucky、Dog  阅读(137)  评论(0编辑  收藏  举报