文章目錄
- 一、深度學習的介紹
- 1.1 深度學習與機器學習的區別
- 1.1.1 特征提取方面
- 1.1.2 資料量和計算性能要求
- 1.1.3 演算法代表
- 1.2 深度學習的應用場景
- 1.3 深度學習框架介紹
- 1.3.1 常見深度學習框架對比
- 1.3.2 tensorflow的特點
- 1.3.3 tensorflow的安裝
- 二、tensorflow框架介紹
- 2.1 TF資料流圖
- 2.1.1 案例:tensorflow實作一個加法運算
- 2.2 圖與TensorBoard
- 2.2.1 什么是圖結構
- 2.2.2 圖相關操作
- 2.2.3 TensorBoard可視化學習
- 2.2.4 OP
- 2.3 會話
- 2.3.1 會話創建
- 2.4 張量
- 2.4.1 張量(Tensor)
- 2.4.2 創建張量的指令
- 2.4.3 張量的變換
- 2.4.4 張量的數學運算
- 2.5 變數OP
- 2.5.1 創建變數
- 2.5.2 使用tf.variable_scope()修改變數的命名空間
- 2.6 高級API
- 2.6.1 其他基礎API
- 2.6.2 高級API
- 2.7 案例:實作線性回歸
- 2.7.2 案例:實作線性回歸的訓練
- 2.7.3 增加其他功能
學習目標:
- 第一天:tensorflow框架實用
- 第二天:資料讀取、神經網路基礎
- 第三天:卷積神經網路、驗證碼識別
第一天:
- 學習學習介紹
- tensorflow框架的使用
-
- 1)tensorflow的結構
-
- 2)tensorflow的各個組件:圖、會話、張量、變數
-
- 3)簡單的線性回歸案例----將TensorFlow用起來
一、深度學習的介紹
1.1 深度學習與機器學習的區別
學習目標:知道深度學習與機器學習的區別
區別:深度學習沒有特征提取

1.1.1 特征提取方面
- 機器學習的特征工程步驟是要靠手動完成的,而且需要大量領域專業知識
- 深度學習通常由多個層組成,它們通常將更簡單的模型組合在一起,將資料從一層傳遞到另一層來構建更復雜的模型,通過訓練大量資料自動得到模型,不需要人工特征提取環節
深度學習演算法試圖從資料中學習高級功能,這是深度學習的一個非常獨特的部分,因此,減少了為每個問題開發新特征提取器的任務,適合用在難提取特征的影像、語音、自然語言處理領域
1.1.2 資料量和計算性能要求
機器學習需要的執行時間遠少于深度學習,深度學習引數往往很龐大,需要通過大量
資料的多次優化來訓練引數

- 第一,深度學習需要大量的訓練資料集
- 第二,訓練深度神經網路需要大量的算力
可能要花費數天、甚至數周的時間,才能使用數百萬張影像的資料集訓練出一個深度網路,所以深度學習通常需要強大的GPU服務器來進行計算
1.1.3 演算法代表
機器學習:樸素貝葉斯,決策樹
深度學習:神經網路
1.2 深度學習的應用場景
影像識別:物體識別、場景識別、車型識別、人臉檢測跟蹤、人臉關鍵點定位、人臉身份認證
自然語言處理技術:機器翻譯、文本識別、聊天對話
語音技術:語音識別
1.3 深度學習框架介紹
1.3.1 常見深度學習框架對比


