Tensorflow中的placeholder和feed_dict的使用

这篇文章主要介绍了Tensorflow中的placeholder和feed_dict的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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]]

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

以上就是Tensorflow中的placeholder和feed_dict的使用的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python