学习了一段时间CRF之后,自己也将重点转移到了TensorFlow的学习上,写写博客,就当是做做笔记了。
- TensorFlow的几大概念:
Tensor:向量,数据的存在格式
Variable:变量,由于变量可以更改,维护了数据的状态,与之对应的是Constants。
# 创建一个变量, 初始化为标量 0.
state = tf.Variable(0, name="counter")
Graph:图,表示框架中的每一个任务
import tensorflow as tf
# 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点
# 加到默认图中.
# 构造器的返回值代表该常量 op 的返回值.
matrix1 = tf.constant([[3., 3.]])
# 创建另外一个常量 op, 产生一个 2x1 矩阵.
matrix2 = tf.constant([[2.],[2.]])
# 创建一个矩阵乘法 matmul op , 把 'matrix1' 和 'matrix2' 作为输入.
# 返回值 'product' 代表矩阵乘法的结果.
product = tf.matmul(matrix1, matrix2)
Session:会话,通过一个session对象来执行每一个任务
# 启动默认图.
sess = tf.Session()
# 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数.
# 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回前面的1和2
# 矩阵乘法 op 的输出.
# 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的.
# 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行.
# 返回值 'result' 是一个 numpy `ndarray` 对象.
result = sess.run(product)
print result
# 任务完成, 关闭会话.
sess.close()
Flow:流,这里的计算都是基于数据流图来的
- 学习mnist的TensorFlow代码:
大佬说:当你入门后,学习TensorFlow最好的方法就是大量阅读别人的代码,并从中学习到别人是如何写的。
以下为mnist的TensorFlow代码以及注释,可以参照LeNet网络结构,会更容易消化
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import input_data
print "importing data"
mnist = input_data.read_data_sets('Mnist_data', one_hot=True)
print "import data done"
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.placeholder('float',shape=[None, 784]) #28*28
y_ = tf.placeholder('float', shape=[None, 10]) #1*10
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
def weight_variable(shape):
#权重值
intial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(intial)
def bias_variable(shape):
#偏置量
intial = tf.constant(0.1,shape=shape)
return tf.Variable(intial)
def conv2d(x,W):
#conv层
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME")
def max_pool_2x2(x):
#pooling层
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
# layer 1---------
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
# 我们的mnist图像是28*28,最后一个1代表只有一个色度空间
x_image = tf.reshape(x,[-1,28,28,1])
# 卷积操作,然后Activation function,relu类似于sigmoid函数,具体要见文章
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
# max 池化,池化的意思就是把一部分的值用与这块值相关的表示,从而减少数据量,常用的有max池化,平均值池化
h_pool1 = max_pool_2x2(h_conv1)
# layer 2---------
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2)+b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
# layer 3---------
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# layer 4---------
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
#求交叉熵,反向传播
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#预测结果,准确率
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#session初始化(必须的步骤)
sess.run(tf.initialize_all_variables())
for i in range(20000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={
x:batch[0], y_: batch[1], keep_prob: 1.0})
print "step %d, training accuracy %g"%(i, train_accuracy)
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
print "test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})