
上一篇文章用了一個簡單的例子說明了一下機(jī)器學(xué)習(xí)的基本實(shí)現(xiàn)方式。我們可以看到,機(jī)器學(xué)習(xí)過程中,會用到很多矩陣運(yùn)算,還會用到一些數(shù)學(xué)算法和公式,例如梯度下降算法、激勵函數(shù)等。如果這些算法讓我們自己去實(shí)現(xiàn),將會十分困難。還好,Google意識到了這是一個有難度但是重復(fù)性的勞動。推出了一款開源的機(jī)器學(xué)習(xí)開發(fā)框架tensorflow(類似的框架還有Theano、Lasagne、Blocks、MXNet...,沒用過),它跟python是一對完美的搭檔(雖然它也支持C++)。python就不多講了,它是當(dāng)前很流行的一款主流語言。這篇文章稍微聊聊tensorflow??纯此峁┝四切┏S玫墓δ?。tensorflow的詳細(xì)使用方法介紹見官網(wǎng)http://www.tensorfly.cn/。
tensorflow的幾個概念:
tensorgraphseesion
tensorflow的幾個特點(diǎn):
- 使用圖 (graph) 來表示計(jì)算任務(wù).
- 在被稱之為 會話 (Session) 的上下文 (context) 中執(zhí)行圖.
- 使用 tensor 表示數(shù)據(jù).
- 通過 變量 (Variable) 維護(hù)狀態(tài).
- 使用 feed 和 fetch 可以為任意的操作(arbitrary operation) 賦值或者從其中獲取數(shù)據(jù)。
代碼示例(實(shí)現(xiàn)向量相減):
import tensorflow as tf
# 變量(同時也是一個tensor)
x = tf.Variable([1.0, 2.0])
# 常量(同時也是一個tensor)
a = tf.constant([3.0, 3.0])
# 定義初始化變量的一個操作(OP)
init = tf.initialize_all_variables()
# 定義一個減法的操作(OP)
sub = tf.sub(x, a)
上面就是利用tensor和OP定義了一個計(jì)算圖Graph,這個計(jì)算圖類似于C語言等中的變量和函數(shù)的聲明和定義,沒有真正的執(zhí)行。
通過下面這段代碼,在會話(Session)中,才能真正的執(zhí)行上面的計(jì)算圖。
# 在Session中啟動計(jì)算圖(Graph).
sess = tf.Session()
# 執(zhí)行計(jì)算圖中的操作(OP),限制性初始化變量的init,在執(zhí)行減法sub
sess.run(init)
sess.run(sub)
# 任務(wù)完成, 關(guān)閉Session.
sess.close()
執(zhí)行結(jié)果:
[-2. -1.]
上面這段是很簡單的一個程序,旨在說明tensorflow的基本組成要素和運(yùn)行方法。真正機(jī)器學(xué)習(xí)中,用到的計(jì)算圖要遠(yuǎn)遠(yuǎn)比上面的程序復(fù)雜。
下面給出一段使用了神經(jīng)網(wǎng)絡(luò)的程序,有興趣的可以看看。
# 從文件中讀入訓(xùn)練數(shù)據(jù)集
import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 定義將要輸入的x和期望輸出的y,這里只是兩個占位符,這類似與兩個變量,需要在訓(xùn)練的時候輸入真實(shí)的值。
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
# 我們定義兩個函數(shù)用于變量初始化
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
# 定義卷積OP
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
# 定義池化OP
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
# 定義第一層卷積的權(quán)值和偏置
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
# 對長度為784的一維的x做個變形,這里是變成28x28的矩陣,這個是原始圖像的尺寸。
x_image = tf.reshape(x, [-1,28,28,1])
# 經(jīng)過Relu激活函數(shù),然后進(jìn)行池化。
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# 經(jīng)過這個池化后,圖像尺寸變?yōu)樵瓉淼囊话?,?4×14
h_pool1 = max_pool_2x2(h_conv1)
# 將Relu函數(shù)的輸出,再經(jīng)過一層卷積神經(jīng)網(wǎng)絡(luò),用法與第一層卷積神經(jīng)網(wǎng)絡(luò)類似。
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)
# 經(jīng)過這個赤化后,圖像尺寸再減小一半,即7×7
h_pool2 = max_pool_2x2(h_conv2)
# 現(xiàn)在,圖片尺寸減小到7x7,我們加入一個有1024個神經(jīng)元的全連接層,用于處理整個圖片。我們把池化層輸出的張量reshape成一維向量,乘上權(quán)重矩陣,加上偏置,然后對其使用ReLU。
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)
# 最后加入一個softmax層
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)
# 創(chuàng)建Session,開始訓(xùn)練
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"))
with tf.Session() as sess:
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]})
print "step %d, training accuracy %g"%(i, train_accuracy)
train_step.run(feed_dict={x: batch[0], y_: batch[1]})
print "test accuracy %g"%accuracy.eval(feed_dict={
x: mnist.test.images, y_: mnist.test.labels})
sweet tip: 上面這段程序是經(jīng)典的手寫數(shù)字識別,tensorflow官網(wǎng)上有相應(yīng)的程序和介紹。代碼實(shí)現(xiàn)見https://github.com/goinghlf/mnist-with-tensorflow