【动手学深度学习】

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

相关推荐
for_ever_love__3 小时前
PySpark学习: 数据输出
开发语言·python·学习·spark
张人玉3 小时前
基于 Python 的桌面端智能识别与可视化系统——生活垃圾分类可视化大屏
python·分类·sqlite·echarts·生活
何以解忧,唯有..3 小时前
Python os模块详解:文件与目录操作指南
java·服务器·python
言乐64 小时前
Python实现自动拉人脚本示例
开发语言·windows·python·django·pygame
啊啊啊啊啊!!!!4 小时前
【c++】二叉搜索树
开发语言·c++
归去来 兮4 小时前
Python爬虫爬取数据案例
开发语言·爬虫·python
ShineWinsu4 小时前
对于 C++:C++20中Concept(概念) 与 Coroutine(协程)的解析
linux·开发语言·网络·c++·c++20·epoll
ly76894 小时前
C 语言从入门到进阶:语法、指针、内存管理与工程实践详解
c语言·开发语言
何以解忧,唯有..4 小时前
Python logging 模块:从入门到精通
python·microsoft·php
quantdash_cc4 小时前
历史数据断层与REST请求慢到崩溃?QuantDash高性能量化数据API终极解决方案
开发语言·python·缓存·php·量化·quantdash