eaglelandsonce commited on
Commit
5f31e7d
1 Parent(s): a19e34a

Update pages/4_LogisticRegressioin.py

Browse files
Files changed (1) hide show
  1. pages/4_LogisticRegressioin.py +74 -1
pages/4_LogisticRegressioin.py CHANGED
@@ -1 +1,74 @@
1
- #LogisticRegression
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #LogisticRegression
2
+
3
+ import streamlit as st
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.optim as optim
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+
10
+ # Define the Logistic Regression Model
11
+ class LogisticRegressionModel(nn.Module):
12
+ def __init__(self):
13
+ super(LogisticRegressionModel, self).__init__()
14
+ self.linear = nn.Linear(1, 1)
15
+
16
+ def forward(self, x):
17
+ return torch.sigmoid(self.linear(x))
18
+
19
+ # Generate synthetic data
20
+ np.random.seed(0)
21
+ torch.manual_seed(0)
22
+ n_samples = 100
23
+ X = np.random.rand(n_samples, 1) * 10 # Random hours between 0 and 10
24
+ y = (X > 5).astype(int).flatten() # Pass if study hours > 5, otherwise fail
25
+
26
+ # Convert to torch tensors
27
+ X_tensor = torch.tensor(X, dtype=torch.float32)
28
+ y_tensor = torch.tensor(y, dtype=torch.float32)
29
+
30
+ # Streamlit interface
31
+ st.title('Logistic Regression with PyTorch')
32
+
33
+ # User inputs
34
+ num_epochs = st.number_input('Number of Epochs', min_value=100, max_value=5000, step=100, value=1000)
35
+ learning_rate = st.number_input('Learning Rate', min_value=0.0001, max_value=0.1, step=0.0001, format="%.4f", value=0.01)
36
+ test_hours = st.text_input('Test Study Hours (comma separated)', '4.0, 6.0, 9.0')
37
+
38
+ # Initialize the model
39
+ model = LogisticRegressionModel()
40
+
41
+ # Binary Cross Entropy Loss
42
+ criterion = nn.BCELoss()
43
+
44
+ # Stochastic Gradient Descent Optimizer
45
+ optimizer = optim.SGD(model.parameters(), lr=learning_rate)
46
+
47
+ # Training the model
48
+ loss_values = []
49
+ for epoch in range(num_epochs):
50
+ outputs = model(X_tensor)
51
+ loss = criterion(outputs, y_tensor.view(-1, 1))
52
+ optimizer.zero_grad()
53
+ loss.backward()
54
+ optimizer.step()
55
+ loss_values.append(loss.item())
56
+
57
+ # Plot the loss curve
58
+ fig, ax = plt.subplots()
59
+ ax.plot(range(num_epochs), loss_values)
60
+ ax.set_xlabel('Epoch')
61
+ ax.set_ylabel('Loss')
62
+ ax.set_title('Loss Curve')
63
+ st.pyplot(fig)
64
+
65
+ # Evaluation
66
+ model.eval()
67
+ test_hours = [float(hour.strip()) for hour in test_hours.split(',')]
68
+ test_tensor = torch.tensor(test_hours, dtype=torch.float32).view(-1, 1)
69
+ predictions = model(test_tensor).detach().numpy()
70
+
71
+ # Display predictions
72
+ st.write('## Predictions')
73
+ for i, test_hour in enumerate(test_hours):
74
+ st.write(f"Study hours: {test_hour}, Predicted pass probability: {predictions[i][0]:.4f}")