错误记录:RuntimeError: Output 0 of SelectBackward0 is a view and is being modified inplace

起因:在修改tensor数据的值的时候,出现上述错误。

完整错误信息:RuntimeError: Output 0 of SelectBackward0 is a view and is being modified inplace. This view is the output of a function that returns multiple views. Such functions do not allow the output views to be modified inplace. You should replace the inplace operation by an out-of-place one.

错误原因:为图方便,直接对tensor数据进行迭代,获取每个batch下和每个channel下的数据。但实际上系统不允许这么做。

错误代码:

    for datas in x:
        # 取得batch中的一张图片的tensor数据
        for data in datas:
            # 取得图片中的一个通道的tensor数据
            meanValue = data.mean()
            if mode == 'enhance':
                maxValue = data.max()
            else:
                minValue = data.min()
            count = 0
            for row in range(data.shape[0]):
                for col in range(data.shape[1]):
                    if data[row][col] > meanValue:
                        if mode == 'enhance':
                            data[row][col] = maxValue
                        else:
                            data[row][col] = minValue
                        count += 1
                    if count == 0.2 * torch.numel(data):
                        break
                if count == 0.2 * torch.numel(data):
                    break

修改方法:不再使用x、datas等作为迭代器;而是使用batch、channels作为索引,在通过下标索引修改data的值。

batch, channels, height, weight = x.shape

    for b in range(batch):
        # 取得batch中的一张图片的tensor数据
        for c in channels:
            # 取得图片中的一个通道的tensor数据
            meanValue = x[b][c].mean()
            if mode == 'enhance':
                maxValue = x[b][c].max()
            else:
                minValue = x[b][c].min()
            count = 0
            for row in range(x[b][c].shape[0]):
                for col in range(x[b][c].shape[1]):
                    if x[b][c][row][col] > meanValue:
                        if mode == 'enhance':
                            x[b][c][row][col] = maxValue
                        else:
                            x[b][c][row][col] = minValue
                        count += 1
                    if count == 0.2 * torch.numel(x[b][c]):
                        break
                if count == 0.2 * torch.numel(x[b][c]):
                    break

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值