日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Tensorflow入门----占位符、常量和Session

發布時間:2023/12/19 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Tensorflow入门----占位符、常量和Session 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

安裝好TensorFlow之后,開一個python環境,就可以開始運行和使用TensorFlow了。

先給一個實例,

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

也許有人奇怪,為什么不直接輸出“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] ])

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

with tf.Session() as sess:
output = sess.run(hello_constant)
這個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'})

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

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

轉載于:https://www.cnblogs.com/auvxx/p/9818796.html

總結

以上是生活随笔為你收集整理的Tensorflow入门----占位符、常量和Session的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。