tensor张量创建的一个数组。
张量用来存放图片0-255的数值。
图像处理其实就是处理数字,利用卷积神经网络。
1)torch.tensor():
torch. tensor(data, dtype=None, device=None, requires_grad=False, pin_memory=False)
功能:从data创建tensor
·data:数据,可以是list,numpy
·dtype:数据类型,默认与data的一致
·device:所在设备,cuda/cpu
·requires_grad:是否需要梯度
·pin_memory:是否存于锁页内存
2)torch.from_numpy(ndarray)
功能:从nunpy创建tensor
注意事项:从torch.from_numpy创建的tensor于原ndarray共享内存,当修改其中一个的数据,另外一个也将会被改动
3)依据数值直接创建 torch.zeros()
torch.zeros(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
功能:依size创建全0张量
·size:张量的形状,如(3,3)、(3,224,224)
·out:输出的张量
·layout:内存中布局形式,有strided(默认值一般用这个),sparse_coo(稀疏矩阵才用这个,会提高读取效率)等
·device:所在设备,gpu/cpu
·requires_grad:是否需要梯度
通过torch.zeros创建张量
out_t = torch.tensor([1])
t = torch.zeros((3, 3), out=out_t)#这是最奇怪的地方,Out的结果要传给了out_t
print(t, '\n', out_t)
print(id(t), id(out_t), id(t) == id(out_t))
4)torch.ones_like()
torch. ones_like(input, dtype=None,layout=None, device=None, requires_grad=False)
功能:依input形状创建全1张量
·size:张量的形状,如(3,3)、(3,224,224)
·dtype:数据类型
·layout:内存中布局形式
·device:所在设备,gpu/cpu
·requires_grad:是否需要梯度
# 通过torch.full创建全1张量
# flag = True
flag = False
if flag:
t = torch.full((3, 3), 1)
print(t)
5)torch.full()和 torch.full_like()
功能:依input形状创建全0张量
·size:张量的形状,如(3,3)
·fill_value:张量的值
torch. full(size, fill_value, out=None, dtype=None,layout=torch. strided, device=None, requires_grad=False)
6)torch.arange()
功能:创建等差的1维张量
注意事项:数值区间为[start,end)
·start:数列起始值
·end:数列“结束值”
·step:数列公差,默认为1
torch. arange(start=e, end, step=1, out=None, dtype=None,layout=torch. strided, device=None, requires_grad=False)
7)torch.linspace()
功能:创建均分的1维张量
注意事项:数值区间为[start,end]
·start:数列起始值
·end:数列结束值
·steps:数列长度,注意这里不是长度,不是步长。
torch. linspace(start, end, steps=100, out=None, dtype=None, layout=torch. strided, device=None, requires_grad=False)
8) torch.logspace()
功能:创建对数均分的1维张量
注意事项:长度为steps,底为base
·start:数列起始值
·end:数列结束值
·steps:数列长度
·base:对数函数的底,默认为10
9) torch.eye()
功能:创建单位对角矩阵(2维张量)
注意事项:默认为方阵
·n:矩阵行数
·m:矩阵列数
10)torch.normal()
功能:生成正态分布(高斯分布)
·mean:均值。
·std:标准差
**torch. normal(mean, std, out=None)**
四种模式:
mean为标量,std为标量(参数多一个:size)
mean为标量,std为张量
mean为张量,std为标量(可以用来初始化权重)
mean为张量,std为张量
# 通过torch.normal创建正态分布张量
flag = True
# flag = False
if flag:
# mean:张量 std: 张量
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std)
print("mean:{}\nstd:{}".format(mean, std))
print(t_normal)
11)torch.randn()和 torch.randn like()
torch.randn(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
功能:生成标准正态分布
·size:张量的形状
12)torch.randint()和torch.randint_like()
功能:区间[low,high)生成整数均匀分布
·size:张量的形状
13) torch.randperm()
功能:生成生成从0到n-1的随机排列
·n:张量的长度
14) torch.bernoulli()
功能:以input为概率,生成伯努力分布(0-1分布,两点分布)
·input:概率值
pytorch中文参考文档:MD格式
https://pytorch.org/docs/stable/index.html