【动手学深度学习】

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]在这里的作用就是只选择第一(首个)个参数(权重)进行打印和初始化

相关推荐
威风的虫2 小时前
ES6 数组方法:告别循环,拥抱函数式编程
开发语言·前端·javascript
码界筑梦坊2 小时前
240-基于Python的医疗疾病数据可视化分析系统
开发语言·python·信息可视化·数据分析·毕业设计·echarts
2301_803554522 小时前
C++ 锁类型大全详解
开发语言·c++
wuwu_q2 小时前
用通俗易懂方式,详细讲讲 Kotlin Flow 中的 map 操作符
android·开发语言·kotlin
曼巴UE52 小时前
UE5 C++ Slate 画曲线
开发语言·c++·ue5
向葭奔赴♡2 小时前
Spring IOC/DI 与 MVC 从入门到实战
java·开发语言
minji...2 小时前
C++ 面向对象三大特性之一---多态
开发语言·c++