import torch.nn as nn
import torch
import torch.nn.functional as F
#定义网络模块 主要包括初始化、前向传播、数据维度处理
class Net(nn.Module):
#初始化
def __init__(self,channel,kernel_count,kenel_size):
super(Net,self).__init__()
#卷积层
self.conv1=nn.Conv2d(1,6,5)
self.conv2=nn.Conv2d(6,16,5)
#全连接层
self.f1=nn.Linear(5*16*5,128)
self.f2=nn.Linear(128,64)
self.f3=nn.Linear(64,10)
#前向传播层
def forward(self,x):
x=F.max_pool2d(F.relu(self.conv1(x)),(2,2))#卷积 激活 池化
x=F.max_pool2d(F.relu(self.conv2(x)),(2,2))
x=x.view(1,-1)#数据维度转换
x=F.relu(self.f1(x))
x=F.relu(self.f2(x))
x=self.f3(x)
return x
#转换数据维度
def num_reshapes(self,x):
size=x.size()[1:]
num_sizes=1
for i in size:
num_sizes*=i
return num_sizes
#实例化网络模型
net=Net(1,6,5)
#输入数据
inputs=torch.randn(1,1,32,32)
#输出
out=net(inputs)
#目标值(确保输出和目标数据的维度一致 如果不一致,要进行维度的转化)
target=torch.randn(1,10)
#定义损失函数
loss_function=nn.MSELoss()
#定义优化器
optimizer=torch.optim.SGD(net.parameters(),lr=0.1)
#列表存储loss值
loss_list=[]
#训练
for i in range(20):
out=net(inputs)#输出
loss=loss_function(out,target)#计算loss
loss_list.append(loss)#存储loss用于后续画loss曲线
print(loss)
optimizer.zero_grad()#梯度清零 防止梯度叠加
loss.backward()#反向传播
optimizer.step()#更新到每一个参数
#画loss曲线
import matplotlib.pyplot as plt
epochs=[i for i in range(21)]
plt.plot(range(9),loss_list[:9],"red")
plt.xlabel("epoch")
plt.ylabel("loss")
plt.show()