如何在 keras 中使用 batch_size 时识别张量的形状(initial_value 必须指定形状)

how to identify shape of tensor while using batch_size in keras (initial_value must have a shape specified)

我有一个custom layer,在这个客户层的一行中我是这样的:

out = tf.Variable(tf.zeros(shape=tf.shape(tf_a1), dtype=tf.float32))

当我运行编码时,我收到这个错误:

ValueError: initial_value must have a shape specified: Tensor("lambda_1/zeros_2:0", shape=(?, 20), dtype=float32)

我搜索了一下发现可以使用validate_shape=False

所以我把代码改成:

out = tf.Variable(tf.zeros(shape=tf.shape(tf_a1), dtype=tf.float32), validate_shape=False)

然后它引发了这个错误:

ValueError: Input 0 is incompatible with layer repeater: expected ndim=2, found ndim=None

更新1

当我尝试这个时:

out = tf.Variable(tf.zeros_like(tf_a1, dtype=tf.float32))

它再次引发错误:

initial_value must have a shape specified: Tensor("lambda_1/zeros_like:0", shape=(?, 20), dtype=float32)

此外,当我这样明确给出时:

out = tf.Variable(tf.zeros(shape=(BATCH_SIZE, LATENT_SIZE), dtype=tf.float32))

它引发了这个错误:

ValueError: An operation has None for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.

以防模型可以帮助找出错误的来源:

这是lambda层,只需要稍微改变一下矩阵即可:

def score_cooccurance(tf_a1):
    N = tf.shape(tf_a1)[0]
    n = 2
    input_tf = tf.concat([tf_a1, tf.zeros((1, tf_a1.shape[1]), tf_a1.dtype)], axis=0)
    tf_a2 = tf.sort(sent_wids, axis=1)
    first_col_change = tf.zeros([tf_a2.shape[0], 1], dtype=tf.int32)
    last_cols_change = tf.cast(tf.equal(tf_a2[:, 1:], tf_a2[:, :-1]), tf.int32)
    change_bool = tf.concat([first_col_change, last_cols_change], axis=-1)
    not_change_bool = 1 - change_bool
    tf_a2_changed = tf_a2 * not_change_bool + change_bool * N #here

    idx = tf.where(tf.count_nonzero(tf.gather(input_tf, tf_a2_changed, axis=0), axis=1) >= n)
    y, x = idx[:, 0], idx[:, 1]
    rows_tf = tf.gather(tf_a2, y, axis=0)

    columns_tf = tf.cast(x[:, None], tf.int32)

    out = tf.Variable(tf.zeros(shape=(BATCH_SIZE, LATENT_SIZE), dtype=tf.float32))

    rows_tf = tf.reshape(rows_tf, shape=[-1, 1])

    columns_tf = tf.reshape(
        tf.tile(columns_tf, multiples=[1, tf.shape(tf_a2)[1]]),
        shape=[-1, 1])

    sparse_indices = tf.reshape(
        tf.concat([rows_tf, columns_tf], axis=-1),
        shape=[-1, 2])
    v = tf.gather_nd(input_tf, sparse_indices)
    v = tf.reshape(v, [-1, tf.shape(tf_a2)[1]])

    scatter = tf.scatter_nd_update(out, tf.cast(sparse_indices, tf.int32), tf.reshape(v, shape=[-1]))
    return scatter

实际上当我打印出 out 的形状时,它打印出 <unknown>.

有什么想法或技巧可以解决这个问题吗?

我正在使用 tensorflow 1.13.

感谢您的帮助:)

所以我的解决方法是删除 tf.variable,只有 tf.zeros。 在这种情况下,tf.scater_nd_update 会引发错误,因为它无法应用于 tensors.

好像还有tensor_scatter_nd_update以前不知道的。所以我也更改了该行,现在代码工作正常,但我没有得到错误的主要原因。我改成这样就成功了运行

out = tf.zeros(shape=tf.shape(tf_a1), dtype=tf.float32)
scatter = tf.tensor_scatter_update(out, tf.cast(sparse_indices, tf.int32), tf.reshape(v, shape=[-1]))

感谢@Daniel Moller 指出可训练变量的概念...:)