python打卡day36@浙大疏锦行
1.信贷项目神经网络改进
# ... 原有导入 ...
import torch.nn as nn
import torch.nn.functional as Fclass CreditRiskModel(nn.Module):def __init__(self, input_size):super().__init__()self.fc1 = nn.Linear(input_size, 64)self.bn1 = nn.BatchNorm1d(64)self.fc2 = nn.Linear(64, 32)self.dropout = nn.Dropout(0.2)self.output = nn.Linear(32, 1)def forward(self, x):x = F.relu(self.bn1(self.fc1(x)))x = self.dropout(x)x = F.relu(self.fc2(x))return torch.sigmoid(self.output(x))
# ... 原有训练代码 ...
2. 美观化改进:
- 使用PyTorch Lightning框架简化训练流程
- 添加类型提示(Type Hints)
- 实现配置化参数管理
nn.Module探索建议
要探索nn.Module的方法,可以通过以下方式:
1.查看所有方法:
import torch.nn as nn
print(dir(nn.Module))
2.关键方法说明:
- parameters() : 返回模型所有参数
- state_dict() : 获取模型状态字典
- train() / eval() : 设置训练/评估模式
- to(device) : 移动模型到指定设备
3.查看源码:
python -c "import torch; print(torch.nn.Module.__module__)"
然后可以在IDE中跳转到源码查看实现细节。