python 学习笔记(update中)
1. argparse
使用方式
import argparse
# 设置说明
parser = argparse.ArgumentParser(description='Train networks')
# 添加参数
parser.add_argument('--train.epochs', type=int, default=100, metavar='NEPOCHS', help='number of epochs to train (default: 100)')
# 激活parser,并利用vars将其化为dict形式,方便后续args直接当作参数调用
args = vars(parser.parse_args())
argparse常用符号
- type:类型,默认string
- default:默认值
- help:帮助信息
- metavar:参数调用别名
- action:指示optparser解析参数时候该如何处理。默认是’store’,表示将命令行参数值保存options
2. 文件夹/文件操作
- 判断文件夹是否存在:
os.path.isdir(path)
- 创建文件夹:
os.makedirs(path)
- 打开文件:
# with as相当于try finally
# 用with打开文件代码更简洁,会自动执行关闭文件操作
with open(path,打开方式) as f:
f操作文件
- 打开文件方式:
w: 写
a: 追加
r: 只读
w+: 读写
wb:写二进制
rb:读二进制
3. torch常用函数
1. cat函数
cat((tensor1,tensor2,...),dim) # 待合并的tensor,在哪个维度上合并
dim=0:竖着合并,其他维度不变,行数加和
dim=1:横着合并,列数加和
2. repeat函数
output.repeat(x,y,z,...) # 对output做维度处理(repeat的参数数量不能少于output的维数
# 示例:
#output初始维数:[2,3,4]
output = output.repeat(1,2,1,1)
#output维度变为:[1,4,3,4]
3. unsqueeze和sequeeze函数
unsqueeze(a,axis=0,1...) # 增加一个维度,维数为1,axis索引从0开始
squeeze(a,axis=none,0,1...) # 去掉一个维度,维数为1,axis索引从0开始
#squeeze不指定axis时,会去掉**所有维数为1**的维度
4. torch.tensor.scatter_函数
根据数据和索引,来更新数组
较为复杂,参考:pytorch中torch.Tensor.scatter用法
# 参数设置
scatter_(dim, index, src)
# dim:待处理的维度
# index:数组,要把原数组src中的数据分配到output数组中的位置
# src:用于更新output的数据
5. gather函数
官方文档解释:
torch.gather(input, dim, index, out=None) → Tensor Gathers values along an axis specified by dim. For a 3-D tensor the output is specified by: out[i][j][k] = input[index[i][j][k]][j][k] # dim=0 out[i][j][k] = input[i][index[i][j][k]][k] # dim=1 out[i][j][k] = input[i][j][index[i][j][k]] # dim=2 Parameters: input (Tensor) – The source tensor dim (int) – The axis along which to index index (LongTensor) – The indices of elements to gather out (Tensor, optional) – Destination tensor Example: >>> t = torch.Tensor([[1,2],[3,4]]) >>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]])) 1 1 4 3 [torch.FloatTensor of size 2x2]
可以看出,gather的作用是这样的,index实际上是索引,具体是行还是列的索引要看前面dim 的指定。
比如对于例子:【1,2,3; 4,5,6,】。
指定dim=1,也就是横向,那么索引就是列号。index的大小就是输出的大小,所以比如index是【1,0; 0,0】,那么看index第一行,1列指的是2, 0列指的是1,同理,第二行为4,4 。这样就输入为【2,1;4,4】,参考这样的解释看上面的输出结果,即可理解gather的含义。
gather用途:在one-hot为输出的多分类问题中,可以把最大值坐标作为index传进去,以此提取到每一行的正确预测结果。
4. torchversion包
1.torchversion.transforms
提供一般的图像转换函数