TensorFlow官方文件學習(二)

2021-08-28 05:51:50 字數 2496 閱讀 3321

開啟anaconda prompt

activate tensor flow

python

>>>import tensorflow as tf

>>>hello=tf.constant('hello')

>>>s=tf.session()

>>>print(s.run(hello))

b'hello'

此處hello為utf-8編碼?列印出來字首b,表示資料型別為bytes而非string

hello處若為數字,則是正確的。

tensorflow 是乙個程式設計系統, 使用圖來表示計算任務. 圖中的節點被稱之為 op (operation 的縮寫). 乙個 op 獲得 0 個或多個 tensor, 執行計算, 產生 0 個或多個 tensor.每個 tensor 是乙個型別化的多維陣列. 例如, 你可以將一小**像集表示為乙個四維浮點數陣列, 這四個維度分別是 [batch, height, width, channels].

乙個 tensorflow 圖描述了計算的過程. 為了進行計算, 圖必須在 會話 裡被啟動. 會話 將圖的 op 分發到諸如 cpu 或 gpu 之類的 裝置 上, 同時提供執行 op 的方法. 這些方法執行後, 將產生的 tensor 返回.在 python 語言中, 返回的 tensor 是 numpy ndarray 物件

tensorflow 程式通常被組織成乙個構建階段和乙個執行階段. 在構建階段, op 的執行步驟 被描述成乙個圖. 在執行階段, 使用會話執行執行圖中的 op.

例如,通常在構建階段建立乙個圖來表示和訓練神經網路, 然後在執行階段反覆執行圖中的訓練 op.

import tensorflow as tf

mat1=tf.constant([[1,2,3]]) #mat1為乙個1x3矩陣

mat2=tf.constant([[4],

[5],

[6]]) #mat2為乙個3x1矩陣

product=tf.matmul(mat1,mat2)

tf.constant()注釋

tf.constant([1]),表示一維張量1,即數字1;

tf.constant([1,2,3]),表示元組或說列表,即常量列表[1,2,3]

tf.constant([[1,2,3]]),表示1x3矩陣[1 2 3]

注意體會雙層中括號的用法

此時計算圖建立完畢,現在這個圖包含三個節點(op),兩個constant(),乙個matmul(),為了真正實現計算,必須在session中啟動這個圖

s=tf.session()

print(s.run(product))

s.close()

session 物件在使用完後需要關閉以釋放資源. 除了顯式呼叫 close 外, 也可以使用 「with」 **塊 來自動完成關閉動作

with tf.session() as s:

print(s.run(product))

interactivesession & session:

tf.interactivesession():它能讓你在執行圖的時候,插入一些計算圖,這些計算圖是由某些操作(operations)構成的。這對於工作在互動式環境中的人們來說非常便利,比如使用ipython。

tf.session():需要在啟動session之前構建整個計算圖,然後啟動該計算圖。

意思就是在我們使用tf.interactivesession()來構建會話的時候,我們可以先構建乙個session然後再定義操作(operation),如果我們使用tf.session()來構建會話我們需要在會話構建之前定義好全部的操作(operation)然後再構建會話。

rank 階

shape 形狀

type 資料型別

# 建立乙個變數, 初始化為標量 

state = tf.variable(0, name="counter")

one = tf.constant(1)

new_value = tf.add(state, one)

update = tf.assign(state, new_value)

init_op = tf.global_variable_initializer

啟**, 執行 op

with tf.session() as sess:

sess.run(init_op)

print sess.run(state)

for _ in range(3):

sess.run(update)

print sess.run(state)

TensorFlow官方文件學習(一)

乙個對手寫數字進行識別的模型。思路 1 將訓練集中獲取的手寫數字影象進行某一統一方式 全部按行或全部按列 的展開,得到乙個長向量 這是為了利用softmax做一維的回歸,不過損失了二維資訊 用乙個二維張量來索引某乙個樣本中的某一畫素。2 softmax模型 用來給不同的物件分配概率 即使在更精細的模...

TensorFlow 官方文件中文版

打個不太恰當的比喻,如今 google 對待 tensorflow 系統,有點類似於該公司對待旗下移動作業系統 android。如果更多的資料科學家開始使用 google 的系統來從事機器學習方面的研究,那麼這將有利於 google 對日益發展的機器學習行業擁有更多的主導權。google tenso...

深度學習框架TensorFlow 官方文件中文版

使用 tensorflow,你必須明白 tensorflow tensorflow 是乙個程式設計系統,使用圖來表示計算任務.圖中的節點被稱之為 op operation 的縮寫 乙個 op 獲得 0 個或多個 tensor 執行計算,產生 0 個或多個 tensor 每個 tensor 是乙個型別...