最近感觉记性变得有点差,很多方法的使用经常记不住,虽然说现在已经是llm后时代了,但是感觉很多代码如果不是自己写的话会有一种无力感(笑),故在此记录一下pytorch常用的一些方法(其实也包括python方法,笔者的python基础也是一坨。。)
首先就是一些常用的创建张量的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import torch
tensor1=torch.tensor()
torch.arange(begin,end,step)
torch.full(size,fill_value)
torch.zeros(size)
torch.ones(size)
torch.ones_like(input_tensor) torch.zeros_like(input_tensor)
|
当然了,我们在写模型和搭建训练pipeline时不止要创造tensor,还要对其进行各种操作,这里我也会列出自己写模型中遇到的常见操作:
先从各种属性讲起吧
1 2 3 4 5 6
| tensor.device
tensor.dtype
tensor.shape
|
对张量变换的各种方法(大部分都是numpy中已有的方法):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| tensor.to(device or dtype)
tensor.split(split_num,dim=dim)->torch.Tensor ''' args: split_num->分离的数量 dim->拆分的维度 '''
tensor.size(dim)
tensor.transpose(size)
tensor.view(size) tensor.reshape(size)
tensor.unsequeeze(dim)
tensor.sequeeze(dim)
tensor.T
tensor.cat(size,dim,device) tensor.stack(size,dim,device)
|
数学方法:
pytorch中有很多数学函数可以直接使用,与numpy不同的是需要输入张量
1 2 3 4 5 6 7 8 9
| torch.exp() torch.log() torch.sin()
torch.outer(tensor,tensor)
torch.rsqrt(tensor,dim)
|
其余常用方法:
pytorch中还提供了其它用于张量操作的方法:
1 2 3 4 5 6 7 8
| torch.sort(tensor,descending=False,dim)
torch.cumsum(tensor,dim)
torch.multinomial(tensor,num_sample)
torch.gather(index_tensor,dim,index_current)
|
一些python中的记忆点:
1 2 3 4 5 6 7 8
| assert
r""
""" 你好呀 """
|
使用命令行参数的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import argparse
def parse_args(): parser=argparse.ArgumentParser( description="" ) parser.add_argument( "--argument_name" , type=, default=, help="" ) return parser.parse_args()
args=parse_args()
|
正则表达式的一些用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import regex PAT="" pattern=regex.complie(PAT) text="" for match in pattern.finditer(text): str=match.group(0) str=match.group(1)
strs=pattern.findall(text)
pattern.sub(replace_str,text)
pattern.subn(replace_str,text)
|
python中字符串的用法:
1 2 3 4 5 6 7
| split(sub_str) find(sub_str) strip(sub_str) sub_str.join(str_iterator) endswith(substr) isalnum() isalpha()
|
易错点: