常见代码记录-python

记录 Python 中一些常见的代码。

该博文会一直持续更新。

常见简易问题

装饰器:

装饰器就是一个闭包,装饰器是闭包的一种应用。装饰器用于拓展原来函数功能的一种函数,其特殊之处在于它的返回值也是一个函数,可以在不用更改原函数的代码前提下给函数增加新的功能。

https://www.runoob.com/w3cnote/python-func-decorators.html

输入输出问题

内置函数

zip

用于将多个可迭代对象(例如列表、元组等)中对应位置的元素打包成元组,并返回一个迭代器。

如:[1, 3, 5, 7] 和 [2, 4, 6, 8] 被 zip 处理后得到:(1, 2), (3, 4), (5, 6), (7, 8)

torch(Pytorch)

1
import torch.nn as nn

Torch:张量,即向量,是Pytorch中进行运算的基本单位

torch.cat:连接两个张量

init(self)

这个函数用于初始化这个类,在创建类的实例的时候自动执行。必须包含self.

super(A, self).init()

该函数会首先找到 A 的父类(比如是类 B ),然后把 self 转换为类 B 的对象,对象转换成 B 类后调用自己的init函数,其实简单理解就是子类把父类的__init__()放到自己的__init__()当中,这样子类就有了父类的__init__()的那些东西。

这个是必须的,如果没有父类,那么 A 我们赋该对象本身所属的类即可。

torch.manual_seed(opt.seed):

设置CPU生成随机数的种子,方便下次复现实验结果。

torchvision

一般是用来导入文件夹中文件

Conv2d

参数:

in_channels:输入张量的channels数。

out_channels:期望的四维输出张量的channels数。

kernel_size:卷积核的大小,一般我们会使用5x5、3x3这种左右两个数相同的卷积核

stride:步长

padding = 0,是否填充(与Tensorflow不同)

dilation = 1:是否采用空洞卷积,默认为1,即不采用,采用空洞卷积增加感受野

groups = 1:是否采用分组卷积

rearrange

softmax

dim = 0 : 按列

dim = 1 : 按行

einsum

numpy 中一种优雅的矩阵矩阵计算方法,有些复杂。

具体参见这两篇文章:https://zhuanlan.zhihu.com/p/506843213

https://zhuanlan.zhihu.com/p/361209187

cumprod

在指定维度上进行累积维度运算。

functools

partial

偏函数(partial function),用于固定一个函数的一部分参数,从而生成一个新的函数的过程。

1
2
3
4
5
6
import functools

def sum(x,y,name = "a"):
return (name,x+y);
sumY = functools.partial(sum,6,name="b")
print(sumY(7))//('b',13)

model

model.eval():在模型中加上Dropout层和batch normalization层,在模型预测阶段将这些层设置到预测模式。

argparse 模块:

是 Python 内置的一个用于命令项选项与参数解析的模块,argparse 模块可以让人轻松编写用户友好的命令行接口。通过在程序中定义好我们需要的参数,然后 argparse 将会从 sys.argv 解析出这些参数。

语法格式:

1
2
3
4
5
6
7
8
9
10
11
parser = argparse.ArgumentParser(description='Process and align face forensics frames')
# 先创建一个解析器对象
parser.add_argument('--source_dir_manipulated', required=True, help='source videos directory, e.g. manipulated_sequences/Deepfakes/c23/frames')
parser.add_argument('--source_dir_original', required=True, help='original videos directory, e.g. original_sequences/youtube/c23/frames')
parser.add_argument('--outsize', type=int, default=128, help='resize to this size')
parser.add_argument('--output_dir', required=True, help='output directory')
parser.add_argument('--split', default='val.json', help='Path to split json file')
# 参数从前到后含义:选项名字、type参数类型、default无参数时默认值、required可选参数是否可省略、help写明解析器作用。

args = parser.parse_args()
# 通过parse_args(),把参数转换为适当的类型,然后调用相应的操作

os模块:

os.mkdir()

就是创建相应的目录

os.getcwd()

获取当前文件夹的路径

os.path.join()

用于拼接文件路径

io.imread()

用于读取图片文件。读取的图片为GRB格式

logging模块:

日志模块,使我们可以实时监测程序运行的状态。

time模块:

时间模块,提供各种与时间相关的函数。

time time(): 返回当前时间的时间戳

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信