tensor:张量,有点像向量
tensor的属性:
data:数据
dtype:张量的数据类型 如:torch.FloatTensor
shape:张量的形状
device:张量所在的设备
requires_grad:是否需要求导
grad:data的梯度
grad_fn:创建Tensor的function
is_leaf:是否为叶子结点
a = np.ones((3, 1))
# t = torch.tensor(a,device='cuda')
t = torch.tensor(a)
print(t)
从numpy创建tensor
numpy中的数据与tensor中的数据使用的同一个内存,一个数据改变另一个也会改变
b = np.array([[1, 2, 3], [4, 5, 6]])
tb = torch.from_numpy(b)
print(tb)
b[0,0] = 0
print(tb)
torch.zeros(
size, 张量大小
out,
layout,内存中的布局形式,有strided sparse_coo
device,
requires_grad
)
out_t=torch.zeros([1])
t=torch.zeros((3,3),out=out_t)
print(t,'\n',out_t)
print(id(t)==id(out_t))
torch.zeros_like(
input, 创建与input同星湖脏的全0张量
dtype,
layout,
device,
requires_gard
)
torch.ones(
size,
out,
layout,内存中的布局形式,有strided sparse_coo
device
requires_grad
)
torch.full(
size,
full_value:张量的值
out,
layout,内存中的布局形式,有strided sparse_coo
device
requires_grad
)
c=torch.full((3,3),1)
print(c)
torch.full_like(
input, 创建与input同星湖脏的全0张量
dtype,
layout,
device,
requires_gard
)
torch.arange(
strat=0,
end,
step=1
out,
dtype,
layout
device
requires_grad
)
创建等差的1维张量 数值区间为:[strat,end)
t=torch.arange(1,10)
print(t)
"""
torch.linspace(
start,
end,
steps,#数列的长度
out,
dtype,
layout,
device,
requires_grad
)
创建均分的1维张量
数值区间[start,end]
"""
t=torch.linspace(1,10,5)
print(t)
创建对数均分的1维张量
torch.logspace(
start,
end,
steps,#数列的长度
base,对数的低 默认为10
out,
dtype,
layout,
device,
requires_grad
)
创建单位对角矩阵
torch.eye(
n #矩阵的行
m #矩阵的列
out,
dtype,
layout,
device,
requires_grad
)
高斯分布
依据概率分布创建
torch.normal(
mean,均值
std,标准差
out
)
mean=torch.arange(1,5,dtype=torch.float)
std=torch.arange(1,5,dtype=torch.float)
t_n=torch.normal(mean,std)
print("mean{},std{}".format(mean,std))
print(t_n)
#标准正态
torch.randn(
size,
out,
dtype,
layout,
device,
requires_grad
)
torch.randn_like(
input,
out,
dtype,
layout,
device,
requires_grad
)
#均匀分布[0,1)
torch.rand(
size
out,
dtype,
layout,
device,
requires_grad
)
torch.randint(
low,
high,
size
out,
dtype,
layout,
device,
requires_grad
)
#区间[low,high)
#0-n-1的随机排列
torch.randperm(
n,
out,
dtype,
layout,
device,
requires_grad
)
#以input为概率生成伯努利分布
torch.bernoulli(
input,
generator,
out
)