Error in total_variation loss -- TypeError: list indices must be integers or slices, not tuple

I have the following function for calculating total variation loss:

def tvLoss(self, img):
		vertical   = torch.abs(img[:, :, 1:, :] - img[:, :, :-1, :])
		horizontal = torch.abs(img[:, :, :, 1:] - img[:, :, :, :-1])
		loss       = torch.sum(horizontal) + torch.sum(vertical)
		return loss

But I get the following error:

 tv_loss  += loss.tvLoss(img)
  File "/home/project/network.py", line 169, in tvLoss
    vertical   = torch.abs(img[:, :, 1:, :] - img[:, :, :-1, :])
TypeError: list indices must be integers or slices, not tuple

How do I resolve this error?

I don’t know what your input is but would assume it’s a tensor.
If so, then I cannot reproduce the error using:

def tvLoss(img):
	vertical   = torch.abs(img[:, :, 1:, :] - img[:, :, :-1, :])
	horizontal = torch.abs(img[:, :, :, 1:] - img[:, :, :, :-1])
	loss       = torch.sum(horizontal) + torch.sum(vertical)
	return loss

img = torch.randn(2, 3, 24, 24)
out = tvLoss(img)

My input is of type <class 'list'>.

Could you describe how this list should be indexed as it seems you expect it to have 4 dimensions?

It is actually the extracted features of an image. It is a list of 4 tensors extracted from 4 different layers of the VGG-19 network.

You would still need to index the list in a single dimension as seen here:

l = [torch.randn(2) for _ in range(4)]
print(l)
# [tensor([ 0.3270, -2.2517]), tensor([-0.2995, -0.1264]), tensor([ 0.1325, -0.0489]), tensor([-1.1356, -0.3686])]

print(l[0])
# tensor([ 0.3270, -2.2517])

print(l[-1])
# tensor([-1.1356, -0.3686])

print(l[:, 0])
# TypeError: list indices must be integers or slices, not tuple