tensorflow学习1——mnist手写体识别

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

##### —————————————模型结构———————————————
x = tf.placeholder("float", [None, 784])        # 第一维可以是任意长度

##### 初值可以随意设置
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))                 # 我们要学习w,b

y = tf.nn.softmax(tf.matmul(x, w) + b)          # 模型结构


y_ = tf.placeholder("float", [None, 10])        # 正确答案

cross_entropy = -tf.reduce_sum(y_*tf.log(y))    # 不再是单一照片,而是100幅图片

##### 自动的使用反向传播算法,来确定不断朝目标又换成本值
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
##### ———————————模型结构—————————————————

##### —————————————初始化变量——————————————
##### 在运行计算前,要添加一个操作来初始化我们创建的变量
init = tf.initialize_all_variables()

##### ———————创建session并启动模型——————————————
##### 随后我们可以在一个session里面启动我们的模型,并且初始化变量
sess = tf.Session()
sess.run(init)

##### ———————————开始训练模型epoch=1000——————————
##### 使用一小部分的随机数据来进行训练被称为随机训练(stochastic training)
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})


##### ———————————模型评估—————————————————
correct_predication = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
##### 布尔映射为float型,进行取平均计算
accuracy = tf.reduce_mean(tf.cast(correct_predication, "float"))

print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

猜你喜欢

转载自blog.csdn.net/qq_33647375/article/details/89244430