1、创建一个服从均匀分布或者随机分布的张量,其大小可变,可一维,二维
tensor.rand(均匀) :区间(0,1)
与tensor.randn(正太分布):标准差为0,方差为1
参数:
size (int…) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple.
y = torch.rand(4)
y1 = torch.rand(2,3)
print(y)
print(y1)
x = torch.randn(4)
x1 = torch.randn(2,3)
print(x)
print(x1)
输出结果:
tensor([0.4162, 0.4271, 0.0685, 0.1288])
tensor([[0.9016, 0.5871, 0.0199],
[0.4834, 0.1247, 0.3603]])
tensor([ 0.8691, 1.4418, 1.5524, -0.8321])
tensor([[-1.2848, 0.1464, 0.6162],
[-0.2246, 1.0506, -0.2157]])
2、torch.range:返回一个一维张量,左开右闭,可带步长
torch.arange:返回一个一维张量,左开右闭,可带步长
参数:
start (Number) – the starting value for the set of points. Default: 0.
end (Number) – the ending value for the set of points
step (Number) – the gap between each pair of adjacent points. Default: 1.
z = torch.arange(1,6)
print(z)
结果如下:
tensor([1, 2, 3, 4, 5])
小技巧:
返回一维张量的有:linspace,logspace,arange,range
形状可变的有:ones,zeros,rand, randn
二、numpy 与tensor之间的转换
- 由Numpy array数组转为张量
import numpy as np
import torch
numpy_data = np.array([1,4,5])
numpy_to_tensor = torch.from_numpy(numpy_data)
print(numpy_to_tensor)
结果如下:
2、 由张量变换为Numpy array数组
tensor_data = torch.randn(2, 4)
tensor_to_numpy = tensor_data.numpy()
print(tensor_data)
print(tensor_to_numpy)