"""
例子为MNIST，对手写图片进行分类。
神经网络hello world。
"""
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# 封装网络用到的API


def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)


def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


def conv2d(x, W):
    return tf.nn.conv2d(x,
                        W,
                        strides= [1, 1, 1, 1],
                        padding= 'SAME')


def max_pool_2x2(x):
    return tf.nn.max_pool(x,
                          ksize= [1, 2, 2, 1],
                          strides= [1, 2, 2, 1],
                          padding='SAME')


"""
MNIST进阶
"""
sess = tf.InteractiveSession()
# [batch_size, 784]
x = tf.placeholder('float', shape=[None, 784])
y_ = tf.placeholder('float', shape=[None, 10])

"""
第一层卷积
"""
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

# [batch_size, 28, 28, 1]
x_image = tf.reshape(x, [-1, 28, 28, 1])

# [batch_size, 28, 28, 32]
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# [batch_size, 14, 14, 32]
h_pool1 = max_pool_2x2(h_conv1)

"""
第二层卷积
"""
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

# [batch_size, 14, 14, 64]
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
# [batch_size, 7, 7, 64]
h_pool2 = max_pool_2x2(h_conv2)

"""
全连接层
"""
w_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

# [batch_size, 7*7*64]
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
# [batch_size, 1024]
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)

"""
dropout
"""
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

"""
输出层
"""
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

# [batch_size, 10]
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
y_sum = tf.reduce_sum(y_conv[0])

# 计算损失和添加优化器
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 评估模型
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

# 初始化
sess.run(tf.initialize_all_variables())

for i in range(1):
    batch = mnist.train.next_batch(50)

    #     train_accuracy = accuracy.eval(feed_dict={x:batch[0],
    #                                               y_: batch[1],
    #                                               keep_prob: 1.0})
    #     print("step %d, training accuracy %g" % (i, train_accuracy))

    y_conv_re = y_conv.eval(feed_dict={x: batch[0],
                                       y_: batch[1],
                                       keep_prob: 1.0})
    #     print(y_conv_re.shape)
    print(y_conv_re)
    y_sum_re = y_sum.eval(feed_dict={x: batch[0],
                                     y_: batch[1],
                                     keep_prob: 1.0})
    print(y_sum_re)

    train_step.run(feed_dict={x: batch[0],
                              y_: batch[1],
                              keep_prob: 0.5})

print("test accuracy %g" % accuracy.eval(feed_dict={x: mnist.test.images,
                                                    y_: mnist.test.labels,
                                                    keep_prob: 1.0}))





[((155, 208), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""MNIST_data"""'], {'one_hot': '(True)'}), "('MNIST_data', one_hot=True)\n", (180, 208), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((819, 842), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (840, 842), True, 'import tensorflow as tf\n'), ((867, 909), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {'shape': '[None, 784]'}), "('float', shape=[None, 784])\n", (881, 909), True, 'import tensorflow as tf\n'), ((915, 956), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {'shape': '[None, 10]'}), "('float', shape=[None, 10])\n", (929, 956), True, 'import tensorflow as tf\n'), ((1080, 1110), 'tensorflow.reshape', 'tf.reshape', (['x', '[-1, 28, 28, 1]'], {}), '(x, [-1, 28, 28, 1])\n', (1090, 1110), True, 'import tensorflow as tf\n'), ((1611, 1648), 'tensorflow.reshape', 'tf.reshape', (['h_pool2', '[-1, 7 * 7 * 64]'], {}), '(h_pool2, [-1, 7 * 7 * 64])\n', (1621, 1648), True, 'import tensorflow as tf\n'), ((1758, 1781), 'tensorflow.placeholder', 'tf.placeholder', (['"""float"""'], {}), "('float')\n", (1772, 1781), True, 'import tensorflow as tf\n'), ((1795, 1826), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['h_fc1', 'keep_prob'], {}), '(h_fc1, keep_prob)\n', (1808, 1826), True, 'import tensorflow as tf\n'), ((1993, 2017), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['y_conv[0]'], {}), '(y_conv[0])\n', (2006, 2017), True, 'import tensorflow as tf\n'), ((267, 305), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['shape'], {'stddev': '(0.1)'}), '(shape, stddev=0.1)\n', (286, 305), True, 'import tensorflow as tf\n'), ((317, 337), 'tensorflow.Variable', 'tf.Variable', (['initial'], {}), '(initial)\n', (328, 337), True, 'import tensorflow as tf\n'), ((380, 409), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': 'shape'}), '(0.1, shape=shape)\n', (391, 409), True, 'import tensorflow as tf\n'), ((421, 441), 'tensorflow.Variable', 'tf.Variable', (['initial'], {}), '(initial)\n', (432, 441), True, 'import tensorflow as tf\n'), ((473, 529), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['x', 'W'], {'strides': '[1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(x, W, strides=[1, 1, 1, 1], padding='SAME')\n", (485, 529), True, 'import tensorflow as tf\n'), ((638, 713), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['x'], {'ksize': '[1, 2, 2, 1]', 'strides': '[1, 2, 2, 1]', 'padding': '"""SAME"""'}), "(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n", (652, 713), True, 'import tensorflow as tf\n'), ((2188, 2208), 'tensorflow.argmax', 'tf.argmax', (['y_conv', '(1)'], {}), '(y_conv, 1)\n', (2197, 2208), True, 'import tensorflow as tf\n'), ((2210, 2226), 'tensorflow.argmax', 'tf.argmax', (['y_', '(1)'], {}), '(y_, 1)\n', (2219, 2226), True, 'import tensorflow as tf\n'), ((2254, 2290), 'tensorflow.cast', 'tf.cast', (['correct_prediction', '"""float"""'], {}), "(correct_prediction, 'float')\n", (2261, 2290), True, 'import tensorflow as tf\n'), ((2308, 2337), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (2335, 2337), True, 'import tensorflow as tf\n'), ((1689, 1719), 'tensorflow.matmul', 'tf.matmul', (['h_pool2_flat', 'w_fc1'], {}), '(h_pool2_flat, w_fc1)\n', (1698, 1719), True, 'import tensorflow as tf\n'), ((1947, 1975), 'tensorflow.matmul', 'tf.matmul', (['h_fc1_drop', 'W_fc2'], {}), '(h_fc1_drop, W_fc2)\n', (1956, 1975), True, 'import tensorflow as tf\n'), ((2097, 2127), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['(0.0001)'], {}), '(0.0001)\n', (2119, 2127), True, 'import tensorflow as tf\n'), ((2068, 2082), 'tensorflow.log', 'tf.log', (['y_conv'], {}), '(y_conv)\n', (2074, 2082), True, 'import tensorflow as tf\n')]