Challenge: Implementing Linear Regression
Tehtävä
Swipe to start coding
You are provided with a dataset that contains information about the number of hours students studied and their corresponding test scores. Your task is to train a linear regression model on this data.
- Convert these columns into PyTorch tensors, and reshape them to ensure they are 2D with shapes
[N, 1]
. - Define a simple linear regression model.
- Use MSE as the loss function.
- Define
optimizer
as SGD with the learning rate equal to0.01
. - Train the linear regression model to predict test scores based on the number of hours studied. At each epoch:
- Compute predictions on
X_tensor
; - Compute the loss;
- Reset the gradient;
- Perform backward pass;
- Update the parameters.
- Compute predictions on
- Access the model's parameters (weights and bias).
Ratkaisu
99
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
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(42)
scores_df = pd.read_csv('https://content-media-cdn.codefinity.com/courses/1dd2b0f6-6ec0-40e6-a570-ed0ac2209666/section_2/hours_scores.csv')
X = scores_df['Hours Studied'].values
Y = scores_df['Test Score'].values
# Convert to PyTorch tensors and reshape
X_tensor = torch.tensor(X, dtype=torch.float32).reshape(-1, 1)
Y_tensor = torch.tensor(Y, dtype=torch.float32).reshape(-1, 1)
# Define the linear regression model
model = nn.Linear(1, 1)
# Define the loss function and optimizer
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# Train the model
epochs = 100
for epoch in range(epochs):
# Perform forward pass
predictions = model(X_tensor)
loss = criterion(predictions, Y_tensor)
# Reset the gradient
optimizer.zero_grad()
# Perform backward pass
loss.backward()
# Update the parameters
optimizer.step()
if (epoch + 1) % 10 == 0:
print(f"Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}")
# Print the model's parameters
weights = model.weight.data
bias = model.bias.data
Oliko kaikki selvää?
Kiitos palautteestasi!
Osio 2. Luku 4
99
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
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(42)
scores_df = pd.read_csv('https://content-media-cdn.codefinity.com/courses/1dd2b0f6-6ec0-40e6-a570-ed0ac2209666/section_2/hours_scores.csv')
X = scores_df['Hours Studied'].values
Y = scores_df['Test Score'].values
# Convert to PyTorch tensors and reshape
X_tensor = ___.___(___, dtype=torch.float32).___
Y_tensor = ___.___(___, dtype=torch.float32).___
# Define the linear regression model
model = ___
# Define the loss function and optimizer
criterion = ___
optimizer = ___
# Train the model
epochs = 100
for epoch in range(epochs):
# Perform forward pass
predictions = ___
loss = ___
# Reset the gradient
___
# Perform backward pass
___
# Update the parameters
___
if (epoch + 1) % 10 == 0:
print(f"Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}")
# Print the model's parameters
weights = ___
bias = ___
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme