Like this:
def subtract_layer(x, device):
y = torch.zeros(x.shape[0], x.shape[1])
y = y.to(device)
for i in range(x.shape[0]):
if i % 2 == 0:
y[i, :] = x[i, :] - x[i + 1, :]
y[i + 1, :] = x[i + 1, :] - x[i, :]
return y
In this layer, x’s shape is (batchsize, channels), i need the feature compare result of two neighbor samples.
Is the code correct? Or should I rewrite this layer with forward and backward codes?