python-3.x - TensorFlow:tf.placeholder 和 tf.Variable - 为什么不需要维度?

标签 python-3.x tensorflow

我正在通过以下示例学习 TensorFlow:https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/2_BasicModels/linear_regression.ipynb

我对下面的代码有几个疑问: 当定义占位符和变量(如 X、Y、W 和 b)时,为什么我们不需要指定它们的维度?如果不知道这些占位符/变量的大小,代码将如何分配内存?谢谢!

    # tf Graph Input
    X = tf.placeholder("float")
    Y = tf.placeholder("float")

    # Set model weights
    W = tf.Variable(rng.randn(), name="weight")
    b = tf.Variable(rng.randn(), name="bias")


    # Construct a linear model
    pred = tf.add(tf.mul(X, W), b)

最佳答案

TensorFlow 的 tf.placeholder() 张量不需要您指定形状,以便您可以在稍后的 tf.Session.run() 提供不同形状的张量称呼。默认情况下,占位符具有完全不受约束的形状,但您可以通过传递可选的 shape 来约束它。争论。例如:

w = tf.placeholder(tf.float32)                      # Unconstrained shape
x = tf.placeholder(tf.float32, shape=[None, None])  # Matrix of unconstrained size
y = tf.placeholder(tf.float32, shape=[None, 32])    # Matrix with 32 columns
z = tf.placeholder(tf.float32, shape=[128, 32])     # 128x32-element matrix

当您创建占位符时,TensorFlow 不会分配任何内存。相反,当您在对 tf.Session.run() 的调用中提供占位符时, ,TensorFlow 将为输入(以及随后的任何必要的中间)张量分配适当大小的内存。

请注意 tf.Variable 对象在创建时通常需要一个形状,并且该形状是从初始化器的第一个参数推断出来的。在你的程序中,rng.randn() ( numpy.random.randn() 的别名)返回标量值,因此变量 Wb将具有标量形状。

尽管代码中的占位符( XY )具有不受约束的形状,但某些运算符,例如 tf.add() tf.mul() ,对其参数的形状有额外的要求(即它们与 NumPy broadcasting rules 兼容)。由于 TensorFlow 不知道您何时构建图,这些张量的实际形状是什么,因此它相信用户知道他们在做什么,并动态执行检查(在调用 tf.Session.run() 期间)。相反,如果您限制占位符的形状,则可以让 TensorFlow 提前执行一些检查,这样做有助于减少错误。

关于python-3.x - TensorFlow:tf.placeholder 和 tf.Variable - 为什么不需要维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352745/

相关文章:

Tensorflow for循环的每次迭代变得越来越慢

python - TensorFlow:以随机角度旋转图像和点时的偏移

python - 如何重命名路径名?

python - PyCharm 中的 pip 版本不一致

python - decimal.InvalidOperation,除法对于非常大的数字来说是不可能的

python - Mac OS Catalina 中修复了 OS Mojave 中的 tkinter 8.6 系统崩溃错误吗?

python - tensorflow 集线器 : module spec export with checkpoint path doesn't save all variables

tensorflow - 使用队列从多个输入文件中统一采样

tensorflow - 在联合训练中实现数据生成器

python - 为什么 `__new__` 返回的对象是可变的,即使对于不可变的基类也是如此?