


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



class Net(nn.Module): def init(self): super(Net, self).init() self.fc1 = nn.Linear(1,64) self.fc2 = nn.Linear(64,1) def forward(self, x): o = self.fc1(x) o = self.act(o) out = self.fc2(o) return out def act(self, x): return torch.tanh(x)
loss_fn = nn.MSELoss(reduction='mean')
optimizer = optim.SGD(net.parameters(),lr= lr)
if name == "main": x = torch.linspace(0, 10, 2000) x_T = x.view(2000, 1) y = torch.exp(x) y_T = y.view(2000, 1) net = Net() lr = 1e- loss_fn = nn.MSELoss() optimizer = optim.SGD(net.parameters(),lr= lr)
plt.ion() for i in range(10 ** 5): optimizer.zero_grad() y_train = net(x_T) loss = loss_fn(y_train,y_T) if i % 10000 == 0: plt.cla() plt.scatter(x.detach().numpy(),y.detach().numpy()) plt.plot(x.detach().numpy(), y_train.detach().numpy(), c='red',lw=5) plt.text(0.5, 0, 'Loss=%.4f' % loss.item(), fontdict={'size': 20, 'color': 'red'}) print(f'times {i} - lr {lr} - loss: {loss.item()}') plt.pause(0.1) loss.backward() optimizer.step() plt.ioff() plt.show() y2 = net(x_T) plt.plot(x.detach().numpy(), y.detach().numpy(), c='red', label='True') plt.plot(x.detach().numpy(), y2.detach().numpy(), c='blue', label='Pred') plt.legend(loc='best') plt.show() 训练结果 训练结果
神经⽹络拟合函数exp(x) """ import torch import torch.nn as nn import numpy as np import matplotlib.pyplot as plt import torch.optim as optim class Net(nn.Module): def init(self): super(Net, self).init() self.fc1 = nn.Linear(1,64) self.fc2 = nn.Linear(64,1) def forward(self, x): o = self.fc1(x) o = self.act(o) out = self.fc2(o) return out def act(self, x): return torch.tanh(x) if name == "main": x = torch.linspace(0, 10, 2000) x_T = x.view(2000, 1) y = torch.exp(x) y_T = y.view(2000, 1) net = Net() lr = 1e- loss_fn = nn.MSELoss() optimizer = optim.SGD(net.parameters(),lr= lr)
plt.ion() for i in range(10 ** 5): optimizer.zero_grad() y_train = net(x_T) loss = loss_fn(y_train,y_T) if i % 10000 == 0: plt.cla() plt.scatter(x.detach().numpy(),y.detach().numpy()) plt.plot(x.detach().numpy(), y_train.detach().numpy(), c='red',lw=5) plt.text(0.5, 0, 'Loss=%.4f' % loss.item(), fontdict={'size': 20, 'color': 'red'}) print(f'times {i} - lr {lr} - loss: {loss.item()}') plt.pause(0.1) loss.backward() optimizer.step() plt.ioff() plt.show() y2 = net(x_T) plt.plot(x.detach().numpy(), y.detach().numpy(), c='red', label='True') plt.plot(x.detach().numpy(), y2.detach().numpy(), c='blue', label='Pred') plt.legend(loc='best') plt.show()