【问题标题】:TensorFlow: tf.placeholder and tf.Variable - why is the dimension not required?TensorFlow:tf.placeholder 和 tf.Variable - 为什么不需要维度?
【发布时间】:2016-12-27 22:03:36
【问题描述】:

我正在通过以下示例学习 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)

【问题讨论】:

    标签: python-3.x tensorflow


    【解决方案1】:

    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 提前执行一些检查,这样做有助于减少错误。

    【讨论】:

    • 谢谢!可变大小写呢?
    • 刚看到你也在问这个问题……我更新了答案来解释。
    • 当我阅读github.com/aymericdamien/TensorFlow-Examples/blob/master/… 中的代码时,在我看来,变量 W 是一个数组,而不是一个标量。我理解错了吗?谢谢!
    • 我几乎可以肯定它是一个标量。请注意,每 50 个 epoch 打印一次的日志消息会给出 Wb 的标量值。
    • 我认为 train_X(它是一个 numpy 数组)是占位符 X 的输入。然后它有 pred = tf.add(tf.mul(X, W), b)。如果 X 是一个数组,W 应该是一个数组。除非 X 也是一个标量?只是从 train_X n 个样本时间输入 X?
    猜你喜欢
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 2020-05-03
    相关资源
    最近更新 更多