一、环境
TensorFlow API r1.12
CUDA 9.2 V9.2.148
cudnn64_7.dll
Python 3.6.3
Windows 10
二、官方说明
网络输入张量的占位符
https://www.tensorflow.org/api_docs/python/tf/placeholder
tf.placeholder(
dtype,
shape=None,
name=None
)
输入:
(1)dtype:输入张量中数据的类型
(2)shape:可选参数,输入张量的维度形状,该项不设置则表示输入的张量可以是任何维度
(3)name:可选参数,操作的名称
返回结果:
(1)张量,用来给网络输入数据的一个工具,但没有具体的数值
说明:
tf.placehoder()定义一个输入占位符,没有具体的值,只有在会话执行时通过sess.run(feed_dict = {input_x:x输入数据, input_y:y具体输入数据})进行幅值使用
三、实例
(1)不设置维度
>>> import tensorflow as tf
>>> import numpy as np
>>> x = tf.placeholder(dtype=tf.float32)
>>> y = tf.matmul(x, x)
>>> data = np.random.rand(2,2)
>>> with tf.Session() as sess:
... sess.run(y, feed_dict={x:data})
...
array([[1.1486264 , 0.67143285],
[1.1721172 , 0.7071244 ]], dtype=float32)
(2)设置固定维度
>>> import tensorflow as tf
>>> import numpy as np
>>> x = tf.placeholder(dtype=tf.float32, shape=(28, 28))
>>> y = tf.matmul(x, x)
>>> data = np.random.rand(28,28)
>>> with tf.Session() as sess:
... sess.run(y, feed_dict={x:data})
(3)某一个维度设置None,一般表示数量可变的batch_size
>>> import tensorflow as tf
>>> x = tf.placeholder(dtype=tf.float32, shape=[None,2])
>>> sum = tf.add(x,x)
>>> data1 = np.random.rand(1,2)
>>> data2 = np.random.rand(2,2)
>>> data3 = np.random.rand(3,2)
>>> with tf.Session() as sess:
... sess.run(sum, feed_dict={x:data1})
... sess.run(sum, feed_dict={x:data2})
... sess.run(sum, feed_dict={x:data3})
...
array([[0.41804734, 0.58225584]], dtype=float32)
...
array([[0.88173157, 0.48073 ],
[0.78674865, 0.9617455 ]], dtype=float32)
...
array([[0.54382133, 0.23284811],
[0.8744685 , 1.3424295 ],
[0.7200361 , 1.609155 ]], dtype=float32)