1.3.2 tensorflow的特點
官網:https://www.tensorflow.org/
1.3.3 tensorflow的安裝
1 CPU版本
2 GPU版本:核芯數量多,更適合處理并行任務
pip install tensorflow==1.8 -i https://pypi.douban.com/simple
二、tensorflow框架介紹
2.1 TF資料流圖
學習目標:說明tensorflow的資料流圖結構
2.1.1 案例:tensorflow實作一個加法運算
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def tensorflow_demo():
"""
tensorflow的基本結構
:return:
"""
# tensorflow實作加法運算
a_t = tf.constant(2)
b_t = tf.constant(3)
c_t = a_t + b_t
print("c_t:", c_t)
# 開啟會話
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print("c_t_value:", c_t_value)
return None
if __name__ == "__main__":
tensorflow_demo()
c_t: Tensor("add:0", shape=(), dtype=int32)
c_t_value: 5
2 TensorFlow結構分析
TensorFlow程式通常被組織成一個構件圖階段和一個執行圖階段,
在構建階段,資料與操作的執行步驟被描述為一個圖
在執行階段,使用會話執行構建好的圖中的操作
圖:這是TensorFlow將計算表示為指令之間的依賴關系的一種表示法
會話:TensorFlow跨一個或多個本地或遠程設備運行資料流圖的機制
張量:TensorFlow中的基本資料物件
節點:提供圖當中執行的操作
2.2 圖與TensorBoard
學習目標:
- 說明圖的基本使用
- 應用tf.Graph創建圖,tf.get_default_graph獲取默認圖
- 知道開啟TensorBoard程序
- 知道圖當中op的名字以及命名空間
2.2.1 什么是圖結構
圖包含了一組tf.Operation代表的計算單元物件和tf.Tensor代表的計算單元之間流動的資料
2.2.2 圖相關操作
1 默認圖
通常tensorflow會默認幫我們創建一張圖
查看默認圖的兩種方法:
- 通過呼叫**tf.get_default_graph()**訪問,要將操作添加到默認圖形中,直接創建OP即可
- op、sess都含有graph屬性,默認都在一張圖中
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def graph_demo():
"""
圖的演示
:return:
"""
# tensorflow實作加法運算
a_t = tf.constant(2)
b_t = tf.constant(3)
c_t = a_t + b_t
print("c_t:", c_t)
# 查看默認圖
# 方法1:呼叫方法
default_g = tf.get_default_graph()
print("default_g:", default_g)
# 方法2:查看屬性
print("a_t的圖屬性:", a_t.graph)
print("c_t的圖屬性:", c_t.graph)
# 開啟會話
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print("c_t_value:", c_t_value)
print("sess的圖屬性:", sess.graph)
return None
if __name__ == "__main__":
graph_demo()
c_t: Tensor("add:0", shape=(), dtype=int32)
default_g: <tensorflow.python.framework.ops.Graph object at 0x000002A49DEA72B0>
a_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000002A49DEA72B0>
c_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000002A49DEA72B0>
c_t_value: 5
sess的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000002A49DEA72B0>
2 創建圖
- 可以通過**tf.Graph()**自定義創建圖
- 如果要在這張圖中創建OP,典型用法是使用**tf.Graph.as_default()**背景關系管理器
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def graph_demo():
"""
圖的演示
:return:
"""
# tensorflow實作加法運算
a_t = tf.constant(2)
b_t = tf.constant(3)
c_t = a_t + b_t
print("c_t:", c_t)
# 查看默認圖
# 方法1:呼叫方法
default_g = tf.get_default_graph()
print("default_g:", default_g)
# 方法2:查看屬性
print("a_t的圖屬性:", a_t.graph)
print("c_t的圖屬性:", c_t.graph)
# 開啟會話
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print("c_t_value:", c_t_value)
print("sess的圖屬性:", sess.graph)
print("--------------------------------")
# 自定義圖
new_g = tf.Graph()
# 在自己的圖中定義資料和操作
with new_g.as_default():
a_new = tf.constant(20)
b_new = tf.constant(30)
c_new = a_new + b_new
print("c_new:", c_new)
print("a_new的圖屬性:", a_new.graph)
print("c_new的圖屬性:", c_new.graph)
# 開啟new_g的會話
with tf.Session(graph=new_g) as new_sess:
# 試圖運行自定義圖中的資料,操作
c_new_value = new_sess.run(c_new)
print("c_new_value:", c_new_value)
print("new_sess的圖屬性:", new_sess.graph)
return None
if __name__ == "__main__":
graph_demo()
c_t: Tensor("add:0", shape=(), dtype=int32)
default_g: <tensorflow.python.framework.ops.Graph object at 0x00000152C1C87400>
a_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152C1C87400>
c_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152C1C87400>
c_t_value: 5
sess的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152C1C87400>
--------------------------------
c_new: Tensor("add:0", shape=(), dtype=int32)
a_new的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152E6FFD9B0>
c_new的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152E6FFD9B0>
c_new_value: 50
new_sess的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x00000152E6FFD9B0>
2.2.3 TensorBoard可視化學習
tensorflow可用于訓練大規模深度神經網路所需的計算,使用該工具設計的計算往往復雜而深奧,為了更方便tensorflow程式的理解、除錯與優化,tensorflow提供了TensorBoard可視化工具
實作程式可視化程序:
1 資料序列化-events檔案
TensorBoard通過讀取TensorFlow的事件檔案來運行,需要將資料生成一個序列化的Summary protobuf物件
tf.summary.FileWriter(path, graph=sess.graph)
2 啟動TensorBoard
tensorboard --logdir=path
例:
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def graph_demo():
"""
圖的演示
:return:
"""
# tensorflow實作加法運算
a_t = tf.constant(2)
b_t = tf.constant(3)
c_t = a_t + b_t
print("c_t:", c_t)
# 查看默認圖
# 方法1:呼叫方法
default_g = tf.get_default_graph()
print("default_g:", default_g)
# 方法2:查看屬性
print("a_t的圖屬性:", a_t.graph)
print("c_t的圖屬性:", c_t.graph)
# 開啟會話
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print("c_t_value:", c_t_value)
print("sess的圖屬性:", sess.graph)
# 1)將圖寫入本地生成events檔案
tf.summary.FileWriter("summary", graph=sess.graph) # tmp檔案夾下
print("--------------------------------")
# 自定義圖
new_g = tf.Graph()
# 在自己的圖中定義資料和操作
with new_g.as_default():
a_new = tf.constant(20)
b_new = tf.constant(30)
c_new = a_new + b_new
print("c_new:", c_new)
print("a_new的圖屬性:", a_new.graph)
print("c_new的圖屬性:", c_new.graph)
# 開啟new_g的會話
with tf.Session(graph=new_g) as new_sess:
# 試圖運行自定義圖中的資料,操作
c_new_value = new_sess.run(c_new)
print("c_new_value:", c_new_value)
print("new_sess的圖屬性:", new_sess.graph)
return None
if __name__ == "__main__":
graph_demo()

之后,在終端輸入:

得到鏈接,點擊網址鏈接


成功!
2.2.4 OP
即操作物件
1 常見OP
那些是OP

| 操作函式 | 操作物件 |
|---|---|
| tf.constant(Tensor物件) | 輸入Tensor物件-Const輸出 Tensor物件 |
| tf.add(Tensor物件1,Tensor物件2) | 輸入(Tensor物件1,Tensor物件2) ,add物件,輸出 Tensor物件3 |
- 一個圖一個命名空間,互不干擾影響
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def graph_demo():
"""
圖的演示
:return:
"""
# tensorflow實作加法運算
a_t = tf.constant(2, name="a_t")
b_t = tf.constant(3, name="b_t")
c_t = tf.add(a_t, b_t, name="c_t")
print("c_t:", c_t)
# 查看默認圖
# 方法1:呼叫方法
default_g = tf.get_default_graph()
print("default_g:", default_g)
# 方法2:查看屬性
print("a_t的圖屬性:", a_t.graph)
print("c_t的圖屬性:", c_t.graph)
# 開啟會話
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print("c_t_value:", c_t_value)
print("sess的圖屬性:", sess.graph)
# 1)將圖寫入本地生成events檔案
tf.summary.FileWriter("logs", graph=sess.graph)
print("--------------------------------")
# 自定義圖
new_g = tf.Graph()
# 在自己的圖中定義資料和操作
with new_g.as_default():
a_new = tf.constant(20, name="a_new")
b_new = tf.constant(30, name="b_new")
c_new = tf.add(a_new, b_new, name="c_new")
print("c_new:", c_new)
print("a_new的圖屬性:", a_new.graph)
print("c_new的圖屬性:", c_new.graph)
tf.summary.FileWriter("log2", graph=sess.graph)
# 開啟new_g的會話
with tf.Session(graph=new_g) as new_sess:
# 試圖運行自定義圖中的資料,操作
c_new_value = new_sess.run(c_new)
print("c_new_value:", c_new_value)
print("new_sess的圖屬性:", new_sess.graph)
return None
if __name__ == "__main__":
graph_demo()

2.3 會話
學習目標:
- 應用sess.rn或者eval運行圖程式并獲取張量值
- 應用feed_dict機制實作運行時填充資料
- 應用placeholder實作創建占位符
2.3.1 會話創建
- tf.Session:用于完整的程式當中
- tf.InteractiveSession:用于互動式背景關系中的TensorFlow,例如shell

