模型: 1)conv1 = nn.Conv2d(in_ch,out_ch,kernel_size,stride,padding) 2) 继承nn.Module类 (nn.Sequence) 3)继承nn.Module类 (手写) Tensor 1) conv1(input) 2) DoubleConv(input) Tensor没有state_dict()方法,模型有state_dict()方法,可以查看变量
#%%
import torch
import torch.nn as nn
#%% md
#%% 单层网络模型
input = torch.arange(16,dtype=torch.float32).view([1,1,4,4])
model = nn.Conv2d(1,1,kernel_size=3,stride=1,padding=0)
print(model.state_dict())
modeldict = model.state_dict()
print(modeldict['weight'])
print(modeldict['bias'])
#%% 多层网络模型(nn.Sequence)
class DoubleConv(nn.Module):
def __init__(self, in_ch, out_ch):
super(DoubleConv, self).__init__()
self.conv = nn.Sequential( #图像大小不变
nn.Conv2d(in_ch, out_ch, 3, padding=1), #in_ch * w * h * t -> out_ch * w * h * t
nn.Conv2d(out_ch, out_ch, 3, padding=1),
)
def forward(self, input):
return self.conv(input)
#模型
model1 = DoubleConv(2,2)
print(model1.state_dict())
#%% 多层网络模型(手动)
class DoubleConv1(nn.Module):
def __init__(self, in_ch, out_ch):
super(DoubleConv1, self).__init__()
#图像大小不变
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1) #in_ch * w * h * t -> out_ch * w * h * t #in_ch * w * h * t -> out_ch * w * h * t #in_ch * w * h * t -> out_ch * w * h * t
self.conv2 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
def forward(self, x):
c1=self.conv1(x) #自动调用DoubleConv类中的forward函数
c2=self.conv2(c1)
return c2
#模型
model2 = DoubleConv1(2,2)
print(model2.state_dict())
权值的输出我就不写了,运行代码即可