代码之家  ›  专栏  ›  技术社区  ›  sachinruk

分配到Tensorflow2中的切片

  •  0
  • sachinruk  · 技术社区  · 4 年前

    假设我有下面的变量x,我想把1赋给所有的0。

    x = tf.random.poisson((3,5), 1)
    idx = x == 0
    y = tf.Variable(tf.zeros_like(x, dtype=tf.float32))
    y[idx] = 1.0
    

    当我试着 y[idx].assign(1.0) AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign' .

    我也尝试了下面的其他变化,但没有成功:

    y[idx].assign(tf.ones_like(y[idx]))
    y[idx] = tf.ones_like(y[idx], dtype=tf.float32)
    

    可选的

    0 回复  |  直到 4 年前
        1
  •  1
  •   adrtam    4 年前

    如果没有进一步的上下文,我不知道为什么要更新 Variable

    >>> x
    <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
    array([[2., 2., 2., 0., 0.],
           [1., 1., 1., 2., 0.],
           [1., 0., 2., 0., 1.]], dtype=float32)>
    >>> idx
    <tf.Tensor: shape=(3, 5), dtype=bool, numpy=
    array([[False, False, False,  True,  True],
           [False, False, False, False,  True],
           [False,  True, False,  True, False]])>
    >>> tf.where(idx, np.inf, tf.zeros_like(x, dtype=tf.float32))
    <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
    array([[ 0.,  0.,  0., inf, inf],
           [ 0.,  0.,  0.,  0., inf],
           [ 0., inf,  0., inf,  0.]], dtype=float32)>
    >>> y = tf.Variable(tf.where(idx, np.inf, tf.zeros_like(x, dtype=tf.float32)), dtype=tf.float32)
    >>> y
    <tf.Variable 'Variable:0' shape=(3, 5) dtype=float32, numpy=
    array([[ 0.,  0.,  0., inf, inf],
           [ 0.,  0.,  0.,  0., inf],
           [ 0., inf,  0., inf,  0.]], dtype=float32)>