-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinear_Regression.py
133 lines (110 loc) · 3.52 KB
/
Linear_Regression.py
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import torch
import matplotlib.pyplot as plt
# 创建数据集
def create_linear_data(nums_data, if_plot=False):
"""
Create data for linear model
Args:
nums_data: how many data points that wanted
Returns:
x with shape (nums_data, 1)
"""
x = torch.linspace(0, 1, nums_data)
x = torch.unsqueeze(x, dim=1)
k = 2
y = k * x + torch.rand(x.size())
if if_plot:
plt.scatter(x.numpy(), y.numpy(), c=x.numpy())
plt.show()
data = {"x": x, "y": y}
return data
data = create_linear_data(300, if_plot=True)
print(data["x"].size())
class LinearRegression(torch.nn.Module):
"""
Linear Regressoin Module, the input features and output
features are defaults both 1
"""
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
out = self.linear(x)
return out
if torch.cuda.is_available():
model = LinearRegression().cuda()
else:
model = LinearRegression()
linear = LinearRegression()
print(linear)
class Linear_Model():
def __init__(self):
"""
Initialize the Linear Model
"""
self.learning_rate = 0.001
self.epoches = 100 # 默认是10000
self.loss_function = torch.nn.MSELoss()
self.create_model()
def create_model(self):
self.model = LinearRegression()
self.optimizer = torch.optim.SGD(self.model.parameters(), lr=self.learning_rate)
def train(self, data, model_save_path="model.pth"):
"""
Train the model and save the parameters
Args:
model_save_path: saved name of model
data: (x, y) = data, and y = kx + b
Returns:
None
"""
x = data["x"]
y = data["y"]
for epoch in range(self.epoches):
prediction = self.model(x)
loss = self.loss_function(prediction, y)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
if epoch % 500 == 0:
print("epoch: {}, loss is: {}".format(epoch, loss.item()))
torch.save(self.model.state_dict(), "linear.pth")
def test(self, x, model_path="linear.pth"):
"""
Reload and test the model, plot the prediction
Args:
model_path: the model's path and name
data: (x, y) = data, and y = kx + b
Returns:
None
"""
x = data["x"]
y = data["y"]
self.model.load_state_dict(torch.load(model_path))
prediction = self.model(x)
plt.scatter(x.numpy(), y.numpy(), c=x.numpy())
plt.plot(x.numpy(), prediction.detach().numpy(), color="r")
plt.show()
def compare_epoches(self, data):
x = data["x"]
y = data["y"]
num_pictures = 16
fig = plt.figure(figsize=(10, 10))
current_fig = 0
for epoch in range(self.epoches):
prediction = self.model(x)
loss = self.loss_function(prediction, y)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
if epoch % (self.epoches / num_pictures) == 0:
current_fig += 1
plt.subplot(4, 4, current_fig)
plt.scatter(x.numpy(), y.numpy(), c=x.numpy())
plt.plot(x.numpy(), prediction.detach().numpy(), color="r")
plt.show()
linear = Linear_Model()
data = create_linear_data(100)
linear.train(data)
# linear.test(data)
linear.compare_epoches(data)