溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Tensorflow中的placeholder和feed_dict的使用

發(fā)布時間:2020-09-16 16:09:57 來源:腳本之家 閱讀:143 作者:海天一樹X 欄目:開發(fā)技術(shù)

TensorFlow 支持占位符placeholder。占位符并沒有初始值,它只會分配必要的內(nèi)存。在會話中,占位符可以使用 feed_dict 饋送數(shù)據(jù)。

feed_dict是一個字典,在字典中需要給出每一個用到的占位符的取值。

在訓(xùn)練神經(jīng)網(wǎng)絡(luò)時需要每次提供一個批量的訓(xùn)練樣本,如果每次迭代選取的數(shù)據(jù)要通過常量表示,那么TensorFlow 的計算圖會非常大。因為每增加一個常量,TensorFlow 都會在計算圖中增加一個結(jié)點。所以說擁有幾百萬次迭代的神經(jīng)網(wǎng)絡(luò)會擁有極其龐大的計算圖,而占位符卻可以解決這一點,它只會擁有占位符這一個結(jié)點。

placeholder函數(shù)的定義為

tf.placeholder(dtype, shape=None, name=None)

參數(shù):

    dtype:數(shù)據(jù)類型。常用的是tf.int32,tf.float32,tf.float64,tf.string等數(shù)據(jù)類型。
    shape:數(shù)據(jù)形狀。默認(rèn)是None,也就是一維值。
           也可以表示多維,比如要表示2行3列則應(yīng)設(shè)為[2, 3]。
           形如[None, 3]表示列是3,行不定。
    name:名稱。

返回:Tensor類型

例1

import tensorflow as tf

x = tf.placeholder(tf.string)

with tf.Session() as sess:
  output = sess.run(x, feed_dict={x: 'Hello World'})
  print(output)

運(yùn)行結(jié)果:Hello World

例2

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 :'Hello World', y:123, z:45.67})
  print(output)
  output = sess.run(y, feed_dict = {x :'Hello World', y:123, z:45.67})
  print(output)
  output = sess.run(z, feed_dict = {x :'Hello World', y:123, z:45.67})
print(output)

運(yùn)行結(jié)果:

Hello Word
123
45.66999816894531

例3:

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=(3, 3)) 
y = tf.matmul(x, x) 
 
with tf.Session() as sess:  
  rand_array = np.random.rand(3, 3)
print(sess.run(y, feed_dict = {x: rand_array}))

運(yùn)行結(jié)果:

[[0.62475741  0.40487182  0.5968855 ]
 [0.17491265  0.08546661  0.23616122]
 [0.53931886  0.24997233  0.56168258]]

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI