python - PyTorch:如何解决运行时错误:就地操作只能用于不与任何其他变量共享存储的变量

标签 python machine-learning torch pytorch

使用 PyTorch 我在使用两个变量进行操作时遇到问题:

sub_patch  : [torch.FloatTensor of size 9x9x32]

pred_patch : [torch.FloatTensor of size 5x5x32]

sub_patch 是由 torch.zeros 创建的一个变量 pred_pa​​tch 是一个变量,我用一个嵌套的 for 循环为 25 个节点中的每一个节点编制索引,然后我将其与其相应的大小为 [5,5,32] 的唯一过滤器 (sub_filt_patch) 相乘。结果被添加到其在 sub_patch 中的相应位置。

这是我的一段代码:

for i in range(filter_sz):
    for j in range(filter_sz):

        # index correct filter from filter tensor
        sub_filt_col = (patch_col + j) * filter_sz
        sub_filt_row = (patch_row + i) * filter_sz

        sub_filt_patch = sub_filt[sub_filt_row:(sub_filt_row + filter_sz), sub_filt_col:(sub_filt_col+filter_sz), :]

        # multiply filter and pred_patch and sum onto sub patch
        sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] += (sub_filt_patch * pred_patch[i,j]).sum(dim=3)

我从这段代码的底线得到的错误是

RuntimeError: in-place operations can be only used on variables that don't share storage with any other variables, but detected that there are 2 objects sharing it

我明白为什么会发生这种情况,因为 sub_patch 是一个变量,而 pred_pa​​tch 也是一个变量,但是我该如何解决这个错误?任何帮助将不胜感激!

谢谢!

最佳答案

我发现问题出在

        sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] += (sub_filt_patch * pred_patch[i,j]).sum(dim=3)

当把这条线分成这样的时候:

sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] = sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] + (sub_filt_patch * pred_patch[i,j]).sum(dim=3)

然后成功了!

a += b 和 a = a + b 的区别在于,第一种情况下,b 被添加到 a 中(因此 a 的内容被更改为现在包含 a+b)。在第二种情况下,创建了一个包含 a+b 的全新张量,然后将这个新张量分配给名称 a。 为了能够计算梯度,您有时需要保留 a 的原始值,因此我们会阻止执行就地操作,否则我们将无法计算梯度。

关于python - PyTorch:如何解决运行时错误:就地操作只能用于不与任何其他变量共享存储的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45693586/

相关文章:

python - 为什么 Python 的装饰器语法比普通包装器语法提供更快的内存代码?

python - 一个文件中的所有代码

machine-learning - 先验分布在分类中重要吗?

python - BertTokenizer - 当编码和解码序列时出现额外的空格

deep-learning - PyTorch 中带有 Sequential 模块的简单 LSTM

python - 如何破译这个 cPickle 错误?

python - astropy.io.votable - 是否有一种简单的方法来获取 VOTable 参数?

c++ - 使用 vowpal wabbit 的典型技术堆栈?

algorithm - 深度学习,关于使用哪种架构的建议

python - Pytorch: AttributeError: 'function' 对象没有属性 'copy'