python - 如何在 Pytorch 的 CNN 中访问卷积层的权重和 L2 范数?
问题描述
是否有 PyTorch 功能可以访问这些功能?
解决方案
您可以使用
torch.div(model[i].weight, torch.norm(model[i].weight), out=model[i].weight)
玩具示例(内联记录)。
import torch
from torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential, Conv2d, MaxPool2d, Module, Softmax, BatchNorm2d, Dropout
from torch.optim import Adam
# Define model
model = Sequential(
Conv2d(1, 4, kernel_size=3, stride=1, padding=1),
BatchNorm2d(4),
ReLU(inplace=True),
MaxPool2d(kernel_size=2, stride=2),
# Defining another 2D convolution layer
Conv2d(4, 4, kernel_size=3, stride=1, padding=1),
BatchNorm2d(4),
ReLU(inplace=True),
MaxPool2d(kernel_size=2, stride=2),
)
optimizer = Adam(model.parameters(), lr=0.07)
criterion = CrossEntropyLoss()
# Train loop
for epoch in range(10):
optimizer.zero_grad()
# Forward
# y_hat = model(X_train)
# loss = criterion(y_train, y_hat)
# Backward
# loss.backward()
# optimizer.step()
# Now maunually update the weights
for i in range(len(model)):
with torch.no_grad():
if hasattr(model[i], 'weight'):
torch.div(model[i].weight, torch.norm(model[i].weight), out=model[i].weight)
推荐阅读
- python - 在运行时重写配置文件
- one-to-many - 微风查询:比较相关实体上的两列
- javascript - 如何使用重组获得反应参考?
- python - Python行没有运行
- java - 从 Spring Boot 1.5-2、Spring Security 4-5 升级到 Spring Security 后,Spring Security 不再重定向到登录页面
- android - 安卓。正在安装 apk 吗?
- java - Java Hibernate 对象在一段时间后失去其价值
- ms-access - MS Access,我的任务是重写 MS Access 应用程序
- c# - 我可以从我的网站启动 IRC Bot(Twitch 聊天机器人)的实例吗?寻找更容易的答案
- php - 从 SQL 结果集中创建一个更复杂的 json 对象