簡體   English   中英

在 Tensorflow2 中分配給切片

[英]Assign to slice in Tensorflow2

假設我有以下變量 x 並且我希望將 1 分配給所有零。

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)

選修的

在我的例子中,我真正需要分配的是 -infinity。 我假設如果我能做到以上,我可以分配它,但如果由於某種原因這更復雜,請告訴我。

沒有進一步的上下文,我不知道你為什么要更新Variable 但是當你創建一個有值的時候(tensorflow 2.0 eager execution下),你可以先預設矩陣:

>>> 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)>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM