I am working with 2 tensors. Tensor A's shape is (20,28,28) (20 images of 28 by 28 pixels), tensor B's shape is (10,28,28) (10 images of 28 by 28 pixels).
I want to calculate the mean absolute difference between every image in tensor A and every image in tensor B and get as a result a matrix with shape (20,10). Which would be 20 rows for the 20 images in tensor A and 10 columns for the 10 images in tensor B.
I can achieve this with a for loop:
L1 = torch.FloatTensor([(i-B).abs().mean(dim=(1,2)).tolist() for i in A])
tensor([[0.1178, 0.2220, 0.2052, 0.1930, 0.2075, 0.1786, 0.1962, 0.2047, 0.1957, 0.2019],
[0.1993, 0.0750, 0.1394, 0.1397, 0.1367, 0.1474, 0.1555, 0.1349, 0.1245, 0.1333],
[0.1755, 0.1427, 0.1306, 0.1570, 0.1535, 0.1551, 0.1415, 0.1562, 0.1357, 0.1460],
[0.1834, 0.1641, 0.1729, 0.1567, 0.1714, 0.1597, 0.1810, 0.1797, 0.1513, 0.1600],
[0.1784, 0.1501, 0.1701, 0.1872, 0.1100, 0.1556, 0.1500, 0.1304, 0.1615, 0.1236],
[0.1721, 0.1493, 0.1879, 0.1566, 0.1405, 0.1308, 0.1612, 0.1515, 0.1540, 0.1362],
[0.2120, 0.2122, 0.1825, 0.2177, 0.1980, 0.2246, 0.1625, 0.2284, 0.2037, 0.2088],
[0.1660, 0.1416, 0.1833, 0.1715, 0.1541, 0.1603, 0.1698, 0.1120, 0.1744, 0.1452],
[0.1754, 0.0756, 0.1381, 0.1344, 0.1297, 0.1315, 0.1264, 0.1313, 0.1298, 0.1239],
[0.1779, 0.1117, 0.1559, 0.1488, 0.1098, 0.1341, 0.1449, 0.1121, 0.1315, 0.0942],
[0.1379, 0.1934, 0.1745, 0.1803, 0.1583, 0.1664, 0.1357, 0.1654, 0.1754, 0.1583],
[0.1838, 0.0509, 0.1413, 0.1352, 0.1373, 0.1339, 0.1407, 0.1251, 0.1353, 0.1303],
[0.2098, 0.1854, 0.1525, 0.2024, 0.1904, 0.2019, 0.1763, 0.1971, 0.1997, 0.2072],
[0.1873, 0.1537, 0.1851, 0.1570, 0.1877, 0.1609, 0.1852, 0.1765, 0.1797, 0.1814],
[0.1806, 0.0861, 0.1430, 0.1455, 0.1129, 0.1283, 0.1347, 0.1205, 0.1260, 0.1154],
[0.1766, 0.1741, 0.1769, 0.1462, 0.1456, 0.1537, 0.1496, 0.1777, 0.1549, 0.1470],
[0.1643, 0.1477, 0.1629, 0.1795, 0.1668, 0.1706, 0.1509, 0.1786, 0.1600, 0.1658],
[0.1768, 0.1336, 0.1833, 0.1610, 0.1333, 0.1498, 0.1630, 0.1126, 0.1631, 0.1277],
[0.1845, 0.1066, 0.1648, 0.1482, 0.1361, 0.1338, 0.1526, 0.1308, 0.1354, 0.1243],
[0.1922, 0.1185, 0.1678, 0.1458, 0.1148, 0.1321, 0.1397, 0.1077, 0.1329, 0.0950]])
But want to do it with a vectorised operation.
I tried adding a dimension to tensor B but it didn't work.
(A-B.view(-1,10,28,28)).abs().mean(dim=(2,3))
tensor([[0.1434, 0.0953, 0.1443, 0.1567, 0.1147, 0.1277, 0.1276, 0.1191, 0.1464, 0.1137]])
which is the equivalent of torch.diag(L1)
Is this possible and if so, how would you do it?