使用PyTorch我在使用两个变量进行操作时遇到问题:
sub_patch : [torch.FloatTensor of size 9x9x32]
pred_patch : [torch.FloatTensor of size 5x5x32]
sub_patch是由torch.zeros制作的变量 pred_patch是一个变量,我用一个嵌套的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_patch也是一个变量,但我怎样才能解决这个错误呢?任何帮助将不胜感激!
谢谢!
答案 0 :(得分:2)
我发现问题在
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 + b)。在第二种情况下,创建一个包含+ b的全新张量,然后将此新张量指定给名称a。 为了能够计算渐变,有时需要保持a的原始值,因此我们阻止了就地操作,否则我们将无法计算渐变。