pytorch Tensor的基本用法
- Tensor的创建
- 索引,合并,切片
- 初始化
- 数学操作
1. Tensor的创建
1) 随机数字
torch.rand(*sizes, out=None) → Tensor
返回一个张量,包含了从区间[0, 1)的均匀分布中抽取的一组随机数。张量的形状由参数sizes定义
# torch.rand(sizes) -> [0,1)之间的均匀分布
x = torch.rand(2,3)
x
out:
0.9161 0.7135 0.8969
0.7552 0.8760 0.2236
[torch.FloatTensor of size 2x3]
torch.randn(*sizes, out=None) → Tensor
返回一个张量,包含了从标准正态分布(均值为0,方差为1,即高斯白噪声)中抽取的一组随机数。张量的形状由参数sizes定义
# torch.randn(sizes) -> Z(0,1)
x = torch.randn(2,3)
x
out:
-1.9352 0.9779 1.7401
2.0432 -0.1962 -0.1177
[torch.FloatTensor of size 2x3]
torch.randperm(n)
返回张量, 0~n之间的一个全排列
# torch.randperm(n) -> permutation of 0~n
x = torch.randperm(5)
x
out:
3
1
4
0
2
[torch.LongTensor of size 5]
2) zeros, ones, eye, arrange
torch.zeros(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
返回张量,用0填充,size有参数sizes确定
# torch.zeros(2,3) -> [[0,0,0],[0,0,0]]
x = torch.zeros(2,3)
x
out:
0 0 0
0 0 0
[torch.FloatTensor of size 2x3]
torch.ones(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
返回张量,用1填充,size有参数sizes确定
# torch.ones(2,3) -> [[0,0,0],[0,0,0]]
x = torch.ones(2,3)
x
out:
1 1 1
1 1 1
[torch.FloatTensor of size 2x3]
torch.arange(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
返回一维张量,在[start, end)区间内,按step为间隔返回一个等差数列,
o u t i + 1 = o u t i + s t e p out_{i+1} = out_i + step outi+1=outi+step
# torch.arange(start,end,step=1) -> [start,end) with step
y = torch.arange(1, 4)
x = torch.arange(0,3,step=0.5)
y
x
out:
tensor([ 1, 2, 3])
0.0000
0.5000
1.0000
1.5000
2.0000
2.5000
[torch.FloatTensor of size 6]
torch.eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
返回二维对角矩阵张量,对角线上为1,其余为0
torch.eye(3)
out:
tensor([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
3) Tensor 数据类型
所有的数据类型都在这里
https://pytorch.org/docs/stable/tensors.html#torch-tensor
创建size为[2,3]的浮点数张量
# torch.FloatTensor(size or list)
x = torch.FloatTensor(2,3)
x
out:
-7.4341e-17 4.5629e-41 -7.4341e-17
4.5629e-41 -7.4342e-17 2.9427e-44
[torch.FloatTensor of size 2x3]
创建数据为2,3的浮点数张量
# torch.FloatTensor(size or list)
x = torch.FloatTensor([2,3])
x
out:
2
3
[torch.FloatTensor of size 2]
转换为整型张量
# tensor.type_as(tensor_type)
x = x.type_as(torch.IntTensor())
x
out:
2
3
[torch.IntTensor of size 2]
4) Tensor 和 numpy的相互转换
从numpy转换为Tensor
import numpy as np
# torch.from_numpy(ndarray) -> tensor
x1 = np.ndarray(shape=(2,3), dtype=int,buffer=np.array([1,2,3,4,5,6