背景關系管理器:
with tf.Session() as sess:
sess.run(sth)
- target:如果將此引數留空(默認設定),會話將僅使用本地計算機中的設備,可以指定grpc://網址,以便指定TensorFlow服務器的地址,這使得會話可以訪問該服務器控制的計算機上的所有設備
- graph:默認情況下,新的tf.Session將系結到當前的默認圖
- config:此引數允許您指定一個tf.ConfigProto以便控制會話的行為,例如,ConfigProto協議用于列印設備使用資訊
# 運行會話并列印設備資訊
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))
2 會話的run()
通過使用sess.run(0)來運行operation
run(fetches, feed_dict=None, options=None, run_metadata=None)
- fetches:單一的operation,或者串列、元組(其他不屬于tensorflow的型別不行)
- feed_dict:引數運行呼叫者覆寫圖中張量的值,運行時賦值,與tf.placeholder搭配使用,則會檢查值的形式是否與占位符兼容
# 創建圖
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a + b
# 創建會話
sess = tf.Session()
# 計算C的值
print(sess.run(c))
print(c.eval(session=sess))
3 feed操作
- placeholder提供占位符,run時候通過feed_dict指定引數
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def session_demo():
"""
會話的演示:列印設備資訊
:return:
"""
# tensorflow實作加法運算
a_t = tf.constant(2, name="a_t")
b_t = tf.constant(3, name="b_t")
c_t = tf.add(a_t, b_t, name="c_t")
print("a_t", a_t)
print("b_t", b_t)
print("c_t:", c_t)
print("------------------------------")
# 定義占位符
a_ph = tf.placeholder(tf.float32)
b_ph = tf.placeholder(tf.float32)
c_ph = tf.add(a_ph, b_ph)
print("a_ph:", a_ph)
print("b_ph:", b_ph)
print("c_ph:", c_ph)
print("------------------------------")
# 查看默認圖
# 方法1:呼叫方法
default_g = tf.get_default_graph()
print("default_g:", default_g)
# 方法2:查看屬性
print("a_t的圖屬性:", a_t.graph)
print("c_t的圖屬性:", c_t.graph)
print("-------------------------------")
# 開啟會話
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
log_device_placement=True)) as sess:
# 運行placeholder
c_ph_value = sess.run(c_ph, feed_dict={a_ph:3.9, b_ph:4.8})
print('c_ph_value', c_ph_value)
print("------------------------------")
abc = sess.run([a_t, b_t, c_t]) # 傳入串列,回傳串列
print("abc:", abc)
print("c_t_value;", c_t.eval())
print("sess的圖屬性:", sess.graph)
#tf.summary.FileWriter("logs", graph=sess.graph) # 1)將圖寫入本地生成events檔案
if __name__ == "__main__":
session_demo()
a_t Tensor("a_t:0", shape=(), dtype=int32)
b_t Tensor("b_t:0", shape=(), dtype=int32)
c_t: Tensor("c_t:0", shape=(), dtype=int32)
------------------------------
a_ph: Tensor("Placeholder:0", dtype=float32)
b_ph: Tensor("Placeholder_1:0", dtype=float32)
c_ph: Tensor("Add:0", dtype=float32)
------------------------------
default_g: <tensorflow.python.framework.ops.Graph object at 0x000001618EF65748>
a_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000001618EF65748>
c_t的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000001618EF65748>
-------------------------------
Device mapping: no known devices.
Add: (Add): /job:localhost/replica:0/task:0/device:CPU:0
c_t: (Add): /job:localhost/replica:0/task:0/device:CPU:0
Placeholder_1: (Placeholder): /job:localhost/replica:0/task:0/device:CPU:0
Placeholder: (Placeholder): /job:localhost/replica:0/task:0/device:CPU:0
b_t: (Const): /job:localhost/replica:0/task:0/device:CPU:0
a_t: (Const): /job:localhost/replica:0/task:0/device:CPU:0
c_ph_value 8.700001
------------------------------
abc: [2, 3, 5]
c_t_value; 5
sess的圖屬性: <tensorflow.python.framework.ops.Graph object at 0x000001618EF65748>
2.4 張量
學習目標:
- 知道常見的TensorFlow創建張量
- 知道常見的張量數學運算操作
- 說明numpy的陣列與張量相同性
- 說明張量的兩種形狀改變特點
- 應用set_shape和tf.reshape山西愛你張量形狀的修改
- 應用tf.matmul實作張量的矩陣運算修改
- 應用tf.cast實作張量的型別
2.4.1 張量(Tensor)
TensorFlow的張量就是一個N維陣列,型別為tf.Tensor,
張量:在計算機當中如何存盤?N維陣列
標量:一個數字----0階張量
向量:一維陣列-----1階張量
矩陣:二維陣列------2階張量
- type:資料型別
- shape:形狀(階)
1 張量的型別

2 張量的階

未指定型別時,默認型別:
- 整型:tf.int32
- 浮點型:tf.float32
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def tensor_demo():
"""
張量的演示
:return:
"""
tensor1 = tf.constant(4.0)
tensor2 = tf.constant([1,2,3,4]) # 未指定型別,默認型別
linear_squares = tf.constant([[4],[9],[16],[25]],dtype=tf.int32)
print("tensor1:", tensor1)
print("tensor2:", tensor2)
print("linear_square:", linear_squares)
return None
if __name__ == "__main__":
tensor_demo()
tensor1: Tensor("Const:0", shape=(), dtype=float32)
tensor2: Tensor("Const_1:0", shape=(4,), dtype=int32)
linear_square: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
2.4.2 創建張量的指令
固定值張量
1 創建多個0
tf.zeros(shape, dtype=tf.float32, name=None)
2 創建多個1
tf.ones(shape, dtype=tf.float32, name=None)
3 創建常數張量
tf.constant(value, dtype=tf.float32, name='Const')
用.eval可以查看值

