0

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

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

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

ValueError:initial_value 必须具有指定的形状: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:输入 0 与层中继器不兼容:预期 ndim=2,发现 ndim=None

更新1

当我尝试这个时:

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

它再次引发错误:

initial_value 必须具有指定的形状:Tensor("lambda_1/zeros_like:0", shape=(?, 20), dtype=float32)

另外,当我这样明确地给出它时:

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

它引发了这个错误:

ValueError:一个操作有None梯度。请确保您的所有操作都定义了渐变(即可微分)。没有梯度的常见操作: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.

谢谢你的帮助:)

4

1 回答 1

0

因此,在我的情况下,解决方法是删除tf.variablean only have 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 指出可训练变量的概念...... :)

于 2019-07-05T15:47:51.547 回答