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
| import torch import matplotlib.pyplot as plt from torch import nn import torch.optim as optim import numpy as np
class LinearRegressionModel(nn.Module): def __init__(self): super().__init__() self.weight = nn.Parameter(torch.randn(1, requires_grad=True, dtype=torch.float)) self.bias = nn.Parameter(torch.randn(1, requires_grad=True, dtype=torch.float))
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.weight * x + self.bias
weight = 0.7 bias = 0.3
start = 0 end = 1 step = 0.02
x = torch.arange(start, end, step).unsqueeze(dim = 1) y = weight * x + bias
train_split = int(0.8 * len(x)) test_split = int(0.2 * len(x))
x_train = x[:train_split] y_train = y[:train_split] x_test = x[-test_split:] y_test = y[-test_split:]
def plot_predictions(train_data = x_train, train_labels = y_train, test_data = x_test, test_labels = y_test, predictions = None): plt.figure(figsize = (10, 7)) plt.scatter(train_data, train_labels, c="b", s=4, label="Training data") plt.scatter(test_data, test_labels, c="g", s=4, label="Test data") if predictions is not None: plt.scatter(test_data, predictions, c="r", s=4, label="Predictions") plt.legend(prop={"size": 14});
model_0 = LinearRegressionModel() epochs = 6000 loss_fn = nn.L1Loss() optimizer = torch.optim.SGD(params = model_0.parameters(), lr = 0.001) epochs_count = [] train_loss = [] test_loss = [] lass_loss = -1;
for epochs in range(epochs): model_0.train() y_pred = model_0(x_train) loss = loss_fn(y_pred, y_train) optimizer.zero_grad() loss.backward() optimizer.step() model_0.eval() if (epochs % 10 == 0): with torch.inference_mode(): y_test_pred = model_0(x_test) loss_test = loss_fn(y_test_pred, y_test) train_loss.append(loss) test_loss.append(loss_test) epochs_count.append(epochs)
plt.plot(epochs_count, torch.tensor(train_loss).numpy(), label = "Train loss") plt.plot(epochs_count, test_loss, label = "Test loss") plt.title("Training and test loss curves") plt.ylabel("Loss") plt.xlabel("Epochs") plt.legend()
|