1. 程式人生 > >tensorflow中的常量、變數和佔位符

tensorflow中的常量、變數和佔位符

部分內容轉自https://blog.csdn.net/baidu_15113429/article/details/78077834?locationNum=8&fps=1

https://blog.csdn.net/fei13971414170/article/details/73309106

先給一個例項,

#先匯入TensorFlow
import tensorflow as tf

# Create TensorFlow object called hello_constant
hello_constant = tf.constant('Hello World!')

with tf.Session() as sess:
    # Run the tf.constant operation in the session
output = sess.run(hello_constant) print(output)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

也許有人奇怪,為什麼不直接輸出“Hello World!”呢,這個看起來很麻煩,是嗎?其實不是的
1.Tensor是什麼?
在 TensorFlow 中,資料不是以整數,浮點數或者字串形式存在的,而是被封裝在一個叫做 tensor 的物件中。Tensor是張量的意思,張量包含了0到任意維度的量,其中,0維的叫做常數,1維的叫做向量,二維叫做矩陣,多維度的就直接叫張量量。在 hello_constant = tf.constant(‘Hello World!’) 程式碼中,hello_constant是一個 0 維度的字串 tensor,tensors 還有很多不同大小:

# tensor1 是一個0維的 int32 tensor
tensor1 = tf.constant(1234) 
# tensor2 是一個1維的 int32 tensor
tensor2 = tf.constant([123,456,789]) 
 # tensor3 是一個二維的 int32 tensor
tensor3 = tf.constant([ [123,456,789], [222,333,444] ])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.Session是Tensorflow中的一個重要概念
Tensorflow中的所有計算都構建在一張計算圖中,這是一種對數學運算過程的視覺化方法。就像剛才的程式碼:

with tf.Session() as sess:
    output = sess.run(hello_constant)
  • 1
  • 2

這裡寫圖片描述
這個session就是負責讓這個圖運算起來,session的主要任務就是負責分配GPU或者CPU的。

3.tf.placeholder()
前面程式碼中出現了tf.constant(‘Hello World!’),這個tf.constant是用來定義常量的,其值是不變的,但是如果你需要用到一個變數怎麼辦呢?

這個時候就需要用到tf.placeholder() 和 feed_dict了。
先給程式碼

x = tf.placeholder(tf.string)

with tf.Session() as sess:
    output = sess.run(x, feed_dict={x: 'Hello World'})
  • 1
  • 2
  • 3
  • 4

tf.placeholder表示一個佔位符,至於是什麼型別,看自己定義了,這裡定義的是tf.string型別,然後呢,在session開始run以前,也就死這個圖開始計算以前,就使用feed_dict將對應的值傳入x,也就是這個佔位符。
同樣的feed_dict可以設定多個tensor

x = tf.placeholder(tf.string)
y = tf.placeholder(tf.int32)
z = tf.placeholder(tf.float32)

with tf.Session() as sess:
    output = sess.run(x, feed_dict={x: 'Test String', y: 123, z: 45.67})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

但是需要注意的是,使用feed_dict設定tensor的時候,需要你給出的值型別與佔位符定義的型別相同。

import tensorflow as tf

a = tf.constant(2, tf.int16)
b = tf.constant(4, tf.float32)

graph = tf.Graph()
with graph.as_default():
    a = tf.Variable(8, tf.float32)
    b = tf.Variable(tf.zeros([2, 2], tf.float32))

with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()
    print(session.run(a))
    print(session.run(b))

實驗結果:

8
[[ 0.  0.]
 [ 0.  0.]]

tensorflow在圖graph中定義了a,b兩個變數,在啟動graph時候,必須把變數載入到記憶體中(通過方法global_variables_initializer())
,這樣才能在session中run(a),run(b)
session只能啟動graph=graph中的變數,如果變數不在graph中就會報錯。

import tensorflow as tf


graph = tf.Graph()
with graph.as_default():
    a = tf.Variable(8, tf.float32)
    b = tf.Variable(tf.zeros([2, 2], tf.float32))
a = tf.constant(2, tf.int16)
b = tf.constant(4, tf.float32)
with tf.Session(graph=graph) as session:
    tf.global_variables_initializer().run()
    print(session.run(a))
    print(session.run(b))

報錯

ValueError: Fetch argument <tf.Tensor 'Const:0' shape=() dtype=int16> cannot be interpreted as a Tensor. (Tensor Tensor("Const:0", shape=(), dtype=int16) is not an element of this graph.)

變數必須初始化才會有具體的值global_variables_initializer()進行初始化,而常量就不用初始化。
佔位符
佔位符是定義一個可變的常量,佔位符賦值後不用初始化就可以獲取值。

import tensorflow as tf

x = tf.placeholder(tf.string)
y = tf.placeholder(tf.int32)
z = tf.placeholder(tf.float32)

with tf.Session() as sess:
    output = sess.run(x, feed_dict={x: 'Test String', y: 123, z: 45.67})
print(output)

實驗結果:

Test String