①tf.Session()
運行TensorFlow操作圖的類,使用默認注冊的圖(可以指定運行圖)
1 import os 2 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #去掉警告,將警告級別提升
3
4 # 創建一張圖
5 g = tf.Graph() 6
7 with g.as_default(): #作為默認圖
8 c = tf.constant(11) 9 print(c.graph) 10
11 a = tf.constant(2) #定義一個常量
12 b = tf.constant(4) 13 sum = tf.add(a,b) #加法操作
14 gr = tf.get_default_graph() 15
16 #一個會話只能使用一張圖,默認是注冊圖,即圖gr
17 # with tf.Session() as sess: #上下文管理
18 # print(sess.run(sum)) #run運行加法op
19 # print(sess.run(c)) # (Tensor Tensor("Const:0", shape=(), dtype=int32) is not an element of this graph.)
20
21 #在會話中指定圖運行
22 with tf.Session(graph=g) as sess: #上下文管理
23 print(sess.run(c))
輸出:
<tensorflow.python.framework.ops.Graph object at 0x000002486656CD30>
11
②會話資源
會話擁有很多資源,如tf.Variable,tf.QueueBase和tf.ReaderBase等,會話結束后需要進行資源釋放
- 使用方法
1、sess = tf.Session(),sess.run(),sess.close()
2、使用上下文管理器
with tf.Session() as sess:
sess.run()
tensorflow可以分為前端系統(定義程序的圖的結構)和后端系統(運算圖的結構,用cpu,gpu進行運算)
會話的功能:
- 運算圖的結構
- 分配資源計算
- 掌握資源(變量的資源,隊列,線程),所以一旦會話結束,所有的資源將不能再使用
③打印設備信息
config=tf.ConfigProto(log_device_placement=True)
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess: #上下文管理
# print(sess.run(sum)) #run運行加法op
print("a.graph:",a.graph)
輸出:
Device mapping: /job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: GeForce GTX 1650, pci bus id: 0000:01:00.0, compute capability: 7.5
④交互式操作 tf.InteractiveSession()
在命令行進行測試時使用
只要有會話的上下文環境,就可以使用操作方便的eval()
1 a = tf.constant(2) #定義一個常量
2 b = tf.constant(4) 3 sum1 = tf.add(a,b) #加法操作
4
5 with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess: #上下文管理
6 print(sess.run(sum1)) #run運行加法op
7 print(sum1.eval())
輸出:
Device mapping: /job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: GeForce GTX 1650, pci bus id: 0000:01:00.0, compute capability: 7.5 Add: (Add): /job:localhost/replica:0/task:0/device:GPU:0 Const: (Const): /job:localhost/replica:0/task:0/device:GPU:0 Const_1: (Const): /job:localhost/replica:0/task:0/device:GPU:0 6
6
⑤會話中的run方法
run(fetches, feed_ dict=None,graph=None) 運行ops和計算tensor
- 嵌套列表,元組。 namedtuple,dict或OrderedDict( 重載的運算符也能運行)
- feed_dict允許調用者覆蓋圖中指定張量的值,提供給placeholder使用
- 返回值異常
RuntimeError:如果它Session處於無效狀態(例如已關閉)。
TypeError:如果fetches或feed_ dict鍵是不 合適的類型。
ValueError:如果fetches或feed_ dict鍵 無效或引用Tensor不存在。
(1)運行多個op
import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #去掉警告,將警告級別提升
a = tf.constant(2) #定義一個常量
b = tf.constant(4) sum1 = tf.add(a,b) #加法操作
with tf.Session() as sess: #上下文管理
print(sess.run(sum1)) #run運行加法op
# print(sess.run(a,b,sum1)) #錯誤,這樣相當於將a,b和sum1當作三個參數
print(sess.run([a,b,sum1])) #要將a,b和sum1當作一個整體,放進列表中或者元組中
輸出:
6
[2, 4, 6]
(2)重載運算符
- 兩個非tensor的量相加(不是op)不能使用run方法
1 var1 = 3.0 2 var2 = 5.0 3 sum2 = var1 + var2 4 5 with tf.Session() as sess: #上下文管理 6 print(sess.run(sum2))
輸出:
TypeError: Fetch argument 8.0 has invalid type <class 'float'>, must be a string or Tensor. (Can not convert a float into a Tensor or Operation.)
- 一個tensor和一個非tensor運算,非tensor會被重載為tensor
1 import tensorflow as tf 2 import os 3 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #去掉警告,將警告級別提升
4
5 a = tf.constant(2.0) #定義一個常量
6 b = tf.constant(4.0) 7 # sum1 = tf.add(a,b) #加法操作
8
9 var1 = 3.0
10 #默認會給運算符重載成op類型
11 sum3 = a + var1 #a和var1的數據類型要匹配
12
13 with tf.Session() as sess: #上下文管理
14 print(sess.run(sum3)) 15 print(a) #直接打印是一個tensor Tensor("Const:0", shape=(), dtype=float32)
16 print(var1) # 3.0
17 print(sum3) #Tensor("add:0", shape=(), dtype=float32)
輸出
5.0 Tensor("Const:0", shape=(), dtype=float32) 3.0 Tensor("add:0", shape=(), dtype=float32)
(3)feed_dict參數,允許調用者覆蓋圖中指定張量的值,提供給placeholder使用
訓練模型時,不知道每批次有多少個樣本 ,即有些量不固定,我們需要實時的提供數據去進行訓練
1 import tensorflow as tf 2 import os 3 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #去掉警告,將警告級別提升 4 5 #placeholder是一個占位符,通常與feed_dict配合使用 6 plt1 = tf.placeholder(tf.float32,[2,3]) 7 8 plt2 = tf.placeholder(tf.float32,[None,3]) #樣本數量不固定用None,Tensor("Placeholder_1:0", shape=(?, 3), dtype=float32) 9 print(plt2) 10 11 with tf.Session() as sess: #上下文管理 12 #相當於在運算的時候實時的提供數據進行訓練 13 print(“plt1:\n”,sess.run(plt1,feed_dict={ plt1:[[1,2,3],[4,5,6]]})) #feed_dict是一個字典,key是變量,value是2x3的值 14 print("plt2:\n",sess.run(plt2, feed_dict={plt2: [[1, 2, 3], [4, 5, 6],[7,8,9]]}))#因為行數不固定,所以可接收任意行數的值
輸出:
Tensor("Placeholder_1:0", shape=(?, 3), dtype=float32)
plt1: [[1. 2. 3.] [4. 5. 6.]] plt2: [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]]
會話最重要的是run,作用是運行的圖的結構,即運行一些op,再得到結果
(4)TensorFlow Feed操作
意義:在程序執行的時候,不確定輸入的是什么,提前“占個坑”
語法:placeholder提供占位符,在會話中run的時候通過feed_dict指定參數
- placeholder(dtype, shape=None, name=None)
shape要用列表表示,默認是一個常量
- run(self, fetches, feed_dict=None, options=None, run_metadata=None)
例1:
1 import tensorflow as tf 2 import os 3 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #去掉警告,將警告級別提升 4 5 input1 = tf.placeholder(tf.float32,[2,1]) #[2,1] 2行1列 6 input2 = tf.placeholder(tf.float32) #默認是一個數 7 output = tf.add(input1,input2) 8 # placeholder 提供占位符,run的時候通過feed_dict指定參數 9 10 with tf.Session() as sess: 11 result = sess.run(output,feed_dict={input1:[[10],[1]],input2:20}) 12 print(result)
輸出:
[[30.]
[21.]]
例2:
1 import tensorflow as tf 2 import os 3 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #去掉警告,將警告級別提升 4 5 input1 = tf.placeholder(tf.float32,[2,2]) 6 input2 = tf.placeholder(tf.float32,1) 7 8 sum = tf.add(input1,input2) 9 10 with tf.Session() as sess: 11 result = sess.run(sum, feed_dict={input1:[[1,2],[3,4]],input2:[3]}) 12 print(result)
輸出:
[[4. 5.]
[6. 7.]]