官方文档地址:https://pytorch.org/docs/stable/torch.html
代码
import torch
print('# 例1、对角线都是1的矩阵')
x = torch.eye(3, 3) # 3x3的单位矩阵,对角线都是1
print(x)
print(x.size(), "\n")
print('# 例2、全是0的矩阵')
x = torch.zeros(3, 3) # 3x3的矩阵,全0
print(x)
print(x.shape) # 等价于 print(x.size())
print(x.size(), "\n")
x = torch.zeros(3, 3, dtype=torch.long) # 指定数据类型为long
print(x)
print(x.size(), "\n")
print('# 例3、全是1的矩阵')
x = torch.ones(3, 3) # 3x3的矩阵,全1
print(x)
print(x.size(), "\n")
print('# 例4、随机矩阵')
x = torch.rand(3, 3) # 3x3的矩阵,随机初始化
print(x)
print(x.size(), "\n")
print('# 例5、根据范围生成一维矩阵')
x = torch.arange(0, 10, 2) # 从0到10,步长为2
print(x)
print(x.size(), "\n")
x = torch.arange(5) # 从0到5,步长为1
print(x)
print(x.size(), "\n")
print('# 例6、均匀分片生成一维矩阵')
x = torch.linspace(0, 10, 6) # 从0到10,等分成6份
print(x)
print(x.size(), "\n")
print('# 例7、正态分布生成一维矩阵')
x = torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1))
print(x)
print(x.size(), "\n")
print('# 例8、生成随机排列')
x = torch.randperm(10) # 生成0到10的随机排列,10个数
print(x)
print(x.size(), "\n")
print('# 例9、从数据直接创建')
x = torch.tensor([1, 2, 3, 4]) # 从数据直接创建一维矩阵
print(x)
print(x.size(), "\n")
x = torch.tensor([[1, 2, 3], [4, 5, 6]]) # 从数据直接创建二维矩阵
print(x)
print(x.size(), "\n")
运行结果
# 例1、对角线都是1的矩阵
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
torch.Size([3, 3])
# 例2、全是0的矩阵
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
torch.Size([3, 3])
torch.Size([3, 3])
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
torch.Size([3, 3])
# 例3、全是1的矩阵
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
torch.Size([3, 3])
# 例4、随机矩阵
tensor([[0.4530, 0.4226, 0.4092],
[0.1351, 0.8594, 0.7021],
[0.9496, 0.4814, 0.6343]])
torch.Size([3, 3])
# 例5、根据范围生成一维矩阵
tensor([0, 2, 4, 6, 8])
torch.Size([5])
tensor([0, 1, 2, 3, 4])
torch.Size([5])
# 例6、均匀分片生成一维矩阵
tensor([ 0., 2., 4., 6., 8., 10.])
torch.Size([6])
# 例7、正态分布生成一维矩阵
tensor([0.6623, 1.2843, 2.8861, 3.9618, 4.6383, 6.1333, 7.1289, 8.0894, 9.3103,
9.9388])
torch.Size([10])
# 例8、生成随机排列
tensor([5, 4, 9, 0, 2, 8, 3, 7, 6, 1])
torch.Size([10])
# 例9、从数据直接创建
tensor([1, 2, 3, 4])
torch.Size([4])
tensor([[1, 2, 3],
[4, 5, 6]])
torch.Size([2, 3])
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