pytorch中自定义backward()函数。在图像处理过程中,我们有时候会使用自己定义的算法处理图像,这些算法多是基于numpy或者scipy等包。那么如何将自定义算法的梯度加入到pytorch的计算图中,能使用Loss.backward()操作自动求导并优化呢。下面的代码展示了这个功能`
import torch
import numpy as np
from PIL import Image
from torch.autograd import gradcheck
class Bicubic(torch.autograd.Function):
def basis_function(self, x, a=-1):
x_abs = np.abs(x)
if x_abs < 1 and x_abs >= 0:
y = (a + 2) * np.power(x_abs, 3) - (a + 3) * np.power(x_abs, 2) + 1
elif x_abs > 1 and x_abs < 2:
y = a * np.power(x_abs, 3) - 5 * a * np.power(x_abs, 2) + 8 * a * x_abs - 4 * a
else:
y = 0
return y
def bicubic_interpolate(self,data_in, scale=1 / 4, mode='edge'):
# data_in = data_in.detach().numpy()
self.grad = np.zeros(data_in.shape,dtype=np.float32)
obj_shape = (int(data_in.shape[0] * scale), int(data_in.shape[1] * scale), data_in.shape[2])
data