Spaces:
Running
Running
Update pages/2_LinearRegression.py
Browse files- pages/2_LinearRegression.py +65 -29
pages/2_LinearRegression.py
CHANGED
|
@@ -3,47 +3,83 @@ import numpy as np
|
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import torch
|
| 5 |
import torch.nn as nn
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
def forward(self, x):
|
| 17 |
return self.linear(x)
|
| 18 |
|
| 19 |
-
|
| 20 |
-
model = LinearModel(1, 1)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
#
|
| 30 |
-
|
| 31 |
-
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
y = y_tensor.numpy().flatten() + noise_level * np.random.randn(num_points)
|
| 40 |
-
|
| 41 |
-
# Create scatter plot
|
| 42 |
fig, ax = plt.subplots()
|
| 43 |
-
ax.scatter(x, y, alpha=0.6)
|
|
|
|
| 44 |
ax.set_title('Scatter Plot with Noise and Number of Data Points')
|
| 45 |
ax.set_xlabel('X-axis')
|
| 46 |
ax.set_ylabel('Y-axis')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
# Display plot in Streamlit
|
| 49 |
-
st.pyplot(
|
|
|
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
import torch
|
| 5 |
import torch.nn as nn
|
| 6 |
+
import torch.optim as optim
|
| 7 |
|
| 8 |
+
# Streamlit app title
|
| 9 |
+
st.title('Simple Linear Regression with PyTorch')
|
| 10 |
+
|
| 11 |
+
# Sidebar sliders for noise and number of data points
|
| 12 |
+
noise_level = st.sidebar.slider('Noise Level', 0.0, 1.0, 0.1, step=0.01)
|
| 13 |
+
num_points = st.sidebar.slider('Number of Data Points', 10, 100, 50, step=5)
|
| 14 |
+
num_epochs = st.sidebar.slider('Number of Epochs', 10, 500, 100, step=10)
|
| 15 |
+
learning_rate = st.sidebar.slider('Learning Rate', 0.001, 0.1, 0.01, step=0.001)
|
| 16 |
|
| 17 |
+
# Generate data
|
| 18 |
+
np.random.seed(0)
|
| 19 |
+
x = np.linspace(0, 10, num_points)
|
| 20 |
+
y = 2 * x + 1 + noise_level * np.random.randn(num_points)
|
| 21 |
+
|
| 22 |
+
# Convert data to PyTorch tensors
|
| 23 |
+
x_tensor = torch.tensor(x, dtype=torch.float32).view(-1, 1)
|
| 24 |
+
y_tensor = torch.tensor(y, dtype=torch.float32).view(-1, 1)
|
| 25 |
+
|
| 26 |
+
# Define the linear regression model
|
| 27 |
+
class LinearRegressionModel(nn.Module):
|
| 28 |
+
def __init__(self):
|
| 29 |
+
super(LinearRegressionModel, self).__init__()
|
| 30 |
+
self.linear = nn.Linear(1, 1)
|
| 31 |
|
| 32 |
def forward(self, x):
|
| 33 |
return self.linear(x)
|
| 34 |
|
| 35 |
+
model = LinearRegressionModel()
|
|
|
|
| 36 |
|
| 37 |
+
# Define the loss function and the optimizer
|
| 38 |
+
criterion = nn.MSELoss()
|
| 39 |
+
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
|
| 40 |
|
| 41 |
+
# Train the model
|
| 42 |
+
losses = []
|
| 43 |
+
for epoch in range(num_epochs):
|
| 44 |
+
model.train()
|
| 45 |
+
optimizer.zero_grad()
|
| 46 |
+
outputs = model(x_tensor)
|
| 47 |
+
loss = criterion(outputs, y_tensor)
|
| 48 |
+
loss.backward()
|
| 49 |
+
optimizer.step()
|
| 50 |
+
losses.append(loss.item())
|
| 51 |
|
| 52 |
+
# Get the final model parameters
|
| 53 |
+
slope = model.linear.weight.item()
|
| 54 |
+
intercept = model.linear.bias.item()
|
| 55 |
|
| 56 |
+
# Make predictions
|
| 57 |
+
model.eval()
|
| 58 |
+
y_pred_tensor = model(x_tensor)
|
| 59 |
+
y_pred = y_pred_tensor.detach().numpy()
|
| 60 |
+
|
| 61 |
+
# Create scatter plot with regression line
|
|
|
|
|
|
|
|
|
|
| 62 |
fig, ax = plt.subplots()
|
| 63 |
+
ax.scatter(x, y, alpha=0.6, label='Data points')
|
| 64 |
+
ax.plot(x, y_pred, color='red', label='Regression line')
|
| 65 |
ax.set_title('Scatter Plot with Noise and Number of Data Points')
|
| 66 |
ax.set_xlabel('X-axis')
|
| 67 |
ax.set_ylabel('Y-axis')
|
| 68 |
+
ax.legend()
|
| 69 |
+
|
| 70 |
+
# Display slope and intercept in Streamlit
|
| 71 |
+
st.write(f"**Slope:** {slope}")
|
| 72 |
+
st.write(f"**Intercept:** {intercept}")
|
| 73 |
+
|
| 74 |
+
# Display scatter plot in Streamlit
|
| 75 |
+
st.pyplot(fig)
|
| 76 |
+
|
| 77 |
+
# Plot training loss
|
| 78 |
+
fig_loss, ax_loss = plt.subplots()
|
| 79 |
+
ax_loss.plot(range(num_epochs), losses)
|
| 80 |
+
ax_loss.set_title('Training Loss')
|
| 81 |
+
ax_loss.set_xlabel('Epoch')
|
| 82 |
+
ax_loss.set_ylabel('Loss')
|
| 83 |
|
| 84 |
+
# Display training loss plot in Streamlit
|
| 85 |
+
st.pyplot(fig_loss)
|