Tensorflow的基礎用法

2022-06-02 15:54:16 字數 2738 閱讀 6959

tensorflow是乙個深度學習框架,它使用圖(graph)來表示計算任務,使用tensor(張量)表示資料,圖中的節點稱為op,在乙個會話(session)的上下文中執行運算,最終產生tensor。

之所以用計算圖來表示計算任務,tensorflow的官網的一張就能很好的說明。

tensor在數學中稱為張量,表示空間,在計算圖模型中就是基本的資料型別,如同我們在sklearn等機器學習框架中使用numpy的矩陣作為基本運算的資料型別一樣,無論幾維的矩陣都是乙個張量

神經網路的前向傳播本質上就是一張計算圖進行計算。相比其他術語,也許計算圖能更好的說明機器學習的本質。

graph 圖

session 會話

#tf.constant(value, dtype=none, shape=none,name="const")

tf.constant(10)

import tensorflow as tf

tf.varialbe(tf.zeros([1]))

故名思意這個量在圖的運算中可以發生改變

文件中的乙個例子

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

# 建立乙個 op, 其作用是使 state 增加 1

one = tf.constant(1)

new_value = tf.add(state, one)

update = tf.assign(state, new_value)

# 啟**後, 變數必須先經過`初始化` (init) op 初始化,

# 首先必須增加乙個`初始化` op 到圖中.

init_op = tf.initialize_all_variables()

# 啟**, 執行 op

with tf.session() as sess:

# 執行 'init' op

sess.run(init_op)

# 列印 'state' 的初始值

print sess.run(state)

# 執行 op, 更新 'state', 並列印 'state'

for _ in range(3):

sess.run(update)

print sess.run(state)

# 輸出:

# 0# 1

# 2# 3

這個是暫時未定義的乙個tensor

在計算圖執行時給予,類似函式的引數。

python

input1 = tf.placeholder(tf.float32)

tensorflow的程式一般分為兩個階段,構建階段和執行極端。一般,構建階段會建立乙個圖,來表示神經網路,在執行階段在反覆執行訓練圖。

可以把圖的構建看成定義乙個複雜的函式。

import tensorflow as tf

matrix1 = tf.constant([[3.,3]])

matrix2 = tf.constant([[2.],[2.]])

product = tf.matmul(matrix1,matrix2)

python

sess = tf.session()

result = sess.run(product)

# 執行圖定義的product運算

print(result)

sess.close

#執行完畢後關閉會話

還有另一種方法會使用python的特性

python

with tf.session() as sess:

result = sess.run([product])

print(result)

在sess的運算中不僅可以取回結果,還可以取回多個tensor,在神經網路中,我們可以取回中間層的結果

input1 = tf.constant(3.0)

input2 = tf.constant(2.0)

input3 = tf.constant(5.0)

intermed = tf.add(input2, input3)

mul = tf.mul(input1, intermed)

with tf.session() as sess:

result = sess.run([mul, intermed])

print result

# 輸出:

# [array([ 21.], dtype=float32), array([ 7.], dtype=float32)]

sess.run()接受的引數是個列表,輸出會輸出這個列表中的值

有時訓練過程中我們會執行增量訓練,這時就會使用前面介紹的placeholder()

input1 = tf.placeholder(tf.float32)

input2 = tf.plaeholder(tf.float32)

output = tf.mul(input1, input2)

with tf.session() as sess:

print(sess.run([ouput], feed_dict=)

Tensorflow的基礎用法

tensorflow是乙個深度學習框架,它使用圖 graph 來表示計算任務,使用tensor 張量 表示資料,圖中的節點稱為op,在乙個會話 session 的上下文中執行運算,最終產生tensor。之所以用計算圖來表示計算任務,tensorflow的官網的一張就能很好的說明。tensor在數學中...

Tensorflow入門基礎語句及用法

tensorflow顧名思義是張量流動的意思,這裡的tensor雖然翻譯成張量但其實跟向量沒區別。tensorflow通過構建一張 圖 這個圖有點類似 樹 的結構。這裡可以看到圖中有很多節點,我們輸入的資料從根節點 就是最上方的節點 進入。然後流過這些節點。因為資料一般是以張量的形式流過節點,所以叫...

TensorFlow基本用法

author youngkl coding utf 8 import tensorflow as tf 1 2的矩陣 mat1 tf.constant 3.3.2 1的矩陣 mat2 tf.constant 2.3.ans tf.matmul mat1,mat2 此時ans無法直接輸出 啟動預設圖 ...