MNIST最基础示例+注释--tensorflow社区入门教程

MNIST最基础示例+注释–tensorflow社区入门教程

MNIST最基础示例+注释–tensorflow社区入门教程

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

# 导入mnist示例集
mnist = input_data.read_data_sets("./MNIST", one_hot=True)

# 占位符的创建,先不包含任何数据,只是把空间定下来,None表示这一维度可以是任意长度
x = tf.placeholder("float", [None, 784])

# y = W*x+b  矩阵的计算要构建好矩阵的维度
# Variable 表示可修改的张量,存在tensorflow的用于描述交互性操作的图
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# 最简单的模型
y = tf.nn.softmax(tf.matmul(x, W) + b)

# 训练模型
# 构建一个用来判断离正确答案差距的函数(成本函数),这里使用的是交叉熵(cross-entropy)

y_ = tf.placeholder("float", [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))

# 梯度下降算法
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

# 初始化操作
init = tf.initialize_all_variables()

# 执行的时候需要再session中执行
sess = tf.Session()
sess.run(init)

# 训练一千次
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)   # 一次随机抓取100张图片
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})  # 训练

# 评估模型
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))  # 返回一组bool值

# 求平均值
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))    # 有多种不同求平均值的方法
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

理解交叉熵
更多的优化算法
tensorflow教程网址

你可能感兴趣的:(入门贴)