eaglelandsonce commited on
Commit
8a34309
·
verified ·
1 Parent(s): 98cec02

Update pages/42_regression.py

Browse files
Files changed (1) hide show
  1. pages/42_regression.py +67 -37
pages/42_regression.py CHANGED
@@ -1,49 +1,79 @@
1
- import streamlit as st
2
- import plotly.graph_objects as go
 
 
 
 
3
 
4
- # Title
5
- st.title("Interactive Equation Plotter")
 
 
6
 
7
- # Sidebar sliders
8
- st.sidebar.header("Controls")
9
- w = st.sidebar.slider('W (slope)', min_value=-10.0, max_value=10.0, value=1.0, step=0.1)
10
- b = st.sidebar.slider('B (intercept)', min_value=-100.0, max_value=100.0, value=0.0, step=1.0)
11
 
12
- # Initial x position
13
- x = st.slider('X position', min_value=-100.0, max_value=100.0, value=0.0, step=1.0)
 
 
 
14
 
15
- # Calculate y based on the equation y = w * x + b
16
- y = w * x + b
 
 
 
 
17
 
18
- # Create the plot
19
- fig = go.Figure()
 
 
20
 
21
- # Plot for the y-axis (top line)
22
- fig.add_shape(type="line", x0=-100, x1=100, y0=1, y1=1,
23
- line=dict(color="blue", width=2, dash="dash"))
 
24
 
25
- # Plot for the x-axis (bottom line)
26
- fig.add_shape(type="line", x0=-100, x1=100, y0=-1, y1=-1,
27
- line=dict(color="blue", width=2, dash="dash"))
28
 
29
- # Plot the x point
30
- fig.add_trace(go.Scatter(x=[x], y=[-1], mode='markers', marker=dict(color='red', size=10), name="X point"))
 
 
 
 
 
 
 
 
31
 
32
- # Plot the y point
33
- fig.add_trace(go.Scatter(x=[y], y=[1], mode='markers', marker=dict(color='red', size=10), name="Y point"))
 
 
 
34
 
35
- # Update the layout
36
- fig.update_layout(
37
- title=f'y = {w} * x + {b}',
38
- xaxis=dict(range=[-100, 100]),
39
- yaxis=dict(range=[-2, 2], showticklabels=False),
40
- showlegend=False,
41
- height=400,
42
- margin=dict(t=50, b=10)
43
- )
44
 
45
- # Display the plot in Streamlit
46
- st.plotly_chart(fig)
 
 
 
 
 
 
47
 
48
- # Add instruction to click and drag the point on x-axis
49
- st.write("Drag the red dot on the x-axis to change the x position.")
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.optim as optim
6
+ from sklearn.model_selection import train_test_split
7
 
8
+ # Step 1: Create Synthetic Data
9
+ np.random.seed(42)
10
+ X = np.linspace(-10, 10, 1000)
11
+ y = 2.5 * X + np.random.normal(0, 2, X.shape) # Linear relation with noise
12
 
13
+ # Split into training and test sets
14
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
 
15
 
16
+ # Convert to PyTorch tensors
17
+ X_train = torch.tensor(X_train, dtype=torch.float32).view(-1, 1)
18
+ y_train = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)
19
+ X_test = torch.tensor(X_test, dtype=torch.float32).view(-1, 1)
20
+ y_test = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)
21
 
22
+ # Step 2: Define and Train a Neural Network Model
23
+ class SimpleNN(nn.Module):
24
+ def __init__(self):
25
+ super(SimpleNN, self).__init__()
26
+ self.fc1 = nn.Linear(1, 10)
27
+ self.fc2 = nn.Linear(10, 1)
28
 
29
+ def forward(self, x):
30
+ x = torch.relu(self.fc1(x))
31
+ x = self.fc2(x)
32
+ return x
33
 
34
+ # Initialize model, loss function, and optimizer
35
+ model = SimpleNN()
36
+ criterion = nn.MSELoss()
37
+ optimizer = optim.Adam(model.parameters(), lr=0.01)
38
 
39
+ # Training loop
40
+ epochs = 500
41
+ losses = []
42
 
43
+ for epoch in range(epochs):
44
+ model.train()
45
+ optimizer.zero_grad()
46
+ outputs = model(X_train)
47
+ loss = criterion(outputs, y_train)
48
+ loss.backward()
49
+ optimizer.step()
50
+ losses.append(loss.item())
51
+ if (epoch + 1) % 50 == 0:
52
+ print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}')
53
 
54
+ # Step 3: Plot the Results
55
+ # Plot the synthetic data and the model's predictions
56
+ model.eval()
57
+ with torch.no_grad():
58
+ predicted = model(X_test).numpy()
59
 
60
+ plt.figure(figsize=(12, 6))
 
 
 
 
 
 
 
 
61
 
62
+ # Plot data and predictions
63
+ plt.subplot(1, 2, 1)
64
+ plt.scatter(X_test, y_test, label='Original data', alpha=0.5)
65
+ plt.scatter(X_test, predicted, label='Fitted line', alpha=0.5)
66
+ plt.title('Regression Results')
67
+ plt.xlabel('X')
68
+ plt.ylabel('y')
69
+ plt.legend()
70
 
71
+ # Plot training loss
72
+ plt.subplot(1, 2, 2)
73
+ plt.plot(losses)
74
+ plt.title('Training Loss')
75
+ plt.xlabel('Epoch')
76
+ plt.ylabel('Loss')
77
+
78
+ plt.tight_layout()
79
+ plt.show()