@TOC
创建tensor
1. 指定tensor
- 如果tensor都是整形,默认创建的都是
torch.int64 - 如果tensor有一个浮点型,创建的就是
torch.float32 - 也可以用
tensor.type()来改变tensor类型
1 | tensor = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) |
2. 创建特殊类型的tensor
(1)空tensor(empty)
torch.empty(size)
返回一个未初始化的tensor(初始化比较随意)
Returns a tensor filled with uninitialized data. The shape of the tensor is defined by the variable argument size.
1 | tensor = torch.empty((2, 3)) |
(2)全为一(ones)
torch.ones(size)
返回一个全为1的tensor
Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size.
1 | tensor = torch.ones((2, 3)) |
(3)全为零(zeros)
torch.ones(size)
返回一个全为0的tensor
Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size.
1 | tensor = torch.zeros((2, 3)) |
(4)均匀分布(rand)
torch.rand(size)
返回符合
的均匀分布:torch.float32
Returns a tensor filled with random numbers from a uniform distribution on the interval [0, 1)
1 | tensor = torch.rand(4) |
(5)正态分布(randn)
torch.randn(size)
返回
的正态分布:torch.float32
Returns a tensor filled with random numbers from a normal distribution with mean 0 and variance 1 (also called the standard normal distribution).
1 | tensor = torch.randn(4) |
(6)整数范围(randint)
torch.randint(low=0, high, size)
返回随机tensor,每一项的取值范围为
:torch.int64
Returns a tensor filled with random integers generated uniformly between
low(inclusive) andhigh(exclusive).
1 | tensor = torch.randint(3, 5, (3,)) |
(7)N范围内的随机序列(randperm)
torch.randperm(n)
返回
之间的随机tensor序列:torch.int64
Returns a random permutation of integers from
0ton - 1.
可以用torch.randperm()来将tensor打乱顺序,如下所示:x输出按照[2, 3, 0, 1]排列
1 | tensor = torch.randperm(4) |
(8)全是value的tensor(full)
torch.full(size, full_value)
创建一个tensor,他的值全是value
Creates a tensor of size size filled with fill_value. The tensor’s dtype is inferred from fill_value.
1 | tensor = torch.full((2, 3), 2.649) |
3. 创建于当前tensor相同大小的tensor
假如有一个tensor1,我们想创建一个和他一样大小的tensor2,PyTorch也给我们提供了*_like函数,其中的星号可以为上述讲过的ones,zeros等
例如我们的tensor1大小为(2, 3),我们想创建一个大小为(2 ,3)并且是全1的tensor,就可以使用ones_like()函数
1 | tensor1 = torch.tensor([[1, 2, 3],[4, 5, 6]]) |
与上述相同的还有torch.empty_like()、torch.ones_like()、torch.zeros_like()、torch.rand_like()、torch.randn_like()、torch.randint_like(),使用方法原函数相同,不同的地方在于size换成要与之相匹配的tensor即可