|
| 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