tf.placeholder()函数解析(最清晰的解释)

欢迎关注WX公众号:【程序员管小亮】

最近学习中碰到了以前学过的tf.placeholder()函数,特此记录。

tf.placeholder()函数作为一种占位符用于定义过程,可以理解为形参,在执行的时候再赋具体的值。

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

参数:

  • dtype:数据类型。常用的是tf.float32,tf.float64等数值类型
  • shape:数据形状。默认是None,就是一维值,也可以多维,比如:[None,3],表示列是3,行不一定
  • name:名称

返回:

Tensor类型

此函数可以理解为形参,用于定义过程,在执行的时候再赋具体的值。

不必指定初始值,可在运行时,通过 Session.run 的函数的 feed_dict 参数指定。

这也是其命名的原因所在,仅仅作为一种占位符。

例子1:

import tensorflow as tf
import numpy as np

# 定义placeholder
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)

# 定义乘法运算
output = tf.multiply(input1, input2)

# 通过session执行乘法运行
with tf.Session() as sess:
    # 执行时要传入placeholder的值
    print sess.run(output, feed_dict = {input1:[7.], input2: [2.]})
> [14.]

例子2:

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)
 
with tf.Session() as sess:
#  print(sess.run(y))  # ERROR: 此处x还没有赋值.

  rand_array = np.random.rand(1024, 1024)
  print(sess.run(y, feed_dict={x: rand_array}))  # Will succeed.
> [[240.76114 244.46692 263.50317 ... 262.20663 263.7563  249.67624]
   [242.09816 253.64767 268.32532 ... 264.11237 260.7736  250.82085]
   [242.47516 245.25845 262.3011  ... 256.1698  254.3529  250.21765]
   ...
   [256.5986  265.0628  276.57742 ... 272.2212  277.17657 266.4881 ]
   [246.27658 250.78848 262.4334  ... 258.74762 259.81946 249.15094]
   [243.97534 254.9902  264.48654 ... 262.31183 260.91547 256.02576]]

python课程推荐。
在这里插入图片描述

原文地址:https://www.cnblogs.com/hzcya1995/p/13302843.html