【动手学深度学习】

python 复制代码
def my_init(m):
    if type(m) == nn.Linear:
        print("Init", *[(name, param.shape)
                        for name, param in m.named_parameters()][0])
        nn.init.uniform_(m.weight, -10, 10)
        m.weight.data *= m.weight.data.abs() >= 5

代码中这里的[0]列表索引 ,表示取列表中的第一个元素

先分解这段代码:

python 复制代码
[(name, param.shape) for name, param in m.named_parameters()][0]

代码分解:

  1. m.named_parameters() - 返回模块的所有参数(权重和偏置)及其名称

    • 对于 nn.Linear 层,通常返回两个参数:weightbias
  2. 列表推导式

python 复制代码
[(name, param.shape) for name, param in m.named_parameters()]

这会生成一个列表,例如:

python 复制代码
[('weight', torch.Size([out_features, in_features])), 
 ('bias', torch.Size([out_features]))]

3. [0] - 取列表中的第一(首)个元素:

python 复制代码
('weight', torch.Size([out_features, in_features]))
  1. *解包 - 将元组解包为单独的参数:
python 复制代码
print("Init", *('weight', torch.Size([out_features, in_features])))
# 等价于:
print("Init", 'weight', torch.Size([out_features, in_features]))

输出示例:

python 复制代码
# 假设有一个 nn.Linear(10, 5) 层
Init weight torch.Size([5, 10])

为什么只取第一个?

因为对于 nn.Linear 层,通常只需要关注权重(weight)的初始化,偏置(bias)可以使用默认初始化或单独处理。

如果你想看到所有参数,可以去掉 [0]

python 复制代码
print("Init", *[(name, param.shape) for name, param in m.named_parameters()])
# 输出:Init weight torch.Size([5, 10]) bias torch.Size([5])

[0]在这里的作用就是只选择第一(首个)个参数(权重)进行打印和初始化

相关推荐
biter down3 小时前
14:pytest-order 插件 顺序控制案例
开发语言·python·pytest
郝学胜-神的一滴3 小时前
Qt 高级开发 009: C++ Lambda 表达式
开发语言·c++·qt·软件构建
测试开发-学习笔记3 小时前
从0开始搭建自动化(一)-appium+python
python·自动化
㳺三才人子3 小时前
初探 Flask
后端·python·flask·html
星栈独行3 小时前
我在 Rust 全栈项目里用 JWT 做无状态认证
开发语言·后端·rust·前端框架·开源·github·web
石山代码4 小时前
C++ 轻量级日志系统
开发语言·c++
AI算法沐枫4 小时前
机器学习到底是什么?
人工智能·python·深度学习·机器学习·数据挖掘·大模型·#ai
小技与小术4 小时前
玩转Flask
开发语言·python·flask
SilentSamsara4 小时前
Python 性能优化:tracemalloc、profiling 与 C 扩展加速
开发语言·python·青少年编程·性能优化
冰小忆4 小时前
大驼峰命名规范和小驼峰命名规范的区别是什么?
开发语言·python