这里讲的是用torch来如何运用基本运算操作
废话不多说 上代码
-
导入PyTorch库:
import torch -
torch.randint函数生成随机整数张量:
a = torch.randint(1, 5, (2, 3)) b = torch.randint(1, 5, (2, 3))这里使用
torch.randint函数生成两个随机整数张量a和b。torch.randint的第一个参数是随机数的最小值,第二个参数是最大值(不包含),第三个参数是张量的形状。所以这里生成的是两个2x3的张量,其中的元素是1到4之间的随机整数。 -
打印张量a和b:
print("a的输出:\n", a) print("b的输出:\n", b) 执行a的输出: tensor([[3, 2, 2], [3, 1, 4]]) 执行b的输出: tensor([[1, 2, 4], [2, 1, 4]])这两行代码打印出张量
a和b的内容。 -
张量相加:
c = torch.add(a, b) print("c的输出:\n", c) 执行c的输出: tensor([[4, 4, 6], [5, 2, 8]])这里使用
torch.add函数将张量a和b相加,得到新的张量c。 -
创建3x5的全1张量:
tensor = torch.ones(3, 5) print("tensor的输出:\n", tensor) tensor的输出: tensor([[1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.]])这里使用
torch.ones函数创建一个3x5的全1张量。 -
矩阵乘法:
a = a.float() d = torch.matmul(a, tensor) print("d的输出:\n", d) d的输出: tensor([[7., 7., 7., 7., 7.], [8., 8., 8., 8., 8.]])这里首先将张量
a转换为浮点数类型(因为torch.matmul要求参与运算的张量必须是浮点数类型),然后使用torch.matmul函数进行矩阵乘法运算,得到新的张量d。