pytorch常用API
一、torch.tensor()和torch.from_numpy()
import torch
import numpy as npa = [1, 2, 3.0]
a = np.asarray([1, 2, 3.0])
b = torch.tensor(a) # 此时a和b不共享内存print(b) # tensor([1., 2., 3.], dtype=torch.float64)
print(b.dtype) # torch.float64
print(b.device) # CPU
print(b.requires_grad) # Flaseb = torch.from_numpy(a) #此时a和b共享内存
二、将tensor对象转换为numpy对象
a = [1, 2, 3, 4.0]
b = torch.tensor(a)
print(b) # tensor([1., 2., 3., 4.])
print(b.device, b.dtype, b.requires_grad, b.shape) # cpu torch.float32 False torch.Size([4])# 将Tensor对象转换为Numpy对象 --> 要求tensor对象必须在cpu上
# cpu: 将tensor数据复制到cpu上,如果数据本身就在cpu上,就直接返回原始数据;否则copy一份数据到cpu
# detach: 梯度反向传播路径的截断,表示产生一个新节点,基于该新节点的后续所有操作,不往前传递梯度
# c = b.cpu().numpy()
c = b.cpu().detach().numpy()
print(c) # [1. 2. 3. 4.]
c[0] = 100
print(c) # [100. 2. 3. 4.]
print(b) # tensor([100., 2., 3., 4.])
print(list(c)) # [100.0, 2.0, 3.0, 4.0]
三、随机数相关API
1、
torch.manual_seed(28) # 设置随机数种子torch.normal(0., 1.0, (2, 3)) # 产生一个[2,3]大小的tensor,tensor中值满足均值为0,标准差为1
2、
torch.rand((2,3)) # 产生一个[2,3]大小的tensor,tensor中值满足[0,1)的均匀分布
3、
print(np.random.permutation(10))
print(torch.randperm(10))
四、索引相关API
1、
a = torch.rand((2,3)) # a是一个两维的矩阵 shape为[2,3]
print(a)# 按照第0维进行数据的合并(行) --> [6,3]
b = torch.cat((a,a,a), dim=0)
print(b, "\n", b.shape)
# 按照第1维进行数据的合并(列) --> [2,9]
c = torch.cat((a,a,a), dim=1)
print(c, "\n", c.shape)
2、
# 这个2表示期望输出的tensor数目最多是2个,每个的大小其实 [total/2] 向上取整
torch.chunk(c, 2, dim=1) # 这个2表示期望的输出结果是2个tensor
3、
# 这个4表示期望每个输出的大小最多是4
torch.split(c, 4, dim=1) # 输出的tensor中,每个tensor在dim=1这个维度最多是两维
4、
torch.split(c, (5,2,2), dim=1) # 期望输出3个tensor,每个tensor在第1维上的大小分别为5 、2 、2
4、
x = torch.rand(2, 3)
print(x)
print(torch.transpose(x, dim0=1, dim1=0))
5、
x = torch.rand(2, 3, 4)
print(x, "\n", x.shape)# 维度转置交换
y = torch.transpose(x, dim0=2, dim1=0)
print(y, "\n", y.shape)
6、
a = torch.rand(5, 3, 4)
print(a.shape)# 将原来的第1维作为现在的第0维、2->1、0->2
b = torch.permute(a, dims=(1, 2, 0))
print(b.shape)
7、
a = torch.rand(2, 3)
b = torch.reshape(a, (3,2))
# view这个reshape操作,要求tensor对象在内存中必须是连续的
# contiguous: 将对象内存重新排序 --> 内存数据变成连续
c = b.view((1, 6))
#c = b.T.contiguous().view((1, 6))
# c = b.T.reshape((1, 6))
print(a)
print(b)
print(c)
五、Tensor数值运算相关API
1、
x = torch.randn(2,3)
print(x)
print(torch.abs(x))
print(x.abs())
2、
x = torch.rand(2,3)
y = torch.rand(3,2)
print(x)
print(y)# 多维举证乘法,只需要满足最后两个维度是否满足矩阵乘法要求:[2,3] @ [3,2]=[2,2]
# 其他维度要求满足广播机制
c = torch.matmul(x, y)
print(c)
3、
x = torch.rand(4, 1, 2, 3)
y = torch.rand(1, 3, 3, 2)
print(x.shape)
print(y.shape)
# 多维矩阵乘法:仅需要考虑最后两个维度是否满足矩阵乘法的要求 [m,k] * [k,n] -> [m,n]
# PS: 其它维度要求满足广播的机制
# [4,2,3]*[4,3,2] -> [4,2,2]
# [4,2,3]*[3,2] -> [4,2,2]
c = torch.matmul(x, y)
print(c.shape)
4、
x = torch.randn(3,4) * 2
print(x)
print(torch.sigmoid(x))
import torch.nn.functional as F
print(F.sigmoid(x))