简体   繁体   English

将一个张量的值添加到另一个而不影响图形

[英]Add values of one tensor to another without affecting the graph

I simply want to add the first three values of the third dimension of tensor2 to tensor1, without affecting the graph when doing backpropagation.我只是想将tensor2的第三维的前三个值添加到tensor1,而不影响反向传播时的图形。 Tensor2 is only required for its values, it shall not be part of the graph. Tensor2 只需要它的值,它不应该是图表的一部分。

Does this work?这行得通吗? That's how I would have done it in numpy.这就是我在 numpy 中的做法。

tensor1[:, :, :3] += tensor2[:, :, :3]

Should I better use torch.add() or use.data?我应该更好地使用 torch.add() 还是 use.data? I am confused about when to use what.我对何时使用什么感到困惑。 Thank you.谢谢。

You should be able to use detatch() to return a copy of the tensor ( tensor2 ) with requires_grad = False .您应该能够使用detatch()返回带有requires_grad = False的张量 ( tensor2 ) 的副本。 Using the inplace += operator causes errors during backpropagation (ie at various times during the forward pass, the same variable stored 2 different values with 2 different associated gradients, but only one set of value/ gradient is stored in that variable during the backwards pass.) I'm a bit fuzzy on whether in-place operations are allowed for variables that are part of the computation graph but when the operation itself is not.使用 inplace += 运算符会在反向传播过程中导致错误(即在前向传播过程中的不同时间,同一个变量存储了 2 个不同的值和 2 个不同的相关梯度,但在向后传播过程中只有一组值/梯度存储在该变量中.) 对于作为计算图一部分的变量是否允许就地操作但当操作本身不允许时,我有点模糊。 You can test this to see, but to be safe I recommend:您可以对此进行测试以查看,但为了安全起见,我建议:

tensor1[:,:,:3] =  torch.add(tensor1[:,:,:3],tensor2[:,:,:3].detach())

Later, if you want to do another operation using tensor2 where the gradient IS part of the computation graph, you still can do this as well.稍后,如果您想使用 tensor2 执行另一个操作,其中梯度是计算图的一部分,您仍然可以这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何选择一个张量中定义的特定值以及另一个张量中的数据 - how to select particular values defined in one tensor with data in another tensor 创建布尔张量,其中一个张量中的值在另一个张量中 - Create boolean tensor where values in one tensor are in another 如何在Theano中将具有给定值的可广播张量添加到另一个张量? - How to add broadcastable tensor with given values to another tensor in Theano? 如何将一个张量的值插入另一个张量? - How to insert values of one tensor into another? Map张量值到另一个张量 - Map tensor values to another tensor 我在一个张量中有索引,在另一个张量中有值。 我如何用这个创建一个新的张量? - I have indices in one tensor and values in another. How do I create a new tensor with this? 仅将张量添加到另一个张量的一部分 - Add a tensor only to a part of another tensor 为什么一个数组中的值更改会影响操作中未涉及的另一个数组(具有完全相同的值)上的值? - Why is the change of values in one array is affecting the value on another array (with exact same values) that isn't involved in the operation? 在Pandas DataFrame中更改某些条件的值并将其保存到新的df中,而不会影响原始的df - Change values on some criteria in Pandas DataFrame and save it to the new df without affecting the original one 更改数据框中的所有值而不影响索引 - Change all the values in dataframe without affecting the index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM