PyTorch:一篇使用技巧汇总

简介: 一些常用的基础操作

设定 tensor 默认的 dtype:torch.set_default_tensor_type(torch.DoubleTensor)

Pytorch 有八个类型:

Daya type dtype Tensor types
32-bit 浮点 torch.float32 or torch.float torch.*.FloatTensor
64-bit 浮点 torch.float64 or torch.double torch.*.DoubleTensor
16-bit 浮点 torch.float16 or torch.half torch.*.HalfTensor
8-bit 整型(无符号) torch.uint8 torch.*.ByteTensor
8-bit 整型(有符号) torch.int8 torch.*.CharTensor
16-bit 整型(有符号) torch.int16 or torch.short torch.*.ShortTensor
32-bit 整型(有符号) torch.int32 or torch.int torch.*.IntTensor
64-bit 整型(有符号) torch.int64 or torch.long torch.*.LongTensor

保存模型:

def save_checkpoint(model, optimizer, scheduler, save_path):
    # 如果还有其它变量想要保存,也可以添加
    torch.save({
        'model_state_dict': model.state_dict(),
        'optimizer_state_dict': optimizer.state_dict(),
        'scheduler_state_dict': scheduler.state_dict(),
    }, save_path)

# 加载模型
checkpoint = torch.load(pretrain_model_path)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
...

打印模型的梯度:

# 打印梯度
for name, parameters in model.named_parameters():
    print('{}\'s grad is:\n{}\n'.format(name, parameters.grad))

使用梯度衰减策略:

# 指数衰减
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=0.9)
# 阶梯衰减
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=200, gamma=0.5)
# 自定义间隔衰减
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[400], gamma=0.5)

梯度截断:

def clip_gradient(optimizer, grad_clip):
    """
    Clips gradients computed during backpropagation to avoid explosion of gradients.

    :param optimizer: optimizer with the gradients to be clipped
    :param grad_clip: clip value
    """
    for group in optimizer.param_groups:
        for param in group["params"]:
            if param.grad is not None:
                param.grad.data.clamp_(-grad_clip, grad_clip)

自定义激活函数示例:

class OutExp(nn.Module):
    def __init__(self):
        super(OutExp, self).__init__()

    def forward(self, x):
        x = -torch.exp(x)
        return x

修改模型某一层参数:nn.Parameter():

# 修改第 2 层的 bias(`layer` 是模型定义时给的名称)
model.layer[2].bias = nn.Parameter(torch.tensor([-0.01, -0.4], device=device, requires_grad=True))

模型参数初始化:

# 自定义权重初始化
def weight_init(m):
    if isinstance(m, nn.Linear):
        nn.init.xavier_uniform_(m.weight, gain=0.1)
        nn.init.constant_(m.bias, 0)
    # 也可以判断是否为 conv2d,使用相应的初始化方式
    elif isinstance(m, nn.Conv2d):
        nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
    # 是否为批归一化层
    elif isinstance(m, nn.BatchNorm2d):
        nn.init.constant_(m.weight, 1)
        nn.init.constant_(m.bias, 0)

# 模型应用函数
model.apply(weight_init)
目录
相关文章
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8082 2
|
11天前
|
域名解析 人工智能 Linux
|
20天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10347 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1564 5
|
9天前
|
云安全 数据采集 人工智能
|
17天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2709 8
|
9天前
|
Web App开发 缓存 安全
巨魔商店 TrollStore 安装教程(2026):免电脑在线安装与全机型安装器矩阵_iOS巨魔安装
巨魔商店(TrollStore)是iOS 14–17.0(特定版本)的永久签名工具,无需越狱,利用CoreTrust漏洞实现IPA签名长期有效,彻底告别7天重签。支持免电脑在线安装(TrollHelperOTA),适配多机型/系统组合,开源免费,安全可控。(239字)
2467 0