2.4.3 張量的變換
1 型別改變
- tf.string_to_number(string_tensor, out_type=None, name=None)
- tf.to_double(x, name=‘ToDouble’)
- tf.to_float(x, name=‘ToFloat’)
- tf.to_bfloat16(x, name=“ToBFloat16”)
- tf.to_int32(x, name=‘Tolnt32’)
- tf.to_int64(x, name=‘Tolnt64’)
- tf.cast(x, dtype, name=None),通用型別轉換
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def tensor_demo():
"""
張量的演示
:return:
"""
tensor1 = tf.constant(4.0)
tensor2 = tf.constant([1,2,3,4]) # 未指定型別,默認型別
linear_squares = tf.constant([[4],[9],[16],[25]],dtype=tf.int32)
print("tensor1:", tensor1)
print("tensor2:", tensor2)
print("linear_square:", linear_squares)
print("----------------")
# 張量型別的修改:不會改變原始的Tensor
l_cast = tf.cast(linear_squares, dtype=tf.float32)
print("linear_square_after:", linear_squares)
print('l_cast:', l_cast)
return None
if __name__ == "__main__":
tensor_demo()
tensor1: Tensor("Const:0", shape=(), dtype=float32)
tensor2: Tensor("Const_1:0", shape=(4,), dtype=int32)
linear_square: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
----------------
linear_square_after: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
l_cast: Tensor("Cast:0", shape=(4, 1), dtype=float32)
2 形狀改變
tensorflow的張量具有兩種形狀變換,動態形狀和靜態形狀
-
tf.reshape:改變動態形狀
-
tf.set_shape:改變靜態形狀
-
靜態形狀:初始創建張量時的形狀
-
動態形狀:
什么情況下可以改變靜態形狀:只有在形狀還沒有完全固定下來的情況下;轉換形狀的時候,只能一維到一維,二維到二維,而不能跨維度改變形狀
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def tensor_demo():
"""
張量的演示
:return:
"""
tensor1 = tf.constant(4.0)
tensor2 = tf.constant([1,2,3,4]) # 未指定型別,默認型別
linear_squares = tf.constant([[4],[9],[16],[25]],dtype=tf.int32)
print("tensor1:", tensor1)
print("tensor2:", tensor2)
print("linear_square:", linear_squares)
print("----------------")
# 張量型別的修改:不會改變原始的Tensor
l_cast = tf.cast(linear_squares, dtype=tf.float32)
print("linear_square_after:", linear_squares)
print('l_cast:', l_cast)
print('------------------')
# 更新、改變靜態形狀
# 定義占位符
a_p = tf.placeholder(dtype=tf.float32, shape=[None, None]) # 形狀沒有完全固定下來的靜態形狀
b_p = tf.placeholder(dtype=tf.float32, shape=[None, 10])
c_p = tf.placeholder(dtype=tf.float32, shape=[3, 2])
print("a_p:", a_p)
print("b_p:", b_p)
print("c_p:", c_p)
print("-----------------------")
# 更新形狀未確定的部分
a_p.set_shape([2,3])
b_p.set_shape([2,10])
print("a_p:", a_p)
print("b_p:", b_p)
print('-------------')
# 動態形狀修改
a_p_reshape = tf.reshape(a_p, shape=[2, 3, 1])
print("a_p:", a_p)
print("a_p_reshape:", a_p_reshape)
c_p_reshape = tf.reshape(c_p, shape=[2, 3, 1]) # 必須保持改變前后元素的數量一致
print("c_p:", c_p)
print("c_p_reshape:", c_p_reshape)
return None
if __name__ == "__main__":
tensor_demo()
tensor1: Tensor("Const:0", shape=(), dtype=float32)
tensor2: Tensor("Const_1:0", shape=(4,), dtype=int32)
linear_square: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
----------------
linear_square_after: Tensor("Const_2:0", shape=(4, 1), dtype=int32)
l_cast: Tensor("Cast:0", shape=(4, 1), dtype=float32)
------------------
a_p: Tensor("Placeholder:0", shape=(?, ?), dtype=float32)
b_p: Tensor("Placeholder_1:0", shape=(?, 10), dtype=float32)
c_p: Tensor("Placeholder_2:0", shape=(3, 2), dtype=float32)
-----------------------
a_p: Tensor("Placeholder:0", shape=(2, 3), dtype=float32)
b_p: Tensor("Placeholder_1:0", shape=(2, 10), dtype=float32)
-------------
a_p: Tensor("Placeholder:0", shape=(2, 3), dtype=float32)
a_p_reshape: Tensor("Reshape:0", shape=(2, 3, 1), dtype=float32)
c_p: Tensor("Placeholder_2:0", shape=(3, 2), dtype=float32)
c_p_reshape: Tensor("Reshape_1:0", shape=(2, 3, 1), dtype=float32)
2.4.4 張量的數學運算
- 算術運算子
- 基本數學函式
- 矩陣運算
- reduce操作
- 序列索引操作
2.5 變數OP
學習目標:
- 說明變數op的特殊作用
- 說明變數op的trainable引數的作用
- 應用global_variables_initializer實作變數op的初始化
變數的特點:
- 存盤持久化
- 可修改值
- 可指定被訓練
2.5.1 創建變數
tf.Variable(initia_value=None, trainable=True, collections=None, name=None)
- initial_value:初始化的值
- trainable:是否被訓練
- collections:新變數將添加到列出的圖的集合中collections,默認為[GraphKeys.GLOBAL_VARIABLES],如果trainable是True變數也被添加到圖形集合GraphKeys.TRAINABLE_VARIABLES
變數需要顯示初始化,才能運行值
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def variable_demo():
"""
變數的演示
:return:
"""
# 創建變數
a = tf.Variable(initial_value=50)
b = tf.Variable(initial_value=40)
c = tf.add(a, b)
print("a:", a)
print("b", b)
print("c", c)
print('----------------------')
# 初始化變數
init = tf.global_variables_initializer()
# 開啟會話
with tf.Session() as sess:
# 運行初始化
sess.run(init)
a_value, b_value, c_value = sess.run([a,b,c])
print("a_value:", a_value)
print("b_value", b_value)
print("c_value", c_value)
return None
if __name__ == "__main__":
variable_demo()
a: <tf.Variable 'Variable:0' shape=() dtype=int32_ref>
b <tf.Variable 'Variable_1:0' shape=() dtype=int32_ref>
c Tensor("Add:0", shape=(), dtype=int32)
----------------------
a_value: 50
b_value 40
c_value 90
2.5.2 使用tf.variable_scope()修改變數的命名空間
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def variable_demo():
"""
變數的演示
:return:
"""
# 創建變數
with tf.variable_scope("my_scope"):
a = tf.Variable(initial_value=50)
b = tf.Variable(initial_value=40)
with tf.variable_scope("your_scope"):
c = tf.add(a, b)
print("a:", a)
print("b", b)
print("c", c)
print('----------------------')
# 初始化變數
init = tf.global_variables_initializer()
# 開啟會話
with tf.Session() as sess:
# 運行初始化
sess.run(init)
a_value, b_value, c_value = sess.run([a,b,c])
print("a_value:", a_value)
print("b_value", b_value)
print("c_value", c_value)
return None
if __name__ == "__main__":
variable_demo()
a: <tf.Variable 'my_scope/Variable:0' shape=() dtype=int32_ref>
b <tf.Variable 'my_scope/Variable_1:0' shape=() dtype=int32_ref>
c Tensor("your_scope/Add:0", shape=(), dtype=int32)
----------------------
a_value: 50
b_value 40
c_value 90
2.6 高級API
2.6.1 其他基礎API
1 tf.app
這個模塊相當于為TensorFlow進行的腳本提供一個main函式入口,可以定義腳本運行的flags
2 tf.image
TensorFlow的影像處理操作,主要是一些顏色變換、變形和影像的編碼和解碼
3 tf.gfile
這個模塊提供了一組檔案操作函式
4 tf.summary
用來生成TensorBoard可用的統計日志,目前Summary主要提供了4種型別:
audio、image、histogram、scalar
5 tf.python_io
用來讀寫TFRecords檔案
6 tf.train
這個模塊提供了一些訓練器,與tf.nn結合起來,實作一些網路的優化計算
7 tf.nn
這個模塊提供了一些構建神經網路的底層函式,TensorFlow構建網路的核心模塊,其中包含了添加各種層的函式,比如添加卷積層、池化層等,
2.6.2 高級API
1 tf.keras
Kears本來是一個獨立的深度學習庫,tensorflow將其學習過來,增加這部分模塊在于快速構建模型
2 tf.layers
高級API,以便高級的概念層來定義一個模型,類似tf.kears
3 tf.contrib
tf.contrib.layers提供夠將計算圖中的網路層、正則化、摘要操作,是構建計算圖的高級操作,但是tf.contrib包含不穩定和實驗代碼,有可能以后API會改變
4 tf.estimator
一個estimator相當于model + training + evaluate 的合體,在模塊中,已經實作了幾種簡單的分類器和回歸其,包括:Baseline,learning 和 DNN,這里的DNN的網路,只是全連接網路,沒有提供卷積之類的
2.7 案例:實作線性回歸
學習目標:
- 應用op的name引數實作op的名字修改
- 應用variable_scope實作圖程式作用域的添加
- 應用scalar或histogram實作張良志的跟蹤顯示
- 應用merge_all實作張量值的合并
- 應用add_summary實作張量值的寫入檔案
- 應用tf.train.saver實作TensorFlow的模型保存以及加載
- 應用tf.app.flags實作命令列引數添加和使用
- 應用reduce_mean、square實作均方誤差計算
- 應用tf.train.GradientDescentOptimizer實作有梯度下降優化器創建
- 應用minimize函式優化損失
- 知道梯度爆炸以及常見解決技巧
2.7.2 案例:實作線性回歸的訓練
1)構建模型
2)構建損失函式:均方誤差
3)優化損失:梯度下降
準備真實資料:
x:特征值,形狀:(100,1)
y_true:目標值 (100,1)
y_true = 0.8x + 0.7 ,100個樣本
假設滿足: y =kx + b
流程分析:
(100,1) * (1,1) = (100,1)
y_predict = x * weight(1,1) + bias(1,1)
1)構建模型
y_predict = tf.matmul(x, weights) + bias
2)構造損失函式
error = tf.reduce_mean(tf.square(y_predict - y_true))
3)優化損失:梯度下降優化器
optimizer = tf.train.GrandientDescentOptimizer(learning_rate=0.01).minimize(error)
運算:
- 矩陣運算:tf.matmu(x,w)
- 平方:tf.square(error)
- 均方:tf.reduce_mean(error)
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def linear_regression():
"""
實作線性回歸
:return:
"""
# 1)準備資料
X = tf.random_normal(shape=[100, 1]) # 形狀:100行1列
y_true = tf.matmul(X, [[0.8]]) + 0.7 # y_true = 0.8x + 0.7
# 2)構造模型
# 定義模型引數,用變數
weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
y_predict = tf.matmul(X, weights) + bias
# 3)構造損失函式
error = tf.reduce_mean(tf.square(y_predict - y_true))
# 4)優化損失
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)
# 顯式地初始化變數
init = tf.global_variables_initializer()
# 開啟會話
with tf.Session() as sess:
# 初始化變數
sess.run(init)
# 查看初始化模型引數之后的值
print("訓練前模型引數為:權重%f,偏置%f,損失為%f" %
(weights.eval(), bias.eval(), error.eval()))
# 開始訓練
for i in range(200):
sess.run(optimizer)
print("第%d訓練后模型引數為:權重%f,偏置%f,損失為%f" %
(i+1, weights.eval(), bias.eval(), error.eval()))
return None
if __name__ == "__main__":
linear_regression()
...
第195訓練后模型引數為:權重0.784588,偏置0.704202,損失為0.000298
第196訓練后模型引數為:權重0.784881,偏置0.704130,損失為0.000259
第197訓練后模型引數為:權重0.785245,偏置0.704024,損失為0.000256
第198訓練后模型引數為:權重0.785542,偏置0.703911,損失為0.000219
第199訓練后模型引數為:權重0.785778,偏置0.703855,損失為0.000218
第200訓練后模型引數為:權重0.786084,偏置0.703762,損失為0.000211
5 學習率的設定、步數的設定與梯度爆炸
- 學習率越大,訓練
2.7.3 增加其他功能
- 變數TensorBoard顯示
- 增加命名空間
- 模型保存于加載
- 命令列引數設定
1 增加變數顯示
目的:在TensorBoard當中觀察模型的引數、損失值等變數值的變化

