Tensor是Pytorch的一种特殊的数据结构,用法类似Numpy中的ndarrays。
创建Tensor的方法
1 直接从数据创建
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
输出结果:
tensor([[1, 2],
[3, 4]])
2 拷贝其他数组形状来创建
data = [[1,2],[3,4]]
x_data = torch.tensor(data)
print(x_data)
x_ones = torch.ones_like(x_data)
print(x_ones)
x_rand = torch.rand_like(x_data, dtype=torch.float)
print(x_rand)
输出结果:
tensor([[1, 2],
[3, 4]])
tensor([[1, 1],
[1, 1]])
tensor([[0.9180, 0.1956],
[0.7514, 0.8894]])
3 创建随机数
shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)
默认类型是tensor.float32
输出结果:
tensor([[0.0022, 0.9311, 0.3372],
[0.4651, 0.9878, 0.0557]])
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[0., 0., 0.],
[0., 0., 0.]])
4 Tensor类型
print(zeros_tensor.shape)
print(zeros_tensor.dtype)
print(zeros_tensor.device)
输出结果:
torch.Size([2, 3])
torch.float32
cpu
5 Tensor 的操作
https://pytorch.org/docs/stable/torch.html