import torch X = torch.rand((4, 5)) Y = torch.rand((5, 2)) Z = torch.empty((4, 2)) for i inrange(X.shape[0]):for j inrange(Y.shape[1]): total =0for k inrange(X.shape[1]): total += X[i,k]* Y[k,j] Z[i,j]= total
其可能用于其他用途,但转置向量或矩阵似乎是最著名的用例。
求和:
import torch X = torch.rand((2, 3)) a = torch.einsum('ij->', X) torch.sum(X) print(a)
简单求和,我们不返回索引。输出是一个标量。或者,准确地说,是一个只有一个值的张量。
行和列求和:
import torch X = torch.rand((2, 3)) a = torch.einsum('ij->i', X) torch.sum(X, axis=1) print(a) b = torch.einsum('ij->j', X) torch.sum(X, axis=0) print(b)
逐元素乘法:
import torch X = torch.rand((3, 2)) Y = torch.rand((3, 2)) A = torch.einsum('ij, ij->ij', X, Y) torch.mul(X, Y)# or X * Y print(A)
点积:
import torch v = torch.rand((3)) c = torch.rand((3)) a = torch.einsum('i, i->', v, c) torch.dot(v, c) print(a)
外积:
import torch v = torch.rand((3)) t = torch.rand((3)) A = torch.einsum('i, j->ij', v, t) torch.outer(v, t) print(A)
矩阵向量乘法
import torch X = torch.rand((3, 3)) y = torch.rand((1, 3)) A = torch.einsum('ij, kj->ik', X, y) torch.mm(X, torch.transpose(y, 0, 1))# or torch.mm(X, y.T) print(A)
矩阵矩阵乘法
import torch X = torch.arange(6).reshape(2, 3) Y = torch.arange(12).reshape(3, 4) A = torch.einsum('ij, jk->ik', X, Y) torch.mm(X, Y) print(A)
批量矩阵乘法
import torch X = torch.arange(24).reshape(2, 3, 4) Y = torch.arange(40).reshape(2, 4, 5) A = torch.einsum('ijk, ikl->ijl', X, Y) torch.bmm(X, Y) print(A)