摸个类中的名称就在def __init__(self)中定义,名字就是self中的定义名称,若在类中还是用了其他的类,那么名称则为实例化的变量名称.其他类中的命名规则
实验代码:
# encoding:utf-8
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import numpy as mp
import matplotlib.pyplot as plt
import torch.nn.functional as F
# define model
class test(nn.Module):
def __init__(self):
super(test, self).__init__()
self.xxxx = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
class TheModelClass(nn.Module):
def __init__(self):
super(TheModelClass, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.test= test()
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def main():
# Initialize model
model = TheModelClass()
# Initialize optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# print model's state_dict
print('Model.state_dict:')
for param_tensor in model.state_dict():
# 打印 key value字典
print(param_tensor, '\t', model.state_dict()[param_tensor].size())
# print optimizer's state_dict
print('Optimizer,s state_dict:')
for var_name in optimizer.state_dict():
print(var_name, '\t', optimizer.state_dict()[var_name])
if __name__ == '__main__':
main()
Model.state_dict:
conv1.weight torch.Size([6, 3, 5, 5])
conv1.bias torch.Size([6])
conv2.weight torch.Size([16, 6, 5, 5])
conv2.bias torch.Size([16])
fc1.weight torch.Size([120, 400])
fc1.bias torch.Size([120])
fc2.weight torch.Size([84, 120])
fc2.bias torch.Size([84])
fc3.weight torch.Size([10, 84])
fc3.bias torch.Size([10])
test.xxxx.weight torch.Size([6, 3, 5, 5])
test.xxxx.bias torch.Size([6])
test.conv2.weight torch.Size([16, 6, 5, 5])
test.conv2.bias torch.Size([16])
Optimizer,s state_dict:
state {}
param_groups [{'lr': 0.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [140443279400536, 140443279400680, 140443279400752, 140443279400824, 140443279400608, 140443279400896, 140443276828744, 140443276828816, 140443276828888, 140443276828960, 140443276829032, 140443276829104, 140443276829176, 140443276829248]}]