tensorflow中张量、常量、变量、占位符
引言
從實(shí)例出發(fā)
#先導(dǎo)入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 sessionoutput = sess.run(hello_constant)print(output)有人會奇怪為什么不直接輸出“hello world”,其實(shí)在tensorflow里面有它自己的 一套。
正文
1.tensor
在tensorflow中,數(shù)據(jù)是被封裝在tensor對象中的。tensor是張量的意思,即包含從0到任意維度的張量。常數(shù)是0維度的張量,向量是1維度的張量,矩陣是二維度的張量,以及還有多維度的張量。
# 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.tf.constant
constant函數(shù)提供在tensorflow中定義常量(不可更改的張量)的方法
如:
tensor_constant = tf.constant([1,2,3,4)3.tf.Variable
tensorflow中的變量是通過Variable類來實(shí)現(xiàn)的。tensorflow中需要定義為變量的包括訓(xùn)練過程中的輸入數(shù)據(jù),輸出數(shù)據(jù),以及控制從輸入到輸出的學(xué)習(xí)機(jī)制,即網(wǎng)絡(luò)參數(shù)。輸入輸出數(shù)據(jù)在tf中是用placeholder占位符來定義的,網(wǎng)絡(luò)參數(shù)是用tf.Variable來定義的。
4.tf.placeholder
用于聲明一個張量的數(shù)據(jù)格式,告訴系統(tǒng)這里會有一個這種格式的張量,但是還沒有傳入具體的值。
如:
X = tf.placeholder("float", shape=[None, 100])
上面聲明了一個張量X,數(shù)據(jù)類型是float,100列,行數(shù)不確定。
5.tf.Session
以上部分都是搭建一個計算圖的代碼,在tf中,先搭建好計算圖,然后再啟動session,運(yùn)行定義好的圖。
import tensorflow as tfx = tf.placeholder("string") with tf.Session() as sess:output = sess.run(x, feed_dict={x : "run the map"})print(output)通過上面的例子我們明白了如何使用占位符,首先定義x為占位符,然后運(yùn)行的時候?qū)⑾胍獋魅氲闹祩鹘ox。
結(jié)尾
參考
https://blog.csdn.net/dcrmg/article/details/79016107
https://blog.csdn.net/fei13971414170/article/details/73309106/
總結(jié)
以上是生活随笔為你收集整理的tensorflow中张量、常量、变量、占位符的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何用item pipeline(管道)
- 下一篇: tf.nn.conv2d()方法