@Andream
2017-05-20T21:56:29.000000Z
字数 2015
阅读 1043
TensorFlow
机器学习
人工智能
Google
Vison
文档链接:MNIST机器学习入门
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Data representation
x = tf.placeholder(tf.float32, [None, 784]) # input image source
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Mathmatical model
y = tf.nn.softmax(tf.matmul(x, W) + b)
# Training model
y_ = tf.placeholder("float", [None, 10]) # input image label
# define a 'loss'
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
# minimize it
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# Run in a session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
# LEARNING... 1000 TIMES
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(209) # random fetch 100 data
sess.run(train_step, feed_dict={x: batch_xs, y_:batch_ys}) # feed_dict is what we should input
# Evulating model
correct_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
这个上下文中执行loss
loss
1、 无法下载数据集
# 通过这两行代码,程序自动下载数据集
# 如果因为网络问题无法下载,可手动下载数据集而后放到/MNIST_data目录下
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = 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()