【发布时间】:2020-04-21 17:14:59
【问题描述】:
Eager 张量不支持赋值。我需要做任务。
a = tf.convert_to_tensor(np.random.choice(10, size = 12).reshape(3,4))
b = tf.convert_to_tensor(np.array([2,3]))
a[:,b] *= -1
Traceback (most recent call last):
File "<ipython-input-15-516f7e5d5213>", line 3, in <module>
a[:,b] *= -1
File "/opt/anaconda3/envs/covid_timeseries/lib/python3.7/site-packages/tensorflow_core/python/ops/array_ops.py", line 777, in _slice_helper
_check_index(s)
File "/opt/anaconda3/envs/covid_timeseries/lib/python3.7/site-packages/tensorflow_core/python/ops/array_ops.py", line 666, in _check_index
raise TypeError(_SLICE_TYPE_ERROR + ", got {!r}".format(idx))
TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got <tf.Tensor: id=3, shape=(2,), dtype=int64, numpy=array([2, 3])>
有一个关于如何解决问题的建议here:
new = original * mask + other * (1 - mask)
我无法完成这项工作,因为我想不出一种方法来创建本身不涉及分配的蒙版!
我非常感谢一些可以帮助我实施这种高级方法的指导,可能是这样的:
def tf_assign_workaround(tensor, index, newvals):
??
return tensor_with_index_assigned_to_newvals
编辑:这是原始的、更简单的示例
a = tf.convert_to_tensor(np.random.choice(10, size = 12).reshape(3,4))
a[:,1] *= -1
Traceback (most recent call last):
File "<ipython-input-35-f8973c287624>", line 2, in <module>
a[:,1] *= -1
TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment
【问题讨论】:
-
那你想做什么?否定第二列中的值?
-
上面的例子只是为了机械地演示我在做什么。在我真正的问题中,我有一个张量流模型,我用它来预测一组微分方程的参数,然后我在梯度磁带中运行 diff eqs。 diff eqs 的输出需要通过网络的不同输出进一步修改。简而言之,这真的很复杂。 @thrushv89
-
无论如何,你的问题是一个更根本的问题。您正在尝试更改
tf.Tensor对象的值。您可以通过转换现有的tf.Tensor对象来创建新的tf.Tensor对象,但您不能就地编辑tf.Tensor。 -
因此问题。我需要一个解决方法!连蒙版都分配不了怎么办?!?
-
您的问题的答案在很大程度上取决于您想要的面具。你能提供一个玩具例子吗?我可以提供一个否定第二列的例子。但听起来你的问题过于简单化了。
标签: python tensorflow variable-assignment