1.1 数据操作
In [1]:
import torch
torch.manual_seed(0)#设置 (CPU) 生成随机数的种子,一旦固定种子,后面依次生成的随机数其实都是固定的
torch.cuda.manual_seed(0)#为GPU生成随机数种子
print(torch.__version__)
1.9.0
1.1.1 创建Tensor
创建一个5x3的未初始化的Tensor
:
In [2]:
x = torch.empty(5, 3)
print(x)
tensor([[1.6932e+22, 3.0728e+32, 1.1093e+27], [7.4111e+34, 1.7936e+25, 6.2618e+22], [4.7428e+30, 2.9514e+29, 1.4607e-19], [1.8888e+31, 3.0308e+24, 1.1542e+19], [4.7429e+30, 1.6098e+19, 4.7429e+30]])
创建一个5x3的随机初始化的Tensor
:
In [3]:
x = torch.rand(5, 3)
print(x)
tensor([[0.4963, 0.7682, 0.0885], [0.1320, 0.3074, 0.6341], [0.4901, 0.8964, 0.4556], [0.6323, 0.3489, 0.4017], [0.0223, 0.1689, 0.2939]])
创建一个5x3的long型全0的Tensor
:
In [4]:
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
tensor([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
直接根据数据创建:
In [5]:
x = torch.tensor([5.5, 3])
print(x)
tensor([5.5000, 3.0000])
还可以通过现有的Tensor
来创建,此方法会默认重用输入Tensor
的一些属性,例如数据类型,除非自定义数据类型。
In [6]:
x = x.new_ones(5, 3, dtype=torch.float64) # 返回的tensor默认具有相同的torch.dtype和torch.device
print(x)
x = torch.randn_like(x, dtype=torch.float) # 指定新的数据类型
print(x)