神经网络拟合立方函数

0.实验效果

1.实验目的

  • 巩固matplotlib中的动态画图过程

  • 实现用神经网络去拟合一个三次函数

2.运行python文件的时候直接可视化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import torch
from torch import optim
from torch import nn

from matplotlib import pyplot as plt

# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# 准备数据
inputs = torch.unsqueeze(torch.linspace(-4,4, 600),dim=1)
# 添加随机噪声~N(0,1)
targets = inputs.pow(3) + 1.89 + 3 * torch.randn(inputs.shape)

real = inputs.pow(3) + 1.89

# 搭建网络
class NetWork(nn.Module):
def __init__(self,n_feature,n_hidden,n_output):
super(NetWork,self).__init__()
self.m = torch.nn.Sequential(
torch.nn.Linear(n_feature,n_hidden),
torch.nn.ReLU(),
torch.nn.Linear(n_hidden,n_output)
)

def forward(self,x):
return self.m(x)

# 定义网络
network = NetWork(1,100,1)


# 定义损失函数
loss_fn = nn.MSELoss()

# 定义优化器
optimizer = optim.Adam(network.parameters(),lr=0.1)

for i in range(10000):
out = network(inputs)
loss = loss_fn(out,targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 可视化训练结果
if i%2 == 0:
# 清空上一次显示的结果
plt.cla()
# 绘制真实的曲线
plt.plot(inputs.numpy(),real.numpy(),c='blue',lw='3')
# 绘制有误差的散点图
plt.plot(inputs.numpy(),targets.numpy(),c='orange')
# 绘制神经网络实时预测的曲线
plt.plot(inputs.numpy(),out.data.numpy(),c='red',lw='3')
plt.text(1, -6, 'Time=%d Loss=%.4f' % (i, loss.data.numpy()), fontdict={'size': 15, 'color': 'red'})
plt.pause(0.1)

3.运行python文件后保存为gif图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import torch
from torch import optim
from torch import nn

from matplotlib import pyplot as plt
from matplotlib.animation import ArtistAnimation

# device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# 准备数据
inputs = torch.unsqueeze(torch.linspace(-4,4, 600),dim=1)
# 添加随机噪声~N(0,1)
targets = inputs.pow(3) + 1.89 + 3 * torch.randn(inputs.shape)

real = inputs.pow(3) + 1.89

# 搭建网络
class NetWork(nn.Module):
def __init__(self,n_feature,n_hidden,n_output):
super(NetWork,self).__init__()
self.m = torch.nn.Sequential(
torch.nn.Linear(n_feature,n_hidden),
torch.nn.ReLU(),
torch.nn.Linear(n_hidden,n_output)
)

def forward(self,x):
return self.m(x)



# 定义网络
network = NetWork(1,100,1)

# 定义损失函数
loss_fn = nn.MSELoss()

# 定义优化器
optimizer = optim.Adam(network.parameters(),lr=0.1)

fig, ax = plt.subplots()

ims = []

for i in range(200):
out = network(inputs)
loss = loss_fn(out,targets)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 可视化训练结果
if i%2 == 0:
# 绘制真实的曲线
frame0, = plt.plot(inputs.numpy(),real.numpy(),c='blue',lw='3')
# 绘制有误差的散点图
frame1, = plt.plot(inputs.numpy(),targets.numpy(),c='orange')
# 绘制神经网络实时预测的曲线
frame2, = plt.plot(inputs.numpy(),out.data.numpy(),c='red',lw='3')
frame3 = plt.text(1, -6, 'Time=%d Loss=%.4f' % (i, loss.data.numpy()), fontdict={'size': 15, 'color': 'red'})
ims.append([frame0,frame1,frame2,frame3])

ani = ArtistAnimation(fig, ims, interval=100, blit=False,
repeat_delay=1000)
ani.save('x_3.gif')
文章作者: 小王同学
文章链接: https://morvan.top/2021/09/01/神经网络拟合立方函数可视化/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小王同学的精神驿站