soumickmj commited on
Commit
4e159ba
1 Parent(s): 0273a09
Files changed (2) hide show
  1. app.py +159 -0
  2. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.optim as optim
6
+ from sklearn.utils import shuffle
7
+ from sklearn.preprocessing import StandardScaler
8
+ from sklearn.linear_model import LogisticRegression
9
+ from sklearn.model_selection import train_test_split
10
+
11
+
12
+ # Function for disease task
13
+ def run_disease_task():
14
+ # Number of samples per class
15
+ N_per_class = 500
16
+
17
+ # Number of classes
18
+ num_classes = 5
19
+
20
+ # Total number of samples
21
+ N = N_per_class * num_classes
22
+
23
+ # Number of features
24
+ D = 2 # For visualization purposes
25
+
26
+ # Initialize feature matrix X and label vector y
27
+ X = np.zeros((N, D))
28
+ y = np.zeros(N, dtype=int)
29
+
30
+ # Generate a multi-class spiral dataset
31
+ def generate_multi_class_spiral(points, classes):
32
+ X = np.zeros((points * classes, 2))
33
+ y = np.zeros(points * classes, dtype=int)
34
+ for class_number in range(classes):
35
+ ix = range(points * class_number, points * (class_number + 1))
36
+ r = np.linspace(0.0, 1, points)
37
+ t = np.linspace(class_number * 4, (class_number + 1) * 4, points) + np.random.randn(points) * 0.2
38
+ X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]
39
+ y[ix] = class_number
40
+ return X, y
41
+
42
+ X, y = generate_multi_class_spiral(N_per_class, num_classes)
43
+
44
+ # Shuffle the dataset
45
+ X, y = shuffle(X, y, random_state=42)
46
+
47
+ # Normalize the features
48
+ scaler = StandardScaler()
49
+ X_scaled = scaler.fit_transform(X)
50
+
51
+ # Convert data to torch tensors
52
+ X_train_tensor = torch.from_numpy(X_scaled).float()
53
+ y_train_tensor = torch.from_numpy(y).long()
54
+
55
+ # Split data into training and test sets
56
+ X_train_tensor, X_test_tensor, y_train_tensor, y_test_tensor = train_test_split(
57
+ X_train_tensor, y_train_tensor, test_size=0.2, random_state=42
58
+ )
59
+
60
+ # Logistic Regression Model
61
+ linear_model = LogisticRegression(max_iter=200)
62
+ linear_model.fit(X_scaled[: int(0.8 * N)], y[: int(0.8 * N)])
63
+
64
+ # Linear model accuracy
65
+ linear_accuracy = linear_model.score(X_scaled[int(0.8 * N) :], y[int(0.8 * N) :])
66
+
67
+ # Neural Network Model
68
+ class NeuralNet(nn.Module):
69
+ def __init__(self, input_dim, hidden_dims, output_dim):
70
+ super(NeuralNet, self).__init__()
71
+ layers = []
72
+ in_dim = input_dim
73
+ for h_dim in hidden_dims:
74
+ layers.append(nn.Linear(in_dim, h_dim))
75
+ layers.append(nn.ReLU())
76
+ layers.append(nn.BatchNorm1d(h_dim))
77
+ layers.append(nn.Dropout(0.3))
78
+ in_dim = h_dim
79
+ layers.append(nn.Linear(in_dim, output_dim))
80
+ self.model = nn.Sequential(*layers)
81
+
82
+ def forward(self, x):
83
+ return self.model(x)
84
+
85
+ # Initialize Neural Network Model
86
+ hidden_dims = [128, 64, 32]
87
+ neural_model = NeuralNet(D, hidden_dims, num_classes)
88
+
89
+ # Loss and optimizer for Neural Network Model
90
+ criterion = nn.CrossEntropyLoss()
91
+ optimizer = optim.Adam(neural_model.parameters(), lr=0.001, weight_decay=1e-4)
92
+
93
+ # Training the Neural Network Model
94
+ num_epochs = 200
95
+ for epoch in range(num_epochs):
96
+ neural_model.train()
97
+ outputs = neural_model(X_train_tensor)
98
+ loss = criterion(outputs, y_train_tensor)
99
+ optimizer.zero_grad()
100
+ loss.backward()
101
+ optimizer.step()
102
+ if (epoch + 1) % 20 == 0:
103
+ st.write(f'Neural Network - Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item():.4f}')
104
+
105
+ # Evaluate Neural Network Model
106
+ neural_model.eval()
107
+ with torch.no_grad():
108
+ outputs = neural_model(X_test_tensor)
109
+ _, predicted = torch.max(outputs.data, 1)
110
+ neural_accuracy = (predicted == y_test_tensor).sum().item() / y_test_tensor.size(0)
111
+ st.write(f'Neural Network Model Accuracy: {neural_accuracy * 100:.2f}%')
112
+
113
+ # Summary of Accuracies
114
+ st.write("\nSummary of Accuracies:")
115
+ st.write(f'Linear Model Accuracy: {linear_accuracy * 100:.2f}%')
116
+ st.write(f'Neural Network Model Accuracy: {neural_accuracy * 100:.2f}%')
117
+
118
+
119
+ # Function for male superhero task
120
+ def run_male_superhero_task():
121
+ st.write("Training Male Superhero model...")
122
+ # Male superhero training logic goes here
123
+ # Add dummy print statements as a placeholder
124
+ st.write("Male superhero model - Step 1: Data prepared.")
125
+ st.write("Male superhero model - Step 2: Model trained.")
126
+ st.write("Male superhero model - Step 3: Results evaluated.")
127
+
128
+
129
+ # Function for female superhero task
130
+ def run_female_superhero_task():
131
+ st.write("Training Female Superhero model...")
132
+ # Female superhero training logic goes here
133
+ # Add dummy print statements as a placeholder
134
+ st.write("Female superhero model - Step 1: Data prepared.")
135
+ st.write("Female superhero model - Step 2: Model trained.")
136
+ st.write("Female superhero model - Step 3: Results evaluated.")
137
+
138
+
139
+ # Streamlit UI
140
+ st.title("AI Training Demo")
141
+
142
+ # Task selection buttons
143
+ task = st.selectbox("Choose a task:", ("Superhero", "Disease"))
144
+
145
+ if task == "Superhero":
146
+ # Sub-options for Male and Female Superhero
147
+ gender = st.selectbox("Choose the gender:", ("Male", "Female"))
148
+
149
+ if gender == "Male":
150
+ if st.button("Run Male Superhero Task"):
151
+ run_male_superhero_task()
152
+
153
+ elif gender == "Female":
154
+ if st.button("Run Female Superhero Task"):
155
+ run_female_superhero_task()
156
+
157
+ elif task == "Disease":
158
+ if st.button("Run Disease Task"):
159
+ run_disease_task()
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ scikit-learn