天天看點

矩張量計算 matlab,TensorFlow計算圖,張量,會話基礎知識

importtensorflow as tf#tensor 張量 零階張量是标量scalar 一階張量是向量vector n階張量了解為n維數組#張量在TensorFlow中不是直接采用數組的形式,隻是運算結果的引用。并沒有儲存數組,儲存的是如何得到這些數字的計算過程

#tf.constan是一個計算,結果為一個張量,儲存在變量a中

a=tf.constant([1.0,2.0],name="a")

b=tf.constant([2.0,3.0],name="b")

result=a+bprint(result)#Tensor("add:0", shape=(2,), dtype=float32)

result=tf.add(a,b,name="add")print(result)#Tensor("add_1:0", shape=(2,), dtype=float32)#張量儲存三個屬性 名字name(唯一辨別) 次元shape 類型 dtype#張量的命名是node:src_output形式給出,node是節點名稱,src_output是表示張量來自節點第幾個輸出#add_1:0 說明是add節點的第一個輸出(編号從0開始)#shape=(2,) 以為數組,長度為2

#dtype=float32 每個張量類型唯一,不比對将報錯

'''a=tf.constant([1,2],name="a")

b=tf.constant([2.0,3.0],name="b")

result=a+b

print(result)

#ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("b_1:0", shape=(2,), dtype=float32)''''

#result.get_shape 擷取張量的次元

print(result.get_shape)#result#>

#當計算圖構造完成後,張量可以獲得計算結果 (張量本身沒有存儲具體的數字)

#使用session來執行定義好的運算 (也就是張量存儲了運算的過程,使用session執行運算擷取結果)#建立會話

sess=tf.Session()

res=sess.run(result)print(res)#result is [ 3. 5.]#關閉會話是本地運作使用到的資源釋放

sess.close()#也可以使用python上下文管理器機制,吧所有的計算放在with中,上下文管理器推出是自動釋放所有資源,可以避免忘記sess.close()去釋放資源

with tf.Session() as sess:print(sess.run(result))#[ 3. 5.]

#as_default 通過預設的會話計算張量的取值 會話不會自動生成預設的會話,需要手動指定 指定後可以通過eval來計算張量的取值

sess =tf.Session()

with sess.as_default():print(result.eval())#[ 3. 5.]

#ConfigProto來配置需要生成的會話#allow_soft_placement GPU裝置相關#log_device_palcement 日志相關

config=tf.ConfigProto(allow_soft_placement=True,

log_device_placement=True)

sess1=tf.InteractiveSession(config=config)

sess2=tf.Session(config=config)#Device mapping: no known devices. tensorflow\core\common_runtime\direct_session.cc#Device mapping: no known devices.

#PY\35\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2