1)創建事件檔案
2)收集變數
3)合并變數
4)每次迭代運行合并變數
5)每次迭代將summary事件寫入事件檔案
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def linear_regression():
"""
實作線性回歸
:return:
"""
# 1)準備資料
X = tf.random_normal(shape=[100, 1]) # 形狀:100行1列
y_true = tf.matmul(X, [[0.8]]) + 0.7 # y_true = 0.8x + 0.7
# 2)構造模型
# 定義模型引數,用變數
weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]))
y_predict = tf.matmul(X, weights) + bias
# 3)構造損失函式
error = tf.reduce_mean(tf.square(y_predict - y_true))
# 4)優化損失
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)
# 2)收集變數
tf.summary.scalar("error", error)
tf.summary.histogram("weights", weights)
tf.summary.histogram("bias", bias)
# 3)合并變數
merged = tf.summary.merge_all()
# 顯式地初始化變數
init = tf.global_variables_initializer()
# 開啟會話
with tf.Session() as sess:
# 初始化變數
sess.run(init)
# 1)創建事件檔案
file_writer = tf.summary.FileWriter('logs', graph=sess.graph)
# 查看初始化模型引數之后的值
print("訓練前模型引數為:權重%f,偏置%f,損失為%f" %
(weights.eval(), bias.eval(), error.eval()))
# 開始訓練
for i in range(100):
sess.run(optimizer)
print("第%d訓練后模型引數為:權重%f,偏置%f,損失為%f" %
(i+1, weights.eval(), bias.eval(), error.eval()))
# 運行合并變數操作
summary = sess.run(merged)
# 每次迭代后的變數寫入事件
file_writer.add_summary(summary, i)
return None
if __name__ == "__main__":
linear_regression()

