程序代码:
importtorch
# 构建一个未初始化的4 * 5的矩阵
x1 = torch.empty(4, 5)
print("x1 :",x1)
# 构建一个随机初始化的4 * 5的矩阵
x2 = torch.rand(4, 5)
print("x2 :",x2)
# 获取矩阵的大小
print("x2的大小:", x2.size())
# 加法
# 方法一: 使用+运算符实现加法
y2 = torch.rand(4, 5)
print("y2 : ", y2)
print("x2 + y2 :", x2 + y2)
# 加法
# 方法二: 使用函数torch.add()实现加法
print("x2 + y2 :", torch.add(x2, y2))
# 加法
# 方法三: 输出到一个向量
result = torch.Tensor(4, 5)
torch.add(x2, y2, out=result)
print("result :",result)
# 加法
# 方法四: 把x加到y上
y2.add_(x2)
print("y2 :", y2)
运行结果:
x1 : tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000]])
x2 : tensor([[0.8977, 0.5756, 0.1564, 0.7000, 0.5113],
[0.6446, 0.0310, 0.7990, 0.1205, 0.6459],
[0.9925, 0.9360, 0.3241, 0.9435, 0.7958],
[0.9179, 0.7885, 0.3862, 0.9539, 0.7838]])
x2的大小: torch.Size([4, 5])
y2 : tensor([[0.7996, 0.0030, 0.2026, 0.3782, 0.7135],
[0.8308, 0.1337, 0.1978, 0.8895, 0.8733],
[0.4892, 0.8054, 0.5245, 0.9167, 0.0088],
[0.7138, 0.9085, 0.6481, 0.9722, 0.2863]])
x2 + y2 : tensor([[1.6973, 0.5785, 0.3590, 1.0782, 1.2248],
[1.4754, 0.1647, 0.9968, 1.0100, 1.5193],
[1.4817, 1.7414, 0.8486, 1.8602, 0.8046],
[1.6317, 1.6970, 1.0343, 1.9262, 1.0701]])
x2 + y2 : tensor([[1.6973, 0.5785, 0.3590, 1.0782, 1.2248],
[1.4754, 0.1647, 0.9968, 1.0100, 1.5193],
[1.4817, 1.7414, 0.8486, 1.8602, 0.8046],
[1.6317, 1.6970, 1.0343, 1.9262, 1.0701]])
result : tensor([[1.6973, 0.5785, 0.3590, 1.0782, 1.2248],
[1.4754, 0.1647, 0.9968, 1.0100, 1.5193],
[1.4817, 1.7414, 0.8486, 1.8602, 0.8046],
[1.6317, 1.6970, 1.0343, 1.9262, 1.0701]])
y2 : tensor([[1.6973, 0.5785, 0.3590, 1.0782, 1.2248],
[1.4754, 0.1647, 0.9968, 1.0100, 1.5193],
[1.4817, 1.7414, 0.8486, 1.8602, 0.8046],
[1.6317, 1.6970, 1.0343, 1.9262, 1.0701]])