Tensorflow中的placeholder和feed_dict的使用

发布时间:2020-09-16 16:09:57 作者:海天一树X
来源:脚本之家 阅读:138

TensorFlow 支持占位符placeholder。占位符并没有初始值,它只会分配必要的内存。在会话中,占位符可以使用 feed_dict 馈送数据。

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

在训练神经网络时需要每次提供一个批量的训练样本,如果每次迭代选取的数据要通过常量表示,那么TensorFlow 的计算图会非常大。因为每增加一个常量,TensorFlow 都会在计算图中增加一个结点。所以说拥有几百万次迭代的神经网络会拥有极其庞大的计算图,而占位符却可以解决这一点,它只会拥有占位符这一个结点。

placeholder函数的定义为

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

参数:

    dtype:数据类型。常用的是tf.int32,tf.float32,tf.float64,tf.string等数据类型。
    shape:数据形状。默认是None,也就是一维值。
           也可以表示多维,比如要表示2行3列则应设为[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)

运行结果: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)

运行结果:

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

运行结果:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. html5中placeholder的使用
  2. css中修改placeholder的样式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

tensorflow placeholder feed dict

上一篇:iOS13 适配和Xcode11.0踩坑小结

下一篇:txt文件如何导入mysql数据库

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》