错误记录: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

猜你喜欢

转载自blog.csdn.net/adminHD/article/details/127888632