Tensorflow中的placeholder和feed_dict的使用
2018-07-09 09:52
591 查看
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]]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- 简单的Tensorflow(3):使用feed_dict字典填充
- [tensorflow] feed_dict 传入序列
- Tensorflow报错之一:InvalidArgumentError: You must feed a value for placeholder tensor 'inputs/x_input'
- tf.placeholder 和 feed_dict
- tensorflow feed_dict()
- tensorflow-placeholder-占位符的使用
- 记一次失败的tensorflow之旅(将feed_dict改为queue异步)
- TF:TF定义两个变量相乘之placeholder先hold类似变量+feed_dict最后外界传入值—Jason niu
- tensorflow48 《面向机器智能的TensorFlow实战》笔记-03-03 tensorflow基本矢量图、summary、feed_dict
- Variable 与 placeholder 之间的区别 + feed_dict
- TensorFlow学习笔记3——Placeholders and feed_dict
- Tensorflow中placeholder传入值与feed_dict喂食器的联系与用法
- 【Tensorflow】报错:Cannot interpret feed_dict key as Tensor: The name 'x' refers to an operation, # > no
- (原)tensorflow中使用指定的GPU及GPU显存
- 使用MNIST数据集,在TensorFlow上实现基础LSTM网络
- TensorFlow-关键字global_step使用
- 使用dict和set
- Class PropertyPlaceholderHelper的使用
- TensorFlow 教程 --新手入门--1.5 基本使用
- Spring中property-placeholder的使用与解析