【问题标题】:Setting the shape of a tensor as the shape of another tensor将一个张量的形状设置为另一个张量的形状
【发布时间】:2017-08-17 20:41:30
【问题描述】:

我正在尝试运行这段代码:

def somefunc(x, rows, n_hidden):
    vectors = tf.contrib.layers.embed_sequence(nodes, vocab_size=vocab_size, embed_dim=n_hidden)
    batch_size = tf.shape(vectors)[0]
    state = tf.zeros([batch_size, rows, n_hidden])
    bias = tf.Variable(tf.constant(0.1, shape=[batch_size,1]) # Error here!
    ...


x = tf.placeholder(tf.int32, shape=[None, 200])
pred = somefunc(x, 200, 40) 
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=target))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)

调用函数时出现此错误(错误是偏置形状):

TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“张量”

我尝试做b = tf.Variable(0.1, validate_shape=False),但后来我在optimizer 收到此错误:

ValueError: as_list() 未在未知的 TensorShape 上定义。

如果我删除 validate_shape=False,我会收到形状错误。

如果我忽略了一些明显的事情,我很抱歉,但有人能告诉我哪里出错了吗?

非常感谢!

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    tf.constant() 操作的 shape 参数需要 静态 形状,因此您不能使用 tf.Tensor 作为参数的一部分。

    幸运的是,还有另一个操作就足够了:tf.fill(),它允许形状(其dims 参数)为tf.Tensor。这意味着您可以将bias 定义为:

    bias = tf.Variable(tf.fill(dims=[batch_size, 1], 0.1), validate_shape=False)
    

    【讨论】:

    • 非常感谢您回答我的问题!但是,当我尝试您的建议时出现此错误:ValueError: initial_value must have a shape specified: Tensor("Fill:0", shape=(?, 1), dtype=float32)。我需要占位符的第一个维度为无,因为我有不同的批量大小。
    • 对不起!我更新了答案以添加 validate_shape=False... 这对您有用吗? (请注意,这将使模型的初始化更加棘手,因为在运行初始化程序时必须输入一批数据。)
    • 那个错误消失了!但是现在优化器有一个错误:ValueError: as_list() is not defined on an unknown TensorShape.,我猜是因为 pred 返回了一个shape=[None,200]。如果他们不知道批量大小将是多少,他们通常如何传递数据?
    • 这是 Adam 算法和其他保持额外状态的优化器的问题:它们依赖于从一步到下一步保持相同大小的状态,因此定义没有意义它们具有潜在的动态形状。可能值得尝试找到一种方法使原始bias 变量的形状变为静态,以避免此问题。 (例如,您可以将其填充到最大批量大小。)
    • 非常感谢您对我的帮助!我真的很感激!
    猜你喜欢
    • 2019-03-18
    • 2019-09-01
    • 2018-12-13
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多