<jupyter_start><jupyter_text>使用Tensorflow训练MNIST数据集  1.引入依赖包<jupyter_code>import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

%matplotlib inline<jupyter_output><empty_output><jupyter_text>2.定义参数<jupyter_code>mnist = input_data.read_data_sets('/tmp/', one_hot=True)

# 定义每一层神经元的个数
"""
层数的选择：线性数据使用1层，非线性数据使用2册, 超级非线性使用3+册。层数／神经元过多会导致过拟合
"""
n_input_layer  = 28*28 # 输入层
n_hidden_layer_1 = 30 # hidden layer 1
n_hidden_layer_2 = 20 # hidden layer 2
n_output_layer = 10 # 输出层

W_xh = tf.Variable(tf.random_normal([n_input_layer, n_hidden_layer_1]))
b_h1  = tf.Variable(tf.random_normal([n_hidden_layer_1]))

W_hh = tf.Variable(tf.random_normal([n_hidden_layer_1, n_hidden_layer_2]))
b_h2  = tf.Variable(tf.random_normal([n_hidden_layer_2]))

W_ho = tf.Variable(tf.random_normal([n_hidden_layer_2, n_output_layer]))
b_o  = tf.Variable(tf.random_normal([n_output_layer]))

batch_size = 100

# 定义实际输入和输出数据
X = tf.placeholder('float', [None, 28*28])
Y = tf.placeholder('float', [None,10])<jupyter_output>Extracting /tmp/train-images-idx3-ubyte.gz
Extracting /tmp/train-labels-idx1-ubyte.gz
Extracting /tmp/t10k-images-idx3-ubyte.gz
Extracting /tmp/t10k-labels-idx1-ubyte.gz<jupyter_text>3.定义神经网络模型<jupyter_code>def neural_network(x):
    
    hidden_layer_1_output = tf.matmul(x, W_xh) + b_h1
    hidden_layer_1_activate = tf.nn.sigmoid(hidden_layer_1_output)  # 激活函数
    
    hidden_layer_2_output = tf.matmul(hidden_layer_1_activate, W_hh) + b_h2
    hidden_layer_2_output = tf.nn.sigmoid(hidden_layer_2_output)
    
    output = tf.matmul(hidden_layer_2_output, W_ho) + b_o
    output = tf.nn.softmax(output)
    return output<jupyter_output><empty_output><jupyter_text>4.训练<jupyter_code>def train_neural_network(x, y):
    
    predict       = neural_network(x)
    cross_entropy = tf.reduce_mean(- tf.reduce_sum(y*tf.log(predict), axis=1))
    train_step    = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy) #学习率调整到0.1,加快梯度下降
    init          = tf.global_variables_initializer()
    
    with tf.Session() as sess:
        sess.run(init)
        epochs = 20000
        
        for epoch in range(epochs):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x: batch_x, y: batch_y})
        
        correct = tf.equal(tf.argmax(predict, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print '准确率：', sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
train_neural_network(X, Y)<jupyter_output>准确率： 0.9155