1、首先要将tensorflow、tensorboard、numpy等更新到最新版本
2、需要先下载mnist数据集,可以在CSDN上找,官网比较慢。数据放在MNIST_data文件夹里面。
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
def mnist_liner():
"""
线性深度网络
:return:
"""
# 用来自动下载数据的,mnist是个数据结构,包括mnist.train和mnist.test
mnist = input_data.read_data_sets('../MNIST_data/', one_hot=True)
# 图片images是[60000, 784]
# 标签labels[60000, 10]
# y=softmax(Wx+b)
# 占位符 placeholder ,这里的 None 表示此张量的第一个维度可以是任何长度的
x = tf.placeholder("float", [None, 784])
# 全为零的张量来初始化W和b,学习 W 和 b 的值, W 的维度是[784,10],因为我们想要用784维的图片向量乘以它以得到一个10维的向量,每一位对应不同数字类。b的形状是[10]
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# matmul(X,W) 表示 x 乘以 W。nn代表神经网络的意思,是个大类,里面有很多函数
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 正确值
y_ = tf.placeholder("float", [None, 10])
# 损失函数,交叉熵。reduce_sum 计算张量的所有元素的总和
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
# 用0.01的梯度下降学习速率最小化损失函数
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# 在一个 Session 里面启动我们的模型,并且初始化变量
init = tf.initialize_all_variables()
sess = tf.Session()
tf.device('/cpu:0')
sess.run(init)
# 1000次迭代。batch为100.feed_dict往里面传值
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# tf.argmax(vector,1)是vector中最大值的索引号,y是10维的向量,只有1位是1,其他是0,那么1所在的位置就是tf.argmax的值
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # 布尔值
# 把布尔值转换成浮点数,然后取平均值
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
def mnist_another():
"""
另外一种写法
:return:
"""
mnist = input_data.read_data_sets('../MNIST_data/', one_hot=True)
# InteractiveSession 类,它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。
sess = tf.InteractiveSession()
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10]) # 正确值
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# 初始化变量
sess.run(tf.initialize_all_variables())
y = tf.nn.softmax(tf.matmul(x, W) + b)
cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) # 损失函数
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
for i in range(1000):
batch = mnist.train.next_batch(50)
# 整个模型的训练可以通过反复地运行train_step 来完成
train_step.run(feed_dict={x: batch[0], y_: batch[1]})
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
if __name__ == '__main__':
mnist_liner()
mnist_another()