默写创建简单网络
x=torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
y=x.pow(2)+0.2*torch.rand(x.size()) #数据准备
class Net(torch.nn.moudule)
def __init(self,n_features,hiddens,n_output)
super(self,Net)__init()
self.Fc1=torch.nn.linear(n_features,hiddens)
self.relu=torch.nn.Relu()
self.Fc2=torch.nn.linear(hiddens,n_output)
def forward(self,x)
out=self.Fc1(x)
out=self.relu(out)
out=self.Fc2(x)
return out
net=Net(1,10.1)
optimizer=torch.optim.SGD(net.parameters(),lr=0.01)
loss_func=torch.nn.MSEloss()
#训练部分
for t in range(100):
prediction=net(x)
loss=loss_func(prediction,y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
torch.save(net1,'net.pkl')
torch.save(net1.state_dict(),'net_params.pkl')#保存训练的网络参数
def restore_net():
net2=torch.load('net.pkl')
out=net2(x)
prediction = torch.max(F.softmax(out),1)[1]#使用模型
def restore_params():
net3=torch.nn.Sequential(
torch.nn.Linear(1, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 1)
)
net3.load_state_dict(torch.load('net_params.pkl'))#使用模型
out = net3(x)
prediction = torch.max(F.softmax(out), 1)[1]