第一部分:训练模型
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, shape=[None, 784]) # placeholder( dtype, shape=None, name=None )
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros([784,10])) # tf.Variable(, name=, dtype=None, trainable=True)
b = tf.Variable(tf.zeros([10])) # 创建一个值为initial-value的新变量
sess.run(tf.global_variables_initializer())
y = tf.matmul(x,W) + b # tf.matmul()是专门矩阵或者tensor乘法
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)) # tf.reduce_mean()对所有的元素求平均
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy) # 梯度下降优化器,(0.1)学习率,最小化损失函数
for _ in range(5000): #迭代 5000 次学习
batch = mnist.train.next_batch(100)
train_step.run(feed_dict={x: batch[0], y_: batch[1]})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) #tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反正返回False
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # cast(x, dtype, name=None) 将x的数据格式转化成dtype
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1) # 截断的正态分布噪声,标准差为0.1(给W制造一些随机噪声打破完全对称)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape) # 会使用到ReLU,增加一些小的正值(0.1)用来避免死亡节点
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1],