【TensorFlow】笔记1:入门笔记
文章目錄
- 零、基礎(chǔ)
- 1、系統(tǒng)架構(gòu)
- 2、設(shè)計(jì)理念
- 3、常用概念
- (1)邊
- (2)節(jié)點(diǎn)
- (3)圖
- (4)會(huì)話
- (5)設(shè)備
- (6)變量——tf.Variable()
- (7)內(nèi)核
- 一、計(jì)算模型——計(jì)算圖
- 1、計(jì)算圖
- 2、計(jì)算圖使用
- (1)計(jì)算階段
- (2)相關(guān)設(shè)置
- (3)TF 中維護(hù)的集合列表
- 二、數(shù)據(jù)模型——張量
- 1、張量的概念
- 2、張量的使用
- (1)對(duì)中間計(jì)算結(jié)果的引用
- (2)獲取計(jì)算結(jié)果
- 三、運(yùn)行模型——會(huì)話(session)
- 1、兩種模式
- 2、默認(rèn)會(huì)話設(shè)置
- 3、配置會(huì)話
- 四、實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)
- 1、過(guò)程
- 2、前向傳播算法
- 3、神經(jīng)網(wǎng)絡(luò)參數(shù) 與 TensorFlow變量
- (1)tf.Variable(變量)
- (2)常數(shù)初始化
- (3)偏置項(xiàng)(bias)設(shè)置
- (4)其他變量的初始值進(jìn)行初始化
- (5)樣例
- 4、通過(guò)Tensorflow訓(xùn)練神經(jīng)網(wǎng)絡(luò)模型
- 5、完整代碼
零、基礎(chǔ)
1、系統(tǒng)架構(gòu)
TF的系統(tǒng)架構(gòu),從底向上分為設(shè)備管理和通信層、數(shù)據(jù)操作層、圖計(jì)算層、API接口層、應(yīng)用層。其中設(shè)備管理和通信層、數(shù)據(jù)操作層、圖計(jì)算層是TF的核心層。
- 底層設(shè)備通信層負(fù)責(zé)網(wǎng)絡(luò)通信和設(shè)備管理。 設(shè)備管理可以實(shí)現(xiàn)TF設(shè)備異構(gòu)的特性,支持CPU、GPU、Mobile等不同設(shè)備。網(wǎng)絡(luò)通信依賴gRPC通信協(xié)議實(shí)現(xiàn)不同設(shè)備間的數(shù)據(jù)傳輸和更新。
- 第二層是數(shù)據(jù)操作層。主要包括卷積函數(shù)、激活函數(shù)等操作。
- 第三層是圖計(jì)算層(Graph),包含本地計(jì)算流圖和分布式計(jì)算流圖的實(shí)現(xiàn)。Graph模塊包含Graph的創(chuàng)建、編譯、優(yōu)化和執(zhí)行等部分。
- 第四層是API接口層。Tensor C API是對(duì)TF功能模塊的接口封裝,便于其他語(yǔ)言平臺(tái)調(diào)用。
- 第四層以上是應(yīng)用層。不同編程語(yǔ)言在應(yīng)用層通過(guò)API接口層調(diào)用TF核心功能實(shí)現(xiàn)相關(guān)實(shí)驗(yàn)和應(yīng)用。
2、設(shè)計(jì)理念
- 將圖的定義和圖的運(yùn)行完全分開(kāi)。TF是符號(hào)式編程(運(yùn)行速度快些),符號(hào)式計(jì)算一般先定義各種變量,然后建立一個(gè)數(shù)據(jù)流圖,在數(shù)據(jù)流圖中規(guī)定各個(gè)變量之間的計(jì)算關(guān)系,最后需要對(duì)數(shù)據(jù)流圖進(jìn)行編譯,注意:此時(shí)的數(shù)據(jù)流圖中沒(méi)有任何實(shí)質(zhì)的數(shù)據(jù),只有把需要運(yùn)行的輸入放進(jìn)去,才能在整個(gè)模型中形成數(shù)據(jù)流,從而形成輸出值。
- TF中涉及的運(yùn)算都放在圖中,而圖的運(yùn)行只發(fā)生在會(huì)話(session)中。會(huì)話啟動(dòng)后,就可以用數(shù)據(jù)填充節(jié)點(diǎn),進(jìn)行計(jì)算;關(guān)閉會(huì)話后,不能再計(jì)算。
3、常用概念
(1)邊
邊有兩種連接關(guān)系:數(shù)據(jù)依賴和控制依賴。
- 實(shí)線表示數(shù)據(jù)依賴,代表數(shù)據(jù)(tensor)。
- 虛線表示控制依賴,用于控制操作的運(yùn)行,用于確保happens-before關(guān)系,這類邊上沒(méi)有數(shù)據(jù)流過(guò),但源節(jié)點(diǎn)必須在目的節(jié)點(diǎn)開(kāi)始執(zhí)行前完成執(zhí)行。常用以下代碼:
(2)節(jié)點(diǎn)
節(jié)點(diǎn):代表一個(gè)操作,一般表示施加的數(shù)學(xué)運(yùn)算,也可以表示數(shù)據(jù)輸入(feed in)的起點(diǎn)以及輸出(push out)的終點(diǎn),或是讀取/寫(xiě)入持久變量的終點(diǎn)。
(3)圖
將各個(gè)節(jié)點(diǎn)構(gòu)建成一個(gè)有向無(wú)環(huán)圖。
(4)會(huì)話
啟動(dòng)圖的第一步就是創(chuàng)建一個(gè)Session對(duì)象。會(huì)話提供在圖中執(zhí)行操作的一些方法。一般的模式是,建立會(huì)話,此時(shí)會(huì)生成一張空?qǐng)D,在會(huì)話中添加節(jié)點(diǎn)和邊,形成一張圖,然后執(zhí)行。
import tensorflow as tfmatrix1 = tf.constant([[3., 3.]]) matrix2 = tf.constant([2.], [2.])product = tf.matmul(matrix1, matrix2)with tf.Session() as sess:result = sess.run([product])print(result)主要有兩個(gè)API接口:
- extend:在Graph中注入數(shù)據(jù)進(jìn)行計(jì)算。
- run:輸入計(jì)算的節(jié)點(diǎn)和填充(傳入tensor)必要的數(shù)據(jù)后,進(jìn)行運(yùn)算,并輸出運(yùn)算結(jié)果。
(5)設(shè)備
設(shè)備(device): 一塊可以用于運(yùn)算并擁有自己的地址空間的硬件,eg: GPU和CPU。
設(shè)備的設(shè)置:with tf.device("/gpu:1"):
(6)變量——tf.Variable()
變量(variable)在圖中有固定的位置,在創(chuàng)建時(shí)需要一個(gè)初始值,初始值的形狀和類型決定該變量的形狀來(lái)類型。
state = tf.Variable(0, name = "counter") # 定義一個(gè)變量,初始化為標(biāo)量0 input1 = tf.constant(3.0) # 定義一個(gè)常量張量填充機(jī)制:tf.placeholder() 臨時(shí)代替任意操作的張量,在調(diào)用Session對(duì)象的run()方法執(zhí)行圖時(shí),使用填充數(shù)據(jù)(feed_dict)作為調(diào)用參數(shù),在結(jié)束調(diào)用后參數(shù)消失。
input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) output = tf.mul(input1, input2) with tf.Session() as sess:print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))(7)內(nèi)核
內(nèi)核(kernel):能夠運(yùn)行在特定設(shè)備(eg: CPU GPU)上的一種對(duì)操作的實(shí)現(xiàn)。
關(guān)鍵詞:計(jì)算模型、數(shù)據(jù)模型 和 運(yùn)行模型;神經(jīng)網(wǎng)絡(luò)的主要計(jì)算流程。
一、計(jì)算模型——計(jì)算圖
計(jì)算圖是 TF 中最基本的一個(gè)概念,TF 中所有計(jì)算都會(huì)被轉(zhuǎn)化為計(jì)算圖上的節(jié)點(diǎn)。
1、計(jì)算圖
TensorFlow
- Tensor(張量): 一種數(shù)據(jù)結(jié)構(gòu),簡(jiǎn)單理解為多維數(shù)組,數(shù)據(jù)流圖的邊。
- Flow(流): 表示張量之間通過(guò)計(jì)算相互轉(zhuǎn)化的過(guò)程,數(shù)據(jù)流圖中節(jié)點(diǎn)所做的操作。
2、計(jì)算圖使用
TF 程序一般可以分為兩個(gè)階段:
- 第一階段:定義計(jì)算圖中所有計(jì)算;
- 第二階段:執(zhí)行計(jì)算階段;
(1)計(jì)算階段
計(jì)算定義階段:
import tensorflow as tfa = tf.constant([1.0, 2.0], name="a") b = tf.constant([2.0, 3.0], name="b") result = a + b# a.graph可以查看張量所屬的計(jì)算圖,若沒(méi)特指,則為默認(rèn)的計(jì)算圖 print(a.graph is tf.get_default_graph()) # True在此過(guò)程中,TF 會(huì)自動(dòng)將定義的計(jì)算轉(zhuǎn)化為計(jì)算圖上的節(jié)點(diǎn)。在 TF 程序中,系統(tǒng)會(huì)自動(dòng)維護(hù)一個(gè)默認(rèn)的計(jì)算圖,通過(guò) tf.get_default_graph 函數(shù)可以獲得當(dāng)前默認(rèn)的計(jì)算圖。
通過(guò) tf.Graph 生成新的計(jì)算圖,不同計(jì)算圖上的張量和運(yùn)算不會(huì)共享,這樣可以隔離張量和計(jì)算。
import tensorflow as tf## tf.Graph 生成新的計(jì)算圖 g1 = tf.Graph() with g1.as_default():# 在計(jì)算圖 g1 中定義變量“v”,并初始化為 0.v = tf.get_variable("v", initializer=tf.zeros_initializer()(shape=[1]))g2 = tf.Graph() with g2.as_default():# 在計(jì)算圖 g2 中定義變量“v”,并初始化為 1.v = tf.get_variable("v", initializer=tf.ones_initializer()(shape=[1]))# 在計(jì)算圖 g1 中讀取變量 “v” 的取值。 with tf.Session(graph=g1) as sess:tf.global_variables_initializer().run()with tf.variable_scope("", reuse=True):print(sess.run(tf.get_variable("v")))# 在計(jì)算圖 g2 中讀取變量 “v” 的取值。 with tf.Session(graph=g2) as sess:tf.global_variables_initializer().run()with tf.variable_scope("", reuse=True):print(sess.run(tf.get_variable("v")))輸出
2019-03-08 16:51:32.897748: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2019-03-08 16:51:33.012464: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:897] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2019-03-08 16:51:33.013465: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1405] Found device 0 with properties: name: GeForce GTX 1060 major: 6 minor: 1 memoryClockRate(GHz): 1.6705 pciBusID: 0000:01:00.0 totalMemory: 5.94GiB freeMemory: 5.57GiB 2019-03-08 16:51:33.013487: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1484] Adding visible gpu devices: 0 2019-03-08 16:51:33.239035: I tensorflow/core/common_runtime/gpu/gpu_device.cc:965] Device interconnect StreamExecutor with strength 1 edge matrix: 2019-03-08 16:51:33.239077: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0 2019-03-08 16:51:33.239084: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] 0: N 2019-03-08 16:51:33.239567: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1097] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 5338 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1060, pci bus id: 0000:01:00.0, compute capability: 6.1) [0.] 2019-03-08 16:51:33.305269: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1484] Adding visible gpu devices: 0 2019-03-08 16:51:33.305352: I tensorflow/core/common_runtime/gpu/gpu_device.cc:965] Device interconnect StreamExecutor with strength 1 edge matrix: 2019-03-08 16:51:33.305360: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0 2019-03-08 16:51:33.305365: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] 0: N 2019-03-08 16:51:33.305609: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1097] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 5338 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1060, pci bus id: 0000:01:00.0, compute capability: 6.1) [1.](2)相關(guān)設(shè)置
通過(guò) tf.Graph.device 函數(shù)可以指定運(yùn)行計(jì)算的設(shè)備(GPU)。
g = tf.Graph() with g.device('/gpu:0'):result = a + b在一個(gè)計(jì)算圖中,可以通過(guò)集合(collection)來(lái)管理不同類別的資源。eg:tf.add_to_collection 函數(shù)可將資源加入一個(gè)或多個(gè)集合中,然后通過(guò) tf.get_collection 函數(shù)獲取一個(gè)集合里面所有的資源。資源包括:張量、變量或運(yùn)行 tf 程序所需的隊(duì)列資源等等。
(3)TF 中維護(hù)的集合列表
| tf.GraphKeys.VARIBLES | 所有變量 | 持久化TF 模型 |
| tf.GraphKeys.TRAINABLE_VARIABLES | 可學(xué)習(xí)的變量(NN中參數(shù)) | 模型訓(xùn)練、生成模型可視化等內(nèi)容 |
| tf.GraphKeys.SUMMARIES | 日志生成相關(guān)的張量 | TF 計(jì)算可視化 |
| tf.GraphKeys.QUEUE_RUNNERS | 處理輸入的 QueueRunner | 處理輸入 |
| tf.GraphKeys.MOVING_AVERAGE_VARIABLES | 所有計(jì)算了滑動(dòng)平均值的變量 | 計(jì)算變量的滑動(dòng)平均值 |
二、數(shù)據(jù)模型——張量
1、張量的概念
在 Tensorflow 中所有的數(shù)據(jù)都是通過(guò)張量的形式表示,簡(jiǎn)單理解為 多維數(shù)組。但張量在 Tensorflow 中的實(shí)現(xiàn)不是直接采用數(shù)組的形式,張量只是對(duì) TF 中運(yùn)算結(jié)果的引用。在張量中沒(méi)有真正保存數(shù)字,而是何如得到這些數(shù)字的計(jì)算過(guò)程。
import tensorflow as tf# tf.constant 是一個(gè)計(jì)算,這個(gè)計(jì)算的結(jié)果是一個(gè)張量,保存在變量 a 中。 a = tf.constant([1.0, 2.0], name="a") b = tf.constant([2.0, 3.0], name="b") result = tf.add(a, b, name="add") print(result)輸出
Tensor("add_2:0", shape=(2,), dtype=float32)分析:
一個(gè)張量中主要保存三個(gè)屬性:名字(name)、維度(shape)和類型(type)。
- name:一個(gè)張量的唯一標(biāo)識(shí)符,同時(shí)給出這個(gè)張量是如何計(jì)算出來(lái)的。命名格式:node:src_output ,其中 node 為節(jié)點(diǎn)名稱,src_output 表示當(dāng)前張量來(lái)自節(jié)點(diǎn)的第幾個(gè)輸出。add:0 表示result這個(gè)張量是計(jì)算節(jié)點(diǎn) add 輸出的第一個(gè)結(jié)果。
- shape:張量的維度。shape=(2,) 表示張量 result 是一個(gè)長(zhǎng)度為 2 的一維數(shù)組。
- type:張量的唯一類型。TF 對(duì)參與運(yùn)算的張量進(jìn)行類型檢查,若不匹配則會(huì)報(bào)錯(cuò)。例如:
輸出
ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("b_1:0", shape=(2,), dtype=float32)'通過(guò)指定 dtype 來(lái)明確指出變量或常量的類型。 TF 支持14種不同的類型,主要包括:實(shí)數(shù)( tf.float32、tf.float64 )、整數(shù)( tf.int8、tf.int16、tf.int32、tf.int64、tf.uint8 )、布爾型( tf.bool ) 和復(fù)數(shù)(tf.complex64、tf.complex128)
2、張量的使用
(1)對(duì)中間計(jì)算結(jié)果的引用
當(dāng)一個(gè)計(jì)算包含很多中間結(jié)果時(shí),使用張量可以大大提高代碼的可讀性。同時(shí),可以方便獲取中間結(jié)果。
# 使用張量記錄中間結(jié)果 a = tf.constant([1.0, 2.0], name="a") b = tf.constant([2.0, 3.0], name="b") result = a + b# 直接計(jì)算向量的和 result = tf.constant([1.0, 2.0], name="a") + tf.constant([2.0, 3.0], name="b")(2)獲取計(jì)算結(jié)果
當(dāng)計(jì)算圖構(gòu)造完成之后,張量可以用來(lái)獲取計(jì)算結(jié)果。
tf.Session().run(result) 獲取計(jì)算結(jié)果。
三、運(yùn)行模型——會(huì)話(session)
使用會(huì)話(session)執(zhí)行定義好的運(yùn)算。
會(huì)話擁有并管理 TF 程序運(yùn)行是所有的資源,在所有計(jì)算完成之后需要關(guān)閉會(huì)話來(lái)幫助系統(tǒng)回收資源,否則會(huì)出現(xiàn)資源泄露的問(wèn)題。
1、兩種模式
- 需要明確調(diào)用會(huì)話生成函數(shù)和關(guān)閉會(huì)話函數(shù)。該模式代碼流程如下:
在這種模式下,在所有計(jì)算完成之后,需要明確調(diào)用 Session.close() 函數(shù)來(lái)關(guān)閉會(huì)話并釋放資源。但是,若程序異常退出則不會(huì)執(zhí)行該函數(shù)。
==》
- 通過(guò) Python 的上下文管理器來(lái)使用會(huì)話。
2、默認(rèn)會(huì)話設(shè)置
TF 不會(huì)自動(dòng)生成默認(rèn)的會(huì)話,而是需要手動(dòng)指定。當(dāng)默認(rèn)的會(huì)話被指定之后,可通過(guò) tf.Tensor.eval 函數(shù)計(jì)算一個(gè)張量的值。
sess = tf.Session() with sess.as_default():print(result.eval())# 兩部分等價(jià) sess = tf.Session() print(sess.run(result)) print(result.eval(session=sess))tf.InteractiveSession() 函數(shù)可以自動(dòng)將生成的會(huì)話注冊(cè)為默認(rèn)會(huì)話。
sess = tf.InteractiveSession() print(result.eval()) sess.close()3、配置會(huì)話
配置會(huì)話:通過(guò) tf.ConfigProto 函數(shù)配置需要生成的會(huì)話。通過(guò) tf.ConfigProto 可以配置類似并行的線程數(shù)、GPU分配策略、運(yùn)算超時(shí)時(shí)間等參數(shù)。
最常用的參數(shù):
- allow_soft_placement:布爾型的參數(shù),當(dāng)它為 True 時(shí),以下任意一個(gè)條件成立時(shí),GPU上的運(yùn)算可以放到CPU上進(jìn)行:
- 運(yùn)算無(wú)法在 GPU 上執(zhí)行;
- 沒(méi)有GPU資源;
- 運(yùn)算輸入包含對(duì)CPU計(jì)算結(jié)果的引用。
- log_device_placement:當(dāng)它為 True 時(shí),日志中將會(huì)記錄每個(gè)節(jié)點(diǎn)被安排在哪個(gè)設(shè)可備上以方便調(diào)試;實(shí)際中,設(shè)置為 False 可減少日志量
四、實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)
1、過(guò)程
使用神經(jīng)網(wǎng)絡(luò)解決分類問(wèn)題可分為以下步驟:
(1) 提取問(wèn)題中實(shí)體的特征向量作為神經(jīng)網(wǎng)絡(luò)的輸入;
(2) 定義網(wǎng)絡(luò)結(jié)構(gòu);
(3) 神經(jīng)網(wǎng)絡(luò)的訓(xùn)練(調(diào)整參數(shù))
(4) 預(yù)測(cè)未知數(shù)據(jù)。
2、前向傳播算法
TF 程序
3、神經(jīng)網(wǎng)絡(luò)參數(shù) 與 TensorFlow變量
側(cè)重點(diǎn): Tensorflow 是如何組織、保存及使用神經(jīng)網(wǎng)絡(luò)中的參數(shù)。
(1)tf.Variable(變量)
作用:保存和更新神經(jīng)網(wǎng)絡(luò)中的參數(shù),需要進(jìn)行初始化,還可設(shè)置為常數(shù)或通過(guò)其他變量的初始值計(jì)算得到。
神經(jīng)網(wǎng)絡(luò)中,常見(jiàn)的初始化:隨機(jī)初始化。
## 聲明均值為0,標(biāo)準(zhǔn)差為2的2*3隨機(jī)數(shù)矩陣。mean參數(shù)可以設(shè)置平均值,默認(rèn)為0 weights = tf.Variable(tf.random_normal([2, 3], stddev=2))隨機(jī)數(shù)生成函數(shù)
| tf.random_normal | 正態(tài)分布 | 均值、標(biāo)準(zhǔn)差、取值類型 |
| tf.truncated_normal | 正態(tài)分布,若隨機(jī)生成的值偏離均值超過(guò)2個(gè)標(biāo)準(zhǔn)差,則重新生成 | 均值、標(biāo)準(zhǔn)差、取值類型 |
| tf.random_uniform | 均勻分布 | 最大取值、最小取值、取值類型 |
| tf.random_gamma | Gamma分布 | 形狀參數(shù)alpha、尺度參數(shù)beta、取值類型 |
(2)常數(shù)初始化
| tf.zeros | 生成全0數(shù)組 | tf.zeros([2, 3], int32)->[[0, 0, 0], [0, 0, 0]] |
| tf.ones | 生成全1數(shù)組 | tf.ones([2, 3], int32)->[[1, 1, 1], [1, 1, 1]] |
| tf.fill | 生成一個(gè)全部為給定數(shù)字的數(shù)組 | tf.fill([2, 3], 9)->[[9, 9, 9], [9, 9, 9]] |
| tf.constant | 生成一個(gè)給定值的常量 | tf.constant([1, 2, 3])->[1, 2, 3] |
(3)偏置項(xiàng)(bias)設(shè)置
bias 通常使用常數(shù)來(lái)設(shè)置。
## 設(shè)置初值全為0且長(zhǎng)度為3的變量 biases = tf.Variable(tf.zeros([3]))(4)其他變量的初始值進(jìn)行初始化
w2 = tf.Variable(weights.initialized_value()) w3 = tf.Variable(weights.initialized_value() * 2.0)(5)樣例
import tensorflow as tf# 聲明w1、w2兩個(gè)變量。seed參數(shù)設(shè)置隨機(jī)種子,保證每次結(jié)果一致 w1 = tf.Variable(tf.random_normal((2, 3), stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal((3, 1), stddev=1, seed=1))# 定義為一個(gè)1*2矩陣 x = tf.constant([[0.7, 0.9]])# 前向傳播 a = tf.matmul(x, w1) y = tf.matmul(a, w2)sess = tf.Session() sess.run(w1.initializer) # 初始化 w1 sess.run(w2.initializer) # 初始化 w2print(sess.run(y)) sess.close()輸出
[[3.957578]]通過(guò) tf.global_variables_initalizer 函數(shù)實(shí)現(xiàn)初始化所有變量。
init_op = tf.global_variable_initalizer() sess.run(init_op)4、通過(guò)Tensorflow訓(xùn)練神經(jīng)網(wǎng)絡(luò)模型
使用反向傳播算法訓(xùn)練神經(jīng)網(wǎng)絡(luò)的流程圖。
反向傳播算法實(shí)現(xiàn)了一個(gè)迭代過(guò)程。在每次迭代的開(kāi)始,首先需要選取一小部分訓(xùn)練數(shù)據(jù)(batch)。然后,這個(gè) batch 的樣例會(huì)通過(guò)前向傳播算法得到神經(jīng)網(wǎng)絡(luò)模型的預(yù)測(cè)結(jié)果,并計(jì)算與 ground truth 之間的差距。最后,反向傳播算法通過(guò)這個(gè)差距,更新神經(jīng)網(wǎng)絡(luò)的參數(shù),使得預(yù)測(cè)結(jié)果與 ground truth 更加接近。
5、完整代碼
import tensorflow as tf from numpy.random import RandomState# 設(shè)置訓(xùn)練數(shù)據(jù) batch 大小 batch_size = 8# 定義神經(jīng)網(wǎng)絡(luò)參數(shù) w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))# 訓(xùn)練數(shù)據(jù) x = tf.placeholder(tf.float32, shape=(None, 2), name='x-input') y_ = tf.placeholder(tf.float32, shape=(None, 1), name='y-input')# 前向傳播 a = tf.matmul(x, w1) y = tf.matmul(a, w2)# 損失函數(shù)和反向傳播過(guò)程 cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0))) train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)# 通過(guò)隨機(jī)數(shù)生成一個(gè)模擬數(shù)據(jù)集 rdm = RandomState(1) dataset_size = 120 X = rdm.rand(dataset_size, 2) Y = [[int(x1 + x2) < 1] for (x1, x2) in X]# 創(chuàng)建會(huì)話來(lái)運(yùn)行 TF 程序 with tf.Session() as sess:init_op = tf.initialize_all_variables()# 初始化變量sess.run(init_op)print(sess.run(w1))print(sess.run(w2))# 設(shè)置訓(xùn)練的輪數(shù)STEPS = 5000for i in range(STEPS):# 每次選取batch_size個(gè)樣本進(jìn)行訓(xùn)練start = (i * batch_size) % dataset_sizeend = min(start + batch_size, dataset_size)# 通過(guò)選取的樣本訓(xùn)練神經(jīng)網(wǎng)絡(luò)并更新參數(shù)sess.run(train_step, feed_dict={x: X[start: end], y_:Y[start: end]})if i % 1000 == 0:# 每隔一段時(shí)間計(jì)算所有數(shù)據(jù)上的交叉熵?fù)p失函數(shù)。total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_: Y})print("After %d training step(s), cross entropy on all data is %g" % (i, total_cross_entropy))print(sess.run(w1))print(sess.run(w2))輸出
2019-03-09 12:22:31.932975: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2019-03-09 12:22:32.053557: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:897] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2019-03-09 12:22:32.054556: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1405] Found device 0 with properties: name: GeForce GTX 1060 major: 6 minor: 1 memoryClockRate(GHz): 1.6705 pciBusID: 0000:01:00.0 totalMemory: 5.94GiB freeMemory: 5.49GiB 2019-03-09 12:22:32.054595: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1484] Adding visible gpu devices: 0 2019-03-09 12:22:32.284779: I tensorflow/core/common_runtime/gpu/gpu_device.cc:965] Device interconnect StreamExecutor with strength 1 edge matrix: 2019-03-09 12:22:32.284804: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0 2019-03-09 12:22:32.284810: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] 0: N 2019-03-09 12:22:32.285118: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1097] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 5257 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1060, pci bus id: 0000:01:00.0, compute capability: 6.1) WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/tf_should_use.py:118: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02. Instructions for updating: Use `tf.global_variables_initializer` instead. [[-0.8113182 1.4845988 0.06532937][-2.4427042 0.0992484 0.5912243 ]] [[-0.8113182 ][ 1.4845988 ][ 0.06532937]] After 0 training step(s), cross entropy on all data is 0.071992 After 1000 training step(s), cross entropy on all data is 0.0167723 After 2000 training step(s), cross entropy on all data is 0.00941592 After 3000 training step(s), cross entropy on all data is 0.00749986 After 4000 training step(s), cross entropy on all data is 0.00600073 [[-1.984426 2.6028152 1.7178398][-3.4925323 1.0919542 2.1556146]] [[-1.8463261][ 2.7097478][ 1.4506569]]關(guān)鍵點(diǎn):
tf提供了 placeholder 機(jī)制用于提供輸入數(shù)據(jù)。 placeholder 相當(dāng)于定義了一個(gè)位置,這個(gè)位置中的數(shù)據(jù)在程序運(yùn)行時(shí)再指定。定義 placeholder 時(shí),需要指定類型,但是不一定需要維度,因?yàn)榭梢愿鶕?jù)提供的數(shù)據(jù)推導(dǎo)出來(lái)。
總結(jié)
以上是生活随笔為你收集整理的【TensorFlow】笔记1:入门笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【NLP】自然语言处理 完整流程
- 下一篇: 【LeetCode】390.消除游戏