@Andream
2017-05-20T13:56:29.000000Z
字数 2015
阅读 1177
TensorFlow 机器学习 人工智能 Google Vison
文档链接:MNIST机器学习入门
import tensorflow as tfimport tensorflow.examples.tutorials.mnist.input_data as input_datamnist = input_data.read_data_sets("MNIST_data/", one_hot=True)# Data representationx = tf.placeholder(tf.float32, [None, 784]) # input image sourceW = tf.Variable(tf.zeros([784, 10]))b = tf.Variable(tf.zeros([10]))# Mathmatical modely = tf.nn.softmax(tf.matmul(x, W) + b)# Training modely_ = tf.placeholder("float", [None, 10]) # input image label# define a 'loss'cross_entropy = -tf.reduce_sum(y_*tf.log(y))# minimize ittrain_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)# Run in a sessioninit = tf.global_variables_initializer()sess = tf.Session()sess.run(init)# LEARNING... 1000 TIMESfor i in range(1000):batch_xs, batch_ys = mnist.train.next_batch(209) # random fetch 100 datasess.run(train_step, feed_dict={x: batch_xs, y_:batch_ys}) # feed_dict is what we should input# Evulating modelcorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # SEE argmax() & equal()accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
这个模型比较简单,每行代码照着写下来,一次就跑通了,主要是借此学习TensorFlow和机器学习的核心概念。
Graph来代表计算Tensor来代表数据Variable维护状态Operation代表函数Fetch读 Tensor/Variable/OperationFeed写 Tensor/Variable/OperationSession这个上下文中执行lossloss1、 无法下载数据集
# 通过这两行代码,程序自动下载数据集# 如果因为网络问题无法下载,可手动下载数据集而后放到/MNIST_data目录下import tensorflow.examples.tutorials.mnist.input_data as input_datamnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
2、 Session.run()之后都发生了什么?
# 这句代码中,x: mnist.test.images流向了哪里?程序应该是通过x更新了y矩阵,那是否每一次x的更新都会导致y的更新呢?sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
3、 next_batch,next bitch!
batch_xs, batch_ys = mnist.train.next_batch(100) # random fetch 100 data#按理说这句代码中的100可以改为任意值,但是我发现如果这个值超过209,最终输出的准确率总是0.098(正常情况应该是0.910左右),怪哉!
4、 其他小改动
tf.initialize_all_variables() #已经弃用,应使用:tf.global_variables_initializer()