自动求导机制的理解
retain_graph (bool, optional) – If False, the graph used to compute the grad will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.
不retain_graph,backward之后就会释放掉
从某分布中随机采样
均匀分布:
构造和x形状相同的从区间[-1, 1]均匀分布采样的tensor:
eta = torch.zeros_like(x).uniform_(-1, 1)
torch.zeros_like(x)可以构造一个dtype、device等等和x相同但值为0的tensor
Optimizer
torch’s optimizers support specifying per-parameter options, we should pass in an iterable of dict
object:
optim.SGD([
{'params': model.base.parameters()},
{'params': model.classifier.parameters(), 'lr': 1e-3}
], lr=1e-2, momentum=0.9)
矩阵运算
torch.bmm(input, mat2)
函数做batch的矩阵乘法,input和mat2都是3D tensor,第一维是batch size, 二三维是矩阵的维度
距离计算
torch.norm()计算范数
nn.PairwiseDistance(p=2)函数,计算p范数距离
F.cosine_similarity,计算余弦相似度
损失函数
nn.CrossEntropyLoss()
输入一般有俩:Input:(N, C), Target: (N), N is number of samples and C is number of classs.
nn.BCELoss()
注意:这里的两个参数需要是FloatTensor类型,我之前送进去的label是int类型,就会报错,送进去之前要先转换成float。
命令行参数
parser = argparse.ArgumentParser()
parser.add_argument("--epoch", type=int, default=10)
args = parser.parse_args()
tensor.repeat(**size)
: 参数数量只能比tensor的维度多,若参数数量和tensor的维度相同,则表示将原来的tensor沿着各自维度复制到相应的倍数;若参数数量多,则靠后的是原tensor相应维度要复制到的倍数,前面的参数是在tensor前面增加的维度。
torch.repeat_interleave(input, repeats, dim=None)
函数将input中的元素重复repeats次,返回一个repeated tensor,除非指定了dim,那么沿着dim进行复制。
torch.max(input, dim)
函数对dim维度求最大值,返回两个值,第一个是max value,第二个是max index。
以后不用max了,直接用:
torch.topk(input, k, dim=-1, largest=True, sorted=True)
,摆的一。返回两个值,第一个是topk values,第二个是topk indexes。其中sorted是指对返回的最大的前k个元素做排序,indexes也会是排序后的indexes。
RNN相关使用
nn.RNN, nn.GRU, nn.LSTM的参数类似。
初始化常用参数:
- input_size:输入的特征维度,处理文本输入时一般是embedding的维度
- hidden_size:RNN隐藏层维度
- num_layers: 层数;bidirectional: 是否双向
- dropout: dropout rate
forward的输入:
- input: 输入的序列,维度是 (seq_len, batch_size, input_size)
- h_0: 初始化隐藏层状态,维度是 (num_layers * num_directions, batch_size, hidden_size)
forward的输出:
- output: 最后一层所有时间步的输出,维度是 (seq_len, bsz, num_directions * hidden_size)
- h_n: 所有层最后一个时间步的输出,维度是 (num_layers * num_directions, bsz, hidden_size)
分类问题计算accuracy:
根据预测结果列表prediction和label列表y计算:
torch.eq函数比较两个tensor,返回一个bool类型的tensor,相同的地方为True,不同的地方为False;通过float()函数将其转换成0、1的float类型;mean()函数用来求平均值,即accuracy,计算出来的是一个tensor,item()用来取出tensor的数值
acc = torch.eq(prediction, y).float().mean().item()
load mnist dataset in torchvision:
torchvision.transform:
ToTensor()函数:将PIL image或np array转换成FloatTensor并将各个pixel的值缩放到[0, 1]区间
Distributed Training
如果在一个node上跑多个程序,会报错 from TCPStore: RuntimeError: Address already in use,原因是TCP端口冲突了,TCP端口是用于不同node之间通信的。
顾只需要指定一个不同的port即可避免冲突,从而在相同的node上运行多个程序:
>>> python -m torch.distributed.launch --master_port 12345 main.py
函数
torch.diag