-
用nn创建一个线性网络:
import torch import torch.nn as nn m = nn.Linear(20, 30) # 定义一个输入20维,输出30维的线性网络,y=Ax+b,即A是20*30的矩阵 input = torch.randn(128, 20) # 输入数据的大小是128*20且服从正态分布 output = m(input) print(output.size()) # torch.Size([128, 30])
-
用nn进行自适应平均池化,括号中的参数只需要目标的尺寸即可,该方法可以自动匹配输入的尺寸生成池化的大小及步长
# target output size of 5x7 m = nn.AdaptiveAvgPool2d((5,7)) input = torch.randn(1, 64, 8, 9) output = m(input) output.shape # torch.Size([1, 64, 5, 7]) # target output size of 7x7 (square) m = nn.AdaptiveAvgPool2d(7) input = torch.randn(1, 64, 10, 9) output = m(input) output.shape # torch.Size([1, 64, 7, 7]) # target output size of 10x7 m = nn.AdaptiveMaxPool2d((None, 7)) input = torch.randn(1, 64, 10, 9) output = m(input) output.shape # torch.Size([1, 64, 10, 7])
-
基本创建方法:
# 张量Tensor,pytorch的数据封装,可以进行一些数学操作,以及cuda()使用GPU进行张量计算 import torch # 判断是否是张量 torch.is_tensor(obj) # 返回张量的元素数量 torch.numel(obj) # 创建随机张量,指定张量的size a = torch.randn(1,2,3,4,5) # 正态分布 a = torch.rand(2,3,4) # 均匀分布 a = torch.randperm(10) # 随机整数分布,参数为n,范围为[0,n-1] Out[29]: tensor([3, 9, 4, 5, 7, 0, 1, 2, 8, 6]) # 创建全零/全一张量,指定张量的size a = torch.zeros(4,4) a = torch.ones(3,2) # 创建单位张量:torch.eye(n, m=None, out=None) a = torch.eye(3) # [3, 3] a = torch.eye(3,2) # [3, 2] # 按照范围创建:torch.arange(start, end, step=1, out=None) → Tensor torch.arange(1, 2.5, 0.5) # step为间隔大小 # numpy的ndarray转为tensor t = torch.from_numpy(numpy.array([1,2,3])) # 返回start和end之间长度为steps的一维张量:torch.linspace(start, end, steps=100, out=None) → Tensor torch.linspace(-10, 10, steps=5) # 同上,区间为[10^start,10^end]:torch.logspace(start, end, steps=100, out=None)
-
张量操作
# 连接 torch.cat(seq: tensor list, dim=0, out=None) → Tensor # 连接 torch.stack(sequence, dim=0) 沿着一个新维度对输入张量序列进行连接。 序列中所有的张量都应该为相同形状。 # 非0元素的索引 torch.nonzero(input, out=None) → LongTensor # 将维度为1的维度压缩,若指定维度,仅当该维度为1时压缩该维度;否则,全部为1的维度都压缩 a = torch.ones(1,2,1,3,1,4) torch.squeeze(a) # torch.Size([2,3,4]) torch.squeeze(a, 0) # torch.Size([2, 1, 3, 1, 4]) torch.squeeze(a, 1) # torch.Size([1, 2, 1, 3, 1, 4]) # 反压缩 torch.unsqueeze(a, 2) # 将dim维度增加一维 # 转置 torch.t(a) # 仅支持2维 a.t() torch.transpose(a, 2, 3) # 支持任意维度的其中2维转置
-
数学操作
-
序列化(本地存储)
torch.save() torch.load()
-
并行化
torch.get_num_threads() → int # 可操作的CPU线程数 torch.set_num_threads(int) # 设置并行线程数



