【动手学深度学习】

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 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽4 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程9 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪9 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook9 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python