将张量的形状设置为另一张量的形状

时间:2017-03-24 19:12:25

标签: tensorflow

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

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()参数必须是字符串,类似字节的对象或数字,而不是'Tensor'

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

  

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

如果我删除validate_shape=False,则会出现形状错误。

如果我忽略了一些显而易见的事情,我很抱歉,但有人可以告诉我哪里出错了吗?

非常感谢!

1 个答案:

答案 0 :(得分:2)

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

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

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