实现过程

搭建两层全连接网络

1
2
3
4
5
6
7
8
9
10
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden)
self.predict = torch.nn.Linear(n_hidden, n_output)

def forward(self, x):
x = F.relu(self.hidden(x))
x = self.predict(x)
return x

预测的值画成曲线

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
65
66
67
68
69
# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# @File : 301_regression.py
# @Time :
# @Author :
# @version :python 3.9
# @Software : PyCharm
# @Description:
"""
# ================【功能:】====================
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

# x data (tensor), shape=(100, 1)
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
# noisy y data (tensor), shappe(100, 1)
y = x.pow(2) + 0.2 * torch.rand(x.size())


# torch can only train on Variable, so convert them to Variable


class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden)
self.predict = torch.nn.Linear(n_hidden, n_output)

def forward(self, x):
x = F.relu(self.hidden(x))
x = self.predict(x)
return x


net = Net(n_feature=1, n_hidden=10, n_output=1)
print(net)

optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
# 针对回归的均方误差
loss_func = torch.nn.MSELoss()
plt.ion()

for t in range(200):
prediction = net(x)
loss = loss_func(prediction, y)
# clear gradients for next train
optimizer.zero_grad()
# backpropagation, comupte gradients
loss.backward()
# apply gradients
optimizer.step()

if t % 2 == 0:
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
# 绘制预测的值
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
# plt.pause(0.1)
# plt.ioff()
# 保存为jpg图像
plt.savefig(f'./img/regression_{t}.jpg')
# plt.show()

jgp图像转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
# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# @File : jpg_2_gif.py
# @Time :
# @Author :
# @version :python 3.9
# @Software : PyCharm
# @Description:
"""
# ================【功能:】====================
import os

import imageio


def main():
root_path = '../img'
image_list = os.listdir(root_path)
gif_name = './regression.gif'
# duration between images
duration = 0.1

#### read images and write in gif
images = []
for image_name in image_list:
image_name = os.path.join(root_path, image_name)
images.append(imageio.imread(image_name))
imageio.mimwrite(gif_name, images, 'GIF', duration=duration)

print('success')


if __name__ == "__main__":
main()

结果可视化

image