2 增加命名空間
使得代碼結構更加資訊,TensorBoard圖結構更加清楚
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def linear_regression():
"""
實作線性回歸
:return:
"""
with tf.variable_scope("prepare_data"):
# 1)準備資料
X = tf.random_normal(shape=[100, 1], name='feature') # 形狀:100行1列
y_true = tf.matmul(X, [[0.8]]) + 0.7 # y_true = 0.8x + 0.7
with tf.variable_scope("create_model"):
# 2)構造模型
# 定義模型引數,用變數
weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]), name="Weights")
bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]), name="Bias")
y_predict = tf.matmul(X, weights) + bias
with tf.variable_scope("loss_function"):
# 3)構造損失函式
error = tf.reduce_mean(tf.square(y_predict - y_true))
with tf.variable_scope("optimizer"):
# 4)優化損失
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(error)
# 2)收集變數
tf.summary.scalar("error", error)
tf.summary.histogram("weights", weights)
tf.summary.histogram("bias", bias)
# 3)合并變數
merged = tf.summary.merge_all()
# 顯式地初始化變數
init = tf.global_variables_initializer()
# 開啟會話
with tf.Session() as sess:
# 初始化變數
sess.run(init)
# 1)創建事件檔案
file_writer = tf.summary.FileWriter('logs', graph=sess.graph)
# 查看初始化模型引數之后的值
print("訓練前模型引數為:權重%f,偏置%f,損失為%f" %
(weights.eval(), bias.eval(), error.eval()))
# 開始訓練
for i in range(100):
sess.run(optimizer)
print("第%d訓練后模型引數為:權重%f,偏置%f,損失為%f" %
(i+1, weights.eval(), bias.eval(), error.eval()))
# 運行合并變數操作
summary = sess.run(merged)
# 每次迭代后的變數寫入事件
file_writer.add_summary(summary, i)
return None
if __name__ == "__main__":
linear_regression()

3 模型的保存與加載

步驟:
1)實體化Saver
2)保存:saver.save(sess, path)
3)加載:saver.restore(sess, path)
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def linear_regression():
"""
實作線性回歸
:return:
"""
with tf.variable_scope("prepare_data"):
# 1)準備資料
X = tf.random_normal(shape=[100, 1], name='feature') # 形狀:100行1列
y_true = tf.matmul(X, [[0.8]]) + 0.7 # y_true = 0.8x + 0.7
with tf.variable_scope("create_model"):
# 2)構造模型
# 定義模型引數,用變數
weights = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]), name="Weights")
bias = tf.Variable(initial_value=tf.random_normal(shape=[1, 1]), name="Bias")
y_predict = tf.matmul(X, weights) + bias
with tf.variable_scope("loss_function"):
# 3)構造損失函式
error = tf.reduce_mean(tf.square(y_predict - y_true))
with tf.variable_scope("optimizer"):
# 4)優化損失
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(error)
# 2)收集變數
tf.summary.scalar("error", error)
tf.summary.histogram("weights", weights)
tf.summary.histogram("bias", bias)
# 3)合并變數
merged = tf.summary.merge_all()
# 創建Saver物件
saver = tf.train.Saver()
# 顯式地初始化變數
init = tf.global_variables_initializer()
# 開啟會話
with tf.Session() as sess:
# 初始化變數
sess.run(init)
# 1)創建事件檔案
file_writer = tf.summary.FileWriter('logs', graph=sess.graph)
# 查看初始化模型引數之后的值
print("訓練前模型引數為:權重%f,偏置%f,損失為%f" %
(weights.eval(), bias.eval(), error.eval()))
# # 開始訓練
# for i in range(100):
# sess.run(optimizer)
# print("第%d訓練后模型引數為:權重%f,偏置%f,損失為%f" %
# (i+1, weights.eval(), bias.eval(), error.eval()))
#
# # 運行合并變數操作
# summary = sess.run(merged)
# # 每次迭代后的變數寫入事件
# file_writer.add_summary(summary, i)
#
# # 保存模型
# if i % 10 == 0:
# saver.save(sess, "model/my_Linear.ckpt")
# 加載模型
if os.path.exists("model/checkpoint"):
saver.restore(sess, "model/my_Linear.ckpt")
print("訓練后模型引數為:權重%f,偏置%f,損失為%f" %
(weights.eval(), bias.eval(), error.eval()))
return None
if __name__ == "__main__":
linear_regression()
訓練前模型引數為:權重-0.726173,偏置-1.391275,損失為6.139051
訓練后模型引數為:權重0.800000,偏置0.700000,損失為0.000000
4 命令列引數設定

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
# 1)定義命令列引數
tf.app.flags.DEFINE_integer("max_step", 100, "訓練模型的步數")
tf.app.flags.DEFINE_string("model_dir", "Unknown", "模型保存的路徑+模型的名字")
# 2)簡化變數名
FLAGS = tf.app.flags.FLAGS
def command_demo():
"""
命令列引數演示
:return:
"""
print("max_step:", FLAGS.max_step)
print("model_dir:", FLAGS.model_dir)
return None
if __name__ == "__main__":
command_demo()




import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def main(argv):
print(argv)
print("code start")
return None
if __name__ == "__main__":
tf.app.run() # 自動運行main函式
#command_demo()
['D:/programming_software/pycharm/PycharmProjects/deep_learning/day01_deeplearning.py']
code start
總結

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/280705.html
標籤:python
