Skip to content

Instantly share code, notes, and snippets.

@vicradon
Created May 21, 2023 15:41
Show Gist options
  • Save vicradon/dee740eabe8c3aada8f826657fe5cf75 to your computer and use it in GitHub Desktop.
Save vicradon/dee740eabe8c3aada8f826657fe5cf75 to your computer and use it in GitHub Desktop.
A python script that calculates the weights necessary for a simple linear regression prediction model
'''
In this program, we implement a simple linear regression ML model
that tries to find weights that will match the input tensor x to
the output tensor y in a multiplication operation
'''
import torch
x = torch.tensor(1.0)
y = torch.tensor(2.0)
w = torch.tensor(1.0, requires_grad=True)
learning_rate = 0.01
num_epochs = 100
# Train the model
for epoch in range(num_epochs):
# forward pass
y_hat = w * x
loss = (y_hat - y)**2
# backward pass
loss.backward()
w.data -= learning_rate * w.grad
w.grad.zero_()
print(w * x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment