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
| import torch import numpy as np import torch.nn as nn
x_values = [i for i in range(11)] x_train = np.array(x_values, dtype=np.float32) x_train = x_train.reshape(-1, 1)
y_values = [2.5*i+3.5 for i in x_values] y_train = np.array(y_values, dtype=np.float32) y_train = y_train.reshape(-1, 1)
class LinearRegressionModel(nn.Module): def __init__(self, input_dim, output_dim): super(LinearRegressionModel, self).__init__() self.linear = nn.Linear(input_dim, output_dim)
def forward(self, x): out = self.linear(x) return out
input_dim = 1 output_dim = 1 model = LinearRegressionModel(input_dim, output_dim)
epochs = 1000 learning_rate = 0.01 optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
criterion = nn.MSELoss()
for epoch in range(epochs): epoch += 1 inputs = torch.from_numpy(x_train) labels = torch.from_numpy(y_train)
optimizer.zero_grad()
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if epoch % 50 == 0: print('epoch {}, loss {}'.format(epoch, loss.item()))
y_predicted = model.forward(torch.from_numpy(x_train)).data.numpy()
print(y_predicted)
|