Skip to content

Commit d59ae9f

Browse files
committed
update
1 parent 148c4b7 commit d59ae9f

File tree

2 files changed

+175
-0
lines changed

2 files changed

+175
-0
lines changed

cahpter3_MLP/linear_model.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
__author__ = 'SherlockLiao'
2+
3+
import torch
4+
from torch import nn, optim
5+
from torch.autograd import Variable
6+
import numpy as np
7+
import matplotlib.pyplot as plt
8+
9+
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
10+
[9.779], [6.182], [7.59], [2.167], [7.042],
11+
[10.791], [5.313], [7.997], [3.1]], dtype=np.float32)
12+
13+
y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
14+
[3.366], [2.596], [2.53], [1.221], [2.827],
15+
[3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
16+
17+
18+
x_train = torch.from_numpy(x_train)
19+
20+
y_train = torch.from_numpy(y_train)
21+
22+
23+
# Linear Regression Model
24+
class LinearRegression(nn.Module):
25+
def __init__(self):
26+
super(LinearRegression, self).__init__()
27+
self.linear = nn.Linear(1, 1) # input and output is 1 dimension
28+
29+
def forward(self, x):
30+
out = self.linear(x)
31+
return out
32+
33+
34+
if torch.cuda.is_available():
35+
model = LinearRegression().cuda()
36+
else:
37+
model = LinearRegression()
38+
# 定义loss和优化函数
39+
criterion = nn.MSELoss()
40+
optimizer = optim.SGD(model.parameters(), lr=1e-4)
41+
42+
# 开始训练
43+
num_epochs = 1000
44+
for epoch in range(num_epochs):
45+
if torch.cuda.is_available():
46+
inputs = Variable(x_train).cuda()
47+
target = Variable(y_train).cuda()
48+
else:
49+
inputs = Variable(x_train)
50+
target = Variable(y_train)
51+
52+
# forward
53+
out = model(inputs)
54+
loss = criterion(out, target)
55+
# backward
56+
optimizer.zero_grad()
57+
loss.backward()
58+
optimizer.step()
59+
60+
if (epoch+1) % 20 == 0:
61+
print('Epoch[{}/{}], loss: {:.6f}'
62+
.format(epoch+1, num_epochs, loss.data[0]))
63+
64+
model.eval()
65+
predict = model(Variable(x_train))
66+
predict = predict.data.numpy()
67+
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label='Original data')
68+
plt.plot(x_train.numpy(), predict, label='Fitting Line')
69+
plt.show()
70+
71+
# 保存模型
72+
torch.save(model.state_dict(), './linear.pth')

cahpter3_MLP/poly_model.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
__author__ = 'SherlockLiao'
2+
3+
import torch
4+
from torch import nn, optim
5+
from torch.autograd import Variable
6+
import numpy as np
7+
import matplotlib.pyplot as plt
8+
9+
W_target = torch.FloatTensor([0.5, 3, 2.4]).unsqueeze(1)
10+
b_target = torch.FloatTensor([0.9])
11+
12+
13+
def make_features(x):
14+
"""Builds features i.e. a matrix with columns [x, x^2, x^3]."""
15+
x = x.unsqueeze(1)
16+
return torch.cat([x ** i for i in range(1, 4)], 1)
17+
18+
19+
def f(x):
20+
"""Approximated function."""
21+
return x.mm(W_target) + b_target[0]
22+
23+
24+
# plot function curve and fitting curve
25+
def plot_function(model):
26+
x_data = make_features(torch.arange(-1, 1, 0.01))
27+
y_data = f(x_data)
28+
if torch.cuda.is_available():
29+
y_pred = model(Variable(x_data).cuda())
30+
x = torch.arange(-1, 1, 0.01).numpy()
31+
y = y_data.numpy()
32+
y_p = y_pred.cpu().data.numpy()
33+
plt.xlabel('x')
34+
plt.ylabel('y')
35+
plt.plot(x, y, 'r', label='real curve')
36+
plt.plot(x, y_p, label='fitting curve')
37+
plt.legend(loc='best')
38+
plt.show()
39+
40+
41+
# print funciton describe
42+
def poly_desc(w, b):
43+
des = 'y = {:.2f} + {:.2f}*x + {:.2f}*x^2 + {:.2f}*x^3'.format(
44+
b[0], w[0], w[1], w[2])
45+
return des
46+
47+
48+
# get data
49+
def get_batch(batch_size=32):
50+
"""Builds a batch i.e. (x, f(x)) pair."""
51+
random = torch.randn(batch_size)
52+
x = make_features(random)
53+
y = f(x)
54+
if torch.cuda.is_available():
55+
return Variable(x).cuda(), Variable(y).cuda()
56+
else:
57+
return Variable(x), Variable(y)
58+
59+
60+
# Define model
61+
class poly_model(nn.Module):
62+
def __init__(self):
63+
super(poly_model, self).__init__()
64+
self.poly = nn.Linear(3, 1)
65+
66+
def forward(self, x):
67+
out = self.poly(x)
68+
return out
69+
70+
71+
if torch.cuda.is_available():
72+
model = poly_model().cuda()
73+
else:
74+
model = poly_model()
75+
76+
criterion = nn.MSELoss()
77+
optimizer = optim.SGD(model.parameters(), lr=1e-3)
78+
79+
epoch = 0
80+
while True:
81+
# Get data
82+
batch_x, batch_y = get_batch()
83+
84+
# Forward pass
85+
output = model(batch_x)
86+
loss = criterion(output, batch_y)
87+
print_loss = loss.data[0]
88+
89+
# Reset gradients
90+
optimizer.zero_grad()
91+
# Backward pass
92+
loss.backward()
93+
# update parameters
94+
optimizer.step()
95+
epoch += 1
96+
if print_loss < 1e-3:
97+
break
98+
99+
print('Loss: {:.6f} after {} batches'.format(print_loss, epoch))
100+
print('==> Learned function:\t' + poly_desc(model.poly.weight.data.view(-1),
101+
model.poly.bias.data))
102+
print('==> Actual function:\t' + poly_desc(W_target.view(-1), b_target))
103+
plot_function(model)

0 commit comments

Comments
 (0)