Docsity

manifold with differential area, Summaries of Geometry

Toggle sidebar
bg1
神经⽹络学习(⼀):拟合简单函数
前⾔前⾔
学习⽤神经⽹络做点数学上的研究,刚开始摸索,记录⼀下过程。
今天是⽤深度学习(Deep Learning)来拟合⼀些函数(因为多项式的拟合⽐较简单,直接学习参数就可以了所以就没有必要放出来了),
准备设计⼀个简单神经⽹络来拟合函数
训练流程训练流程
1.定义⽹络定义⽹络
选择⾃定义⼀个简单神经⽹络,⼤部分都直接继承⽗类就⾏了,其中fc1是输⼊数据映射到神经⽹络隐藏层,fc2是隐藏层给出到输出
层的数据。
前向传播中我加⼊了激活函数act,⽬的是为了更好地映射(
其实是实验发现不加误差就是nan
),经过试验发现使⽤tanh()的效果
是最好的,其他可参考的激活函数有Sigmoid(),Relu()两种。
class Net(nn. Module):
def __ init__(self):
supe r(Net, self) .__init__()
self.fc1 = nn.Linear(1,64)
self.fc2 = nn.Linear(64,1)
def for ward(self, x):
o = self.fc1(x)
o = self.act(o)
out = self.fc2(o)
return out
def act (self, x):
ret urn torch .tanh(x)
2. 定义损失定义损失
损失可以⾃⼰写,也可以调⽤现有的损失函数计算⽅法,下⾯使⽤的就是2-范数来计算损失
loss_fn = nn. MSELoss(redu ction='mean ')
3.选择优化器选择优化器
optimizer = optim.SGD(net .parame ters(),lr = lr)
4.训练训练&可视化(可视化(main))
为了能够更好地看⽹络学的咋样了,我在循环⾥加⼊了图像显⽰
pf3
pf4

Partial preview of the text

Download manifold with differential area and more Summaries Geometry in PDF only on Docsity!

今天是⽤深度学习(Deep Learning)来拟合⼀些函数(因为多项式的拟合⽐较简单,直接学习参数就可以了所以就没有必要放出来了),

选择⾃定义⼀个简单神经⽹络,⼤部分都直接继承⽗类就⾏了,其中fc1是输⼊数据映射到神经⽹络隐藏层,fc2是隐藏层给出到输出

前向传播中我加⼊了激活函数act,⽬的是为了更好地映射( 其实是实验发现不加误差就是nan),经过试验发现使⽤tanh()的效果

是最好的,其他可参考的激活函数有Sigmoid(),Relu()两种。

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)

4. 训练训练 & 可视化(可视化( main ))

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() 训练结果 训练结果

可以看到训练过程是⼀步⼀步在爬升,这应该是SGD的原因(我记得我试了其他优化器,效果不咋地就换回来了)

神经⽹络拟合函数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()