TensorFlow學習筆記(一)——快速上手

寫在前面的話:
因爲工作需要,新接觸TensorFlow,基本上所有的筆記都是從博客上整理過來的,做筆記只是爲了鞏固和加深記憶的一種方式,同時也能自己不斷的回顧,如果能對各位看官有一點點幫助的話,是我的榮幸。如果在博客中有很多不當的地方,希望能夠多多指正,有不理解或者描述不當的地方,也希望能夠一起交流討論,共同成長~ 如果有參考的資料或者是引用的地方,我會儘可能註明出處,並且這些筆記會隨着理解的加深儘可能更新,同時儘可能採用一手學習資料從而避免在學習中出現的理解偏差,要是因爲該筆記對你造成的誤導敬請諒解。

1 基本概念

Graph:在TensorFlow中,將模型構建稱爲一個graph,每一個有向的graph,操作的前後順序決定了在圖的的拓撲結構。我們可以將每一個operator(op)看成是圖中的一個節點,而Tensor攜帶着數據沿着Graph的拓撲路徑在圖中流淌,也許會在某個op消失,也可能轉化成其他的Tensor。

Tensor:Tensor表示的是一個張量,在這裏我們可以將其理解爲一個矩陣,下面是一個TensorFlow簡單的累加例子。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tensorflow as tf
#定義一個變量,並且初始值爲0
state = tf.Variable(0, name="counter")
#定義一個常量
one = tf.constant(1)
#定義一個對1累加的操作
new_value = tf.add(state, one)
#將new_value的值賦值給state
update = tf.assign(state, new_value)
#進行初始化操作
init_op = tf.initialize_all_variables()
with tf.Session() as sess:
  print(sess.run(init_op))
  print(sess.run(state))
  for _ in range(3):
    sess.run(update)
    print(sess.run(state))

Variable:Variable用來表示變量表示TensorFlow搭建的模型中的各個參數,在使用了Variable後需要對變量進行初始化後才能在Session中運行。

fetch:在執行Session的時候傳入一些Tensor,這些Tensor會取回執行過程中的一些值,例如下面例子中傳入的[mul,intermed]兩個值分別取回了一些對應的值。

input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)

with tf.Session() as sess:
  result = sess.run([mul, intermed])
  print result
#輸出:[21.0, 7.0]

feed:tensorflow提供的feed機制,用於替代操作中的任何Tensor。具體例子如下,我們首先不適用feed機制來看一下結果。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tensorflow as tf
#定義一個變量,並且初始值爲0

input1 = tf.Variable(5.0,name="input1")
input2 = tf.Variable(6.0,name="input2")
output = tf.multiply(input1, input2)

init_op = tf.global_variables_initializer()

with tf.Session() as sess:
  sess.run(init_op)
  print (sess.run([output]))

結果如下圖:
這裏寫圖片描述
接下來使用feed機制代替已經有的input1和input2:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tensorflow as tf
#定義一個變量,並且初始值爲0

input1 = tf.Variable(5.0,name="input1")
input2 = tf.Variable(6.0,name="input2")
output = tf.multiply(input1, input2)

init_op = tf.global_variables_initializer()

with tf.Session() as sess:
  sess.run(init_op)
  print (sess.run([output], feed_dict={input1:7.0, input2:2.0}))

結果如下圖所示:
這裏寫圖片描述

Session:就是會話,在TensorFlow中主要分爲兩個部分,一個部分是圖的構建,一個部分是Session的執行。在我看來圖構建的過程相當於搭建整個圖框架,而Session執行部分則是對整個模型運行~ (我認爲圖構建的部分相當於搭建好自來水管道,而運行部分是通過管道注入自來水並運輸到我們要的地方)

2 簡單例子

2.1 multiply

該例子主要通過TensorFlow將兩個數據相乘,具體的方式如下,見具體代碼。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tensorflow as tf

#定義一個佔位符a和一個佔位符b
a = tf.placeholder("float")
b = tf.placeholder("float")

#將兩個佔用位符相乘
y = tf.multiply(a, b)
with tf.Session() as sess:
    #通過feed修改兩個Tensor的值,計算1*2
    print("%f should equal 2.0" % sess.run(y,feed_dict = {a:1,b:2}))
    #通過feed修改兩個Tensor的值,計算3*3
    print("%f should equal 9.0" % sess.run(y,feed_dict = {a:3,b:3}))

2.2 Linear Regression

在下面代碼中我們主要介紹了線性迴歸的在TensorFlow中的實現,在這個模型的設計中對於model沒有添加偏置量,並且對於具體的代碼實現而言,我們採用了因此迭代。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tensorflow as tf
import numpy as np
#導入matplotlib繪圖工具
import matplotlib.pyplot as plt

#生成100個隨機數數組在[-1,1]之間
trX = np.linspace(-1,1,101)

#隨機性生成對應的Y,W的值在2左右
trY = 2*trX + np.random.randn(*trX.shape)*0.33
#定義兩個佔位符
X = tf.placeholder("float")
Y = tf.placeholder("float")

#定義模型的結果
def model(X,w):
    return tf.multiply(X,w)

#定義參數值  
w = tf.Variable(0.0, name="weights")
y_model = model(X,w)

#定義損失函數
cost = tf.square(Y - y_model)
#定義初始化方法
init_op = tf.global_variables_initializer()
#通過梯度下降最小化cost損失函數
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
result = 0

#執行會話
with tf.Session() as sess:
    #首先要執行init_op否則會報錯
    sess.run(init_op)
    #運行對於每一個數組進行訓練
    for i in range(100):
        for(x, y) in zip(trX, trY):
            sess.run(train_op, feed_dict={X:x,Y:y})
    result = sess.run(w)
    print(result)

#繪製散點圖
plt.scatter(trX,trY,marker=".",color="y")
#繪製得到的函數圖像
testX = np.arange(-1,1,0.001)
testY = testX * result
plt.plot(testX,testY)
plt.show()

最後我們通過TensorFlow得到的線性迴歸的具體圖像如下圖所示,根據圖像可以大致看出通過TensorFlow得到的結果。在後續更新中,會進一步添加一下其他的信息,類似於迭代次數的增加,以及tensorboard的實用情況等。
這裏寫圖片描述
在上述代碼運行過程總得到的W的結果如下圖所示:
這裏寫圖片描述

參考資料

[1]tensorflow筆記:流程,概念和簡單代碼註釋
[2]TensorFlow中文文檔
[3]TensorFlow-Tutorials

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章