tensorflow中的常量 變數和佔位符

2021-08-20 06:52:38 字數 2720 閱讀 9385

部分內容**

先給乙個例項,

#先導入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)

# 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] ])

output = sess.run(hello_constant)

x = tf.placeholder(tf.string)

with tf.session() as sess:

output = sess.run(x, feed_dict=)

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=)

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 'const:0' shape=() dtype=int16> cannot be interpreted as

a tensor. (tensor tensor("const:0", shape=(), dtype=int16) is not

anelement

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=)

print(output)

實驗結果:

test string

tensorflow中張量 常量 變數 佔位符

從例項出發 先導入tensorflow import tensorflow as tf create tensorflow object called hello constant hello constant tf.constant hello world with tf.session as s...

tensorflow 使用 1 常量,變數

import tensorflow as tf 建立乙個常量 op 一行二列 m1 tf.constant 3,3 建立乙個常量 op 二行一列 m2 tf.constant 2 3 建立乙個矩陣乘法 op,把 m1,m3 傳入 prod tf.matmul m1,m2 print prod 呼叫 ...

20150527常量變數

main.c ios150527 created by peng junlong on 15 5 27.include void changliangbian int main int argc,const char argv 常量 變數 常量 是c語言中最基本的元素,包括 字元常量,整型常量,浮點...