pytorch中张量tensor的使用以及相关函数介绍
导入torch模块
import torch
#初始化一个2*3矩阵
X=[ [1,2,3],
[4,5,6] ]
Tensor生成
#生成整型张量
a=torch.IntTensor(X)
print(a)
>>tensor([[1, 2, 3],
[4, 5, 6]], dtype=torch.int32)
#自定义数据维度生成(2,3)
b=torch.IntTensor(2,3)
print(b)
>>tensor([[0, 0, 0],
[0, 0, 0]], dtype=torch.int32)
#生成浮点型张量
c=torch.FloatTensor(X)
print(c)
>>tensor([[1., 2., 3.],
[4., 5., 6.]])
d=torch.FloatTensor(2,3)
print(d)
>>tensor([[0., 0., 0.],
[0., 0., 0.]])
#生成空的张量
e=torch.empty(1,3)
print(e)
>>tensor([[2.3694e-38, 3.6013e-43, 0.0000e+00]])
#生成均匀分布的随机张量
f=torch.rand(2,3)
print(f)
>>tensor([[0.4933, 0.1631, 0.7526],
[0.7490, 0.0400, 0.6873]])
#生成标准正态分布的随机张量
g=torch.randn(2,3)
print(g)
>>tensor([[-0.6483, 0.6056, -0.2008],
[ 0.5404, 0.4420, 0.6512]])
#生成离散正态分布的随机张量,均值为1,标准差为0.1
h=torch.normal(1,0.1,(2,3))
print(h)
>>tensor([[1.1328, 0.8543, 1.0340],
[0.9768, 1.0010, 1.0519]])
#生成指定维度的张量,使用指定数值填充
i=torch.full((2,3),2)
print(i)
>>tensor([[2, 2, 2],
[2, 2, 2]])
#生成指定值为1的固定维度张量
j=torch.ones(2,3)
print(j)
>>tensor([[1., 1., 1.],
[1., 1., 1.]])
#生成指定值为0的固定维度张量
k=torch.zeros(2,3)
print(k)
>>tensor([[0., 0., 0.],
[0., 0., 0.]])
Tensor转换
将list和ndarray数值转换成tensor
import numpy as np
Y=np.array(X)
print(Y)
>>[[1 2 3]
[4 5 6]]
#直接将数据转换成tensor
a=torch.tensor(Y)
print(a)
>>tensor([[1, 2, 3],
[4, 5, 6]], dtype=torch.int32)
#as_tensor()会将内存空间进行改变
b=torch.as_tensor(Y)
print(b)
>>tensor([[1, 2, 3],
[4, 5, 6]], dtype=torch.int32)
Y[0][0]=0
print(Y)
>>[[0 2 3]
[4 5 6]]
改变tensor形状
Y=np.array(X)
a=torch.tensor(Y)
print(a.size())
>>torch.Size([2, 3])
#将2*3转换成3*2
b=a.view(3,2)
print(b.size())
>>torch.Size([3, 2])
tensor默认存储在cpu上,当存在GPU时,可以将数据加载到GPU提速
a.cuda() #加载到gpu上
a.cpu() #加载到cpu上
#自动选择,若有gpu则加载到GPU上,否则使用cpu
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
a.device()
自动求导
x=torch.ones(2,2,requires_grad=True)
y=x+2
z=y*y*3
out=z.mean()
out.backward()
print(x.grad)
>>tensor([[4.5000, 4.5000],
[4.5000, 4.5000]])