v2 release
Browse files- NdR_disease.py +66 -62
- NdR_female_superheros.py +245 -184
- app.py +93 -37
NdR_disease.py
CHANGED
|
@@ -7,7 +7,7 @@ from sklearn.utils import shuffle
|
|
| 7 |
from sklearn.preprocessing import StandardScaler
|
| 8 |
from sklearn.model_selection import train_test_split
|
| 9 |
|
| 10 |
-
#
|
| 11 |
np.random.seed(42)
|
| 12 |
torch.manual_seed(42)
|
| 13 |
|
|
@@ -16,10 +16,10 @@ def run_disease_train():
|
|
| 16 |
N_per_class = 500
|
| 17 |
|
| 18 |
# List of conditions (classes)
|
| 19 |
-
|
| 20 |
|
| 21 |
# Total number of classes
|
| 22 |
-
num_classes = len(
|
| 23 |
|
| 24 |
# Total number of samples
|
| 25 |
N = N_per_class * num_classes
|
|
@@ -35,36 +35,36 @@ def run_disease_train():
|
|
| 35 |
y = np.zeros(N, dtype=int)
|
| 36 |
|
| 37 |
# Define the mean and standard deviation for each feature per condition
|
| 38 |
-
# Features: [
|
| 39 |
-
|
| 40 |
-
'
|
| 41 |
'mean': [1, 6, 7, 8, 1, 1, 1, 5, 5, 5],
|
| 42 |
'std': [1.5, 2, 2, 2, 1.5, 1.5, 1.5, 2, 2, 2]
|
| 43 |
},
|
| 44 |
-
'
|
| 45 |
'mean': [0, 3, 8, 9, 1, 1, 1, 4, 4, 6],
|
| 46 |
'std': [1.5, 2, 2, 2, 1.5, 1.5, 1.5, 2, 2, 2]
|
| 47 |
},
|
| 48 |
-
'
|
| 49 |
'mean': [0, 1, 1, 1, 2, 2, 2, 8, 7, 8],
|
| 50 |
'std': [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 2, 2, 2]
|
| 51 |
},
|
| 52 |
-
'
|
| 53 |
'mean': [2, 2, 1, 1, 7, 6, 8, 5, 6, 5],
|
| 54 |
'std': [1.5, 2, 1.5, 1.5, 2, 2, 2, 2, 2, 2]
|
| 55 |
},
|
| 56 |
-
'
|
| 57 |
'mean': [0, 1, 1, 1, 1, 1, 1, 6, 5, 8],
|
| 58 |
'std': [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 2, 2, 2]
|
| 59 |
},
|
| 60 |
}
|
| 61 |
|
| 62 |
# Generate synthetic data for each condition
|
| 63 |
-
for idx, condition in enumerate(
|
| 64 |
start = idx * N_per_class
|
| 65 |
end = (idx + 1) * N_per_class
|
| 66 |
-
means =
|
| 67 |
-
stds =
|
| 68 |
X_condition = np.random.normal(means, stds, (N_per_class, D))
|
| 69 |
# Ensure feature values are within reasonable ranges
|
| 70 |
X_condition = np.clip(X_condition, 0, 10)
|
|
@@ -130,8 +130,8 @@ def run_disease_train():
|
|
| 130 |
optimizer.zero_grad()
|
| 131 |
loss.backward()
|
| 132 |
optimizer.step()
|
| 133 |
-
if (epoch + 1) %
|
| 134 |
-
st.write('
|
| 135 |
epoch + 1, num_epochs, loss.item()))
|
| 136 |
|
| 137 |
# Evaluate Linear Model
|
|
@@ -177,7 +177,7 @@ def run_disease_train():
|
|
| 177 |
loss.backward()
|
| 178 |
optimizer.step()
|
| 179 |
if (epoch + 1) % 30 == 0:
|
| 180 |
-
st.write('
|
| 181 |
epoch + 1, num_epochs, loss.item()))
|
| 182 |
|
| 183 |
# Evaluate Neural Network Model
|
|
@@ -188,61 +188,65 @@ def run_disease_train():
|
|
| 188 |
neural_accuracy = (predicted == y_test_tensor).sum().item() / y_test_tensor.size(0)
|
| 189 |
|
| 190 |
# Summary of Accuracies
|
| 191 |
-
st.write("\
|
| 192 |
-
st.
|
| 193 |
-
st.
|
| 194 |
-
st.
|
| 195 |
|
| 196 |
-
return linear_model, neural_model, scaler,
|
| 197 |
-
|
| 198 |
-
def get_user_input_and_predict(linear_model, neural_model, scaler, conditions, num_classes):
|
| 199 |
-
st.write("\nAdjust the sliders for the following symptoms on a scale from 0 (none) to 10 (severe):")
|
| 200 |
|
|
|
|
|
|
|
|
|
|
| 201 |
# Feature names
|
| 202 |
-
|
| 203 |
-
|
| 204 |
|
| 205 |
-
#
|
| 206 |
-
user_features
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
# Normalize features
|
| 227 |
user_features = scaler.transform([user_features])
|
| 228 |
user_tensor = torch.from_numpy(user_features).float()
|
| 229 |
-
|
| 230 |
# Random prediction
|
| 231 |
-
|
| 232 |
-
st.
|
| 233 |
-
|
| 234 |
# Linear Model Prediction
|
| 235 |
-
|
| 236 |
with torch.no_grad():
|
| 237 |
-
|
| 238 |
-
_,
|
| 239 |
-
|
| 240 |
-
st.
|
| 241 |
-
|
| 242 |
# Neural Network Prediction
|
| 243 |
-
|
| 244 |
with torch.no_grad():
|
| 245 |
-
|
| 246 |
-
_,
|
| 247 |
-
|
| 248 |
-
st.
|
|
|
|
| 7 |
from sklearn.preprocessing import StandardScaler
|
| 8 |
from sklearn.model_selection import train_test_split
|
| 9 |
|
| 10 |
+
# Imposta il seed casuale per la riproducibilità
|
| 11 |
np.random.seed(42)
|
| 12 |
torch.manual_seed(42)
|
| 13 |
|
|
|
|
| 16 |
N_per_class = 500
|
| 17 |
|
| 18 |
# List of conditions (classes)
|
| 19 |
+
condizioni = ['Raffreddore Comune', 'Allergie Stagionali', 'Emicrania', 'Gastroenterite', 'Cefalea Tensiva']
|
| 20 |
|
| 21 |
# Total number of classes
|
| 22 |
+
num_classes = len(condizioni)
|
| 23 |
|
| 24 |
# Total number of samples
|
| 25 |
N = N_per_class * num_classes
|
|
|
|
| 35 |
y = np.zeros(N, dtype=int)
|
| 36 |
|
| 37 |
# Define the mean and standard deviation for each feature per condition
|
| 38 |
+
# Features: [Febbre, Tosse, Starnuti, Naso che Cola, Nausea, Vomito, Diarrea, Mal di Testa, Affaticamento, Livello di Stress]
|
| 39 |
+
statistiche_condizioni = {
|
| 40 |
+
'Raffreddore Comune': {
|
| 41 |
'mean': [1, 6, 7, 8, 1, 1, 1, 5, 5, 5],
|
| 42 |
'std': [1.5, 2, 2, 2, 1.5, 1.5, 1.5, 2, 2, 2]
|
| 43 |
},
|
| 44 |
+
'Allergie Stagionali': {
|
| 45 |
'mean': [0, 3, 8, 9, 1, 1, 1, 4, 4, 6],
|
| 46 |
'std': [1.5, 2, 2, 2, 1.5, 1.5, 1.5, 2, 2, 2]
|
| 47 |
},
|
| 48 |
+
'Emicrania': {
|
| 49 |
'mean': [0, 1, 1, 1, 2, 2, 2, 8, 7, 8],
|
| 50 |
'std': [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 2, 2, 2]
|
| 51 |
},
|
| 52 |
+
'Gastroenterite': {
|
| 53 |
'mean': [2, 2, 1, 1, 7, 6, 8, 5, 6, 5],
|
| 54 |
'std': [1.5, 2, 1.5, 1.5, 2, 2, 2, 2, 2, 2]
|
| 55 |
},
|
| 56 |
+
'Cefalea Tensiva': {
|
| 57 |
'mean': [0, 1, 1, 1, 1, 1, 1, 6, 5, 8],
|
| 58 |
'std': [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 2, 2, 2]
|
| 59 |
},
|
| 60 |
}
|
| 61 |
|
| 62 |
# Generate synthetic data for each condition
|
| 63 |
+
for idx, condition in enumerate(condizioni):
|
| 64 |
start = idx * N_per_class
|
| 65 |
end = (idx + 1) * N_per_class
|
| 66 |
+
means = statistiche_condizioni[condition]['mean']
|
| 67 |
+
stds = statistiche_condizioni[condition]['std']
|
| 68 |
X_condition = np.random.normal(means, stds, (N_per_class, D))
|
| 69 |
# Ensure feature values are within reasonable ranges
|
| 70 |
X_condition = np.clip(X_condition, 0, 10)
|
|
|
|
| 130 |
optimizer.zero_grad()
|
| 131 |
loss.backward()
|
| 132 |
optimizer.step()
|
| 133 |
+
if (epoch + 1) % 25 == 0:
|
| 134 |
+
st.write('Modello Lineare - Epoch [{}/{}], Loss: {:.4f}'.format(
|
| 135 |
epoch + 1, num_epochs, loss.item()))
|
| 136 |
|
| 137 |
# Evaluate Linear Model
|
|
|
|
| 177 |
loss.backward()
|
| 178 |
optimizer.step()
|
| 179 |
if (epoch + 1) % 30 == 0:
|
| 180 |
+
st.write('Rete Neurale - Epoch [{}/{}], Loss: {:.4f}'.format(
|
| 181 |
epoch + 1, num_epochs, loss.item()))
|
| 182 |
|
| 183 |
# Evaluate Neural Network Model
|
|
|
|
| 188 |
neural_accuracy = (predicted == y_test_tensor).sum().item() / y_test_tensor.size(0)
|
| 189 |
|
| 190 |
# Summary of Accuracies
|
| 191 |
+
st.write("\nRiepilogo delle Accuratezze:....")
|
| 192 |
+
st.error(f'Accuratezza Previsione Casuale: {random_accuracy * 100:.2f}%')
|
| 193 |
+
st.warning(f'Accuratezza Modello Lineare: {linear_accuracy * 100:.2f}%')
|
| 194 |
+
st.success(f'Accuratezza Rete Neurale: {neural_accuracy * 100:.2f}%')
|
| 195 |
|
| 196 |
+
return linear_model, neural_model, scaler, condizioni, num_classes
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
+
def get_user_input_and_predict_disease(modello_lineare, modello_neurale, scaler, condizioni, num_classes):
|
| 199 |
+
st.write("Regola i cursori per i seguenti sintomi su una scala da 0 (nessuno) a 10 (grave):")
|
| 200 |
+
|
| 201 |
# Feature names
|
| 202 |
+
nomi_caratteristiche = ['Febbre', 'Tosse', 'Starnuti', 'Naso che Cola', 'Nausea', 'Vomito',
|
| 203 |
+
'Diarrea', 'Mal di Testa', 'Affaticamento', 'Livello di Stress']
|
| 204 |
|
| 205 |
+
# Initialize or retrieve user features from session state
|
| 206 |
+
if 'user_features' not in st.session_state:
|
| 207 |
+
st.session_state.user_features = [5] * len(nomi_caratteristiche) # Valore predefinito impostato a 5
|
| 208 |
+
|
| 209 |
+
# Create a form to group sliders and button
|
| 210 |
+
with st.form(key='symptom_form'):
|
| 211 |
+
for i, caratteristica in enumerate(nomi_caratteristiche):
|
| 212 |
+
st.session_state.user_features[i] = st.slider(
|
| 213 |
+
caratteristica, 0, 10, st.session_state.user_features[i], key=f'slider_{i}'
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# Form submission button
|
| 217 |
+
submit_button = st.form_submit_button(label='Calcola Previsioni')
|
| 218 |
+
if submit_button:
|
| 219 |
+
st.session_state.form_submitted = True # Store form submission state
|
| 220 |
+
|
| 221 |
+
# Check if the form has been submitted
|
| 222 |
+
if st.session_state.get('form_submitted', False):
|
| 223 |
+
user_features = st.session_state.user_features.copy()
|
| 224 |
+
|
| 225 |
+
# Calculate interaction terms
|
| 226 |
+
termine_interazione = np.sin(user_features[7]) * np.log1p(user_features[9]) # Mal di testa e Livello di Stress
|
| 227 |
+
termine_interazione2 = user_features[0] * user_features[4] # Febbre * Nausea
|
| 228 |
+
user_features.extend([termine_interazione, termine_interazione2])
|
| 229 |
+
|
| 230 |
# Normalize features
|
| 231 |
user_features = scaler.transform([user_features])
|
| 232 |
user_tensor = torch.from_numpy(user_features).float()
|
| 233 |
+
|
| 234 |
# Random prediction
|
| 235 |
+
previsione_casuale = np.random.randint(num_classes)
|
| 236 |
+
st.error(f"\nPrevisione Casuale: {condizioni[previsione_casuale]}")
|
| 237 |
+
|
| 238 |
# Linear Model Prediction
|
| 239 |
+
modello_lineare.eval()
|
| 240 |
with torch.no_grad():
|
| 241 |
+
output = modello_lineare(user_tensor)
|
| 242 |
+
_, predetto = torch.max(output.data, 1)
|
| 243 |
+
previsione_lineare = predetto.item()
|
| 244 |
+
st.warning(f"Previsione Modello Lineare: {condizioni[previsione_lineare]}")
|
| 245 |
+
|
| 246 |
# Neural Network Prediction
|
| 247 |
+
modello_neurale.eval()
|
| 248 |
with torch.no_grad():
|
| 249 |
+
output = modello_neurale(user_tensor)
|
| 250 |
+
_, predetto = torch.max(output.data, 1)
|
| 251 |
+
previsione_neurale = predetto.item()
|
| 252 |
+
st.success(f"Previsione Rete Neurale: {condizioni[previsione_neurale]}")
|
NdR_female_superheros.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import numpy as np
|
| 2 |
import torch
|
| 3 |
import torch.nn as nn
|
|
@@ -10,187 +11,247 @@ from sklearn.preprocessing import StandardScaler
|
|
| 10 |
np.random.seed(42)
|
| 11 |
torch.manual_seed(42)
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
X
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
#
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
'
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
'
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
'
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
'
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
'
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
for
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
# Define Linear Model
|
| 107 |
-
class LinearModel(nn.Module):
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
# Initialize Linear Model
|
| 116 |
-
input_dim = total_features
|
| 117 |
-
output_dim = num_classes
|
| 118 |
-
linear_model = LinearModel(input_dim, output_dim)
|
| 119 |
-
|
| 120 |
-
# Loss and optimizer for Linear Model
|
| 121 |
-
criterion = nn.CrossEntropyLoss()
|
| 122 |
-
optimizer = optim.SGD(linear_model.parameters(), lr=0.01, weight_decay=1e-4)
|
| 123 |
-
|
| 124 |
-
# Training the Linear Model
|
| 125 |
-
num_epochs =
|
| 126 |
-
for epoch in range(num_epochs):
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
# Evaluate Linear Model
|
| 138 |
-
linear_model.eval()
|
| 139 |
-
with torch.no_grad():
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
in_dim
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
import numpy as np
|
| 3 |
import torch
|
| 4 |
import torch.nn as nn
|
|
|
|
| 11 |
np.random.seed(42)
|
| 12 |
torch.manual_seed(42)
|
| 13 |
|
| 14 |
+
def run_female_superhero_train():
|
| 15 |
+
# Number of samples per superhero
|
| 16 |
+
N_per_class = 200
|
| 17 |
+
|
| 18 |
+
# List of female superheroes
|
| 19 |
+
superheroes = ['Wonder Woman', 'Captain Marvel', 'Vedova Nera', 'Tempesta', 'Supergirl']
|
| 20 |
+
|
| 21 |
+
# Total number of classes
|
| 22 |
+
num_classes = len(superheroes)
|
| 23 |
+
|
| 24 |
+
# Total number of samples
|
| 25 |
+
N = N_per_class * num_classes
|
| 26 |
+
|
| 27 |
+
# Number of original features
|
| 28 |
+
D = 5 # Strength, Speed, Intelligence, Durability, Energy Projection
|
| 29 |
+
|
| 30 |
+
# Update the total number of features after adding the interaction term
|
| 31 |
+
total_features = D + 1 # Original features plus the interaction term
|
| 32 |
+
|
| 33 |
+
# Initialize feature matrix X and label vector y
|
| 34 |
+
X = np.zeros((N, total_features))
|
| 35 |
+
y = np.zeros(N, dtype=int)
|
| 36 |
+
|
| 37 |
+
# Define the mean and standard deviation for each feature per superhero
|
| 38 |
+
# Features: [Strength, Speed, Intelligence, Durability, Energy Projection]
|
| 39 |
+
superhero_stats = {
|
| 40 |
+
'Wonder Woman': {
|
| 41 |
+
'mean': [9, 9, 8, 9, 8],
|
| 42 |
+
'std': [0.5, 0.5, 0.5, 0.5, 0.5]
|
| 43 |
+
},
|
| 44 |
+
'Captain Marvel': {
|
| 45 |
+
'mean': [10, 9, 7, 10, 10],
|
| 46 |
+
'std': [0.5, 0.5, 0.5, 0.5, 0.5]
|
| 47 |
+
},
|
| 48 |
+
'Vedova Nera': {
|
| 49 |
+
'mean': [5, 7, 8, 6, 2],
|
| 50 |
+
'std': [0.5, 0.5, 0.5, 0.5, 0.5]
|
| 51 |
+
},
|
| 52 |
+
'Tempesta': {
|
| 53 |
+
'mean': [6, 7, 8, 6, 9],
|
| 54 |
+
'std': [0.5, 0.5, 0.5, 0.5, 0.5]
|
| 55 |
+
},
|
| 56 |
+
'Supergirl': {
|
| 57 |
+
'mean': [10, 10, 8, 10, 9],
|
| 58 |
+
'std': [0.5, 0.5, 0.5, 0.5, 0.5]
|
| 59 |
+
},
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
# Generate synthetic data for each superhero with non-linear relationships
|
| 63 |
+
for idx, hero in enumerate(superheroes):
|
| 64 |
+
start = idx * N_per_class
|
| 65 |
+
end = (idx + 1) * N_per_class
|
| 66 |
+
means = superhero_stats[hero]['mean']
|
| 67 |
+
stds = superhero_stats[hero]['std']
|
| 68 |
+
X_hero = np.random.normal(means, stds, (N_per_class, D))
|
| 69 |
+
# Ensure feature values are within reasonable ranges before computing interaction
|
| 70 |
+
X_hero = np.clip(X_hero, 1, 10)
|
| 71 |
+
# Introduce non-linear feature interactions
|
| 72 |
+
interaction_term = np.sin(X_hero[:, 1]) * np.log(X_hero[:, 4]) # Interaction between Speed and Energy Projection
|
| 73 |
+
X_hero = np.hstack((X_hero, interaction_term.reshape(-1, 1)))
|
| 74 |
+
X[start:end] = X_hero
|
| 75 |
+
y[start:end] = idx
|
| 76 |
+
|
| 77 |
+
# Ensure all feature values are within reasonable ranges
|
| 78 |
+
X[:, :D] = np.clip(X[:, :D], 1, 10)
|
| 79 |
+
|
| 80 |
+
# Shuffle the dataset
|
| 81 |
+
X, y = shuffle(X, y, random_state=42)
|
| 82 |
+
|
| 83 |
+
# Normalize the features
|
| 84 |
+
scaler = StandardScaler()
|
| 85 |
+
X = scaler.fit_transform(X)
|
| 86 |
+
|
| 87 |
+
# Split data into training and test sets
|
| 88 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 89 |
+
X, y, test_size=0.2, random_state=42)
|
| 90 |
+
|
| 91 |
+
# Convert data to torch tensors
|
| 92 |
+
X_train_tensor = torch.from_numpy(X_train).float()
|
| 93 |
+
y_train_tensor = torch.from_numpy(y_train).long()
|
| 94 |
+
X_test_tensor = torch.from_numpy(X_test).float()
|
| 95 |
+
y_test_tensor = torch.from_numpy(y_test).long()
|
| 96 |
+
|
| 97 |
+
# Random prediction function
|
| 98 |
+
def random_prediction(X):
|
| 99 |
+
num_samples = X.shape[0]
|
| 100 |
+
random_preds = np.random.randint(num_classes, size=num_samples)
|
| 101 |
+
return random_preds
|
| 102 |
+
|
| 103 |
+
# Random prediction and evaluation
|
| 104 |
+
random_preds = random_prediction(X_test)
|
| 105 |
+
random_accuracy = (random_preds == y_test).sum() / y_test.size
|
| 106 |
+
|
| 107 |
+
# Define Linear Model
|
| 108 |
+
class LinearModel(nn.Module):
|
| 109 |
+
def __init__(self, input_dim, output_dim):
|
| 110 |
+
super(LinearModel, self).__init__()
|
| 111 |
+
self.linear = nn.Linear(input_dim, output_dim)
|
| 112 |
+
|
| 113 |
+
def forward(self, x):
|
| 114 |
+
return self.linear(x)
|
| 115 |
+
|
| 116 |
+
# Initialize Linear Model
|
| 117 |
+
input_dim = total_features
|
| 118 |
+
output_dim = num_classes
|
| 119 |
+
linear_model = LinearModel(input_dim, output_dim)
|
| 120 |
+
|
| 121 |
+
# Loss and optimizer for Linear Model
|
| 122 |
+
criterion = nn.CrossEntropyLoss()
|
| 123 |
+
optimizer = optim.SGD(linear_model.parameters(), lr=0.01, weight_decay=1e-4)
|
| 124 |
+
|
| 125 |
+
# Training the Linear Model
|
| 126 |
+
num_epochs = 1#00
|
| 127 |
+
for epoch in range(num_epochs):
|
| 128 |
+
linear_model.train()
|
| 129 |
+
outputs = linear_model(X_train_tensor)
|
| 130 |
+
loss = criterion(outputs, y_train_tensor)
|
| 131 |
+
optimizer.zero_grad()
|
| 132 |
+
loss.backward()
|
| 133 |
+
optimizer.step()
|
| 134 |
+
if (epoch + 1) % 25 == 0:
|
| 135 |
+
st.write('Modello Lineare - Epoch [{}/{}], Loss: {:.4f}'.format(
|
| 136 |
+
epoch + 1, num_epochs, loss.item()))
|
| 137 |
+
|
| 138 |
+
# Evaluate Linear Model
|
| 139 |
+
linear_model.eval()
|
| 140 |
+
with torch.no_grad():
|
| 141 |
+
outputs = linear_model(X_test_tensor)
|
| 142 |
+
_, predicted = torch.max(outputs.data, 1)
|
| 143 |
+
linear_accuracy = (predicted == y_test_tensor).sum().item() / y_test_tensor.size(0)
|
| 144 |
+
|
| 145 |
+
# Define Neural Network Model with regularization
|
| 146 |
+
class NeuralNet(nn.Module):
|
| 147 |
+
def __init__(self, input_dim, hidden_dims, output_dim):
|
| 148 |
+
super(NeuralNet, self).__init__()
|
| 149 |
+
layers = []
|
| 150 |
+
in_dim = input_dim
|
| 151 |
+
for h_dim in hidden_dims:
|
| 152 |
+
layers.append(nn.Linear(in_dim, h_dim))
|
| 153 |
+
layers.append(nn.ReLU())
|
| 154 |
+
layers.append(nn.BatchNorm1d(h_dim))
|
| 155 |
+
layers.append(nn.Dropout(0.3))
|
| 156 |
+
in_dim = h_dim
|
| 157 |
+
layers.append(nn.Linear(in_dim, output_dim))
|
| 158 |
+
self.model = nn.Sequential(*layers)
|
| 159 |
+
|
| 160 |
+
def forward(self, x):
|
| 161 |
+
return self.model(x)
|
| 162 |
+
|
| 163 |
+
# Initialize Neural Network Model
|
| 164 |
+
hidden_dims = [128, 64, 32]
|
| 165 |
+
neural_model = NeuralNet(input_dim, hidden_dims, output_dim)
|
| 166 |
+
|
| 167 |
+
# Loss and optimizer for Neural Network Model
|
| 168 |
+
criterion = nn.CrossEntropyLoss()
|
| 169 |
+
optimizer = optim.Adam(neural_model.parameters(), lr=0.001, weight_decay=1e-4)
|
| 170 |
+
|
| 171 |
+
# Training the Neural Network Model
|
| 172 |
+
num_epochs = 200
|
| 173 |
+
for epoch in range(num_epochs):
|
| 174 |
+
neural_model.train()
|
| 175 |
+
outputs = neural_model(X_train_tensor)
|
| 176 |
+
loss = criterion(outputs, y_train_tensor)
|
| 177 |
+
optimizer.zero_grad()
|
| 178 |
+
loss.backward()
|
| 179 |
+
optimizer.step()
|
| 180 |
+
if (epoch + 1) % 20 == 0:
|
| 181 |
+
st.write('Rete Neurale - Epoch [{}/{}], Loss: {:.4f}'.format(
|
| 182 |
+
epoch + 1, num_epochs, loss.item()))
|
| 183 |
+
|
| 184 |
+
# Evaluate Neural Network Model
|
| 185 |
+
neural_model.eval()
|
| 186 |
+
with torch.no_grad():
|
| 187 |
+
outputs = neural_model(X_test_tensor)
|
| 188 |
+
_, predicted = torch.max(outputs.data, 1)
|
| 189 |
+
neural_accuracy = (predicted == y_test_tensor).sum().item() / y_test_tensor.size(0)
|
| 190 |
+
|
| 191 |
+
# Summary of Accuracies
|
| 192 |
+
st.write("\nRiepilogo delle Accuratezze:....")
|
| 193 |
+
st.error('Accuratezza Previsione Casuale: {:.2f}%'.format(100 * random_accuracy))
|
| 194 |
+
st.warning('Accuratezza Modello Lineare: {:.2f}%'.format(100 * linear_accuracy))
|
| 195 |
+
st.success('Accuratezza Rete Neurale: {:.2f}%'.format(100 * neural_accuracy))
|
| 196 |
+
|
| 197 |
+
return linear_model, neural_model, scaler, superheroes, num_classes
|
| 198 |
+
|
| 199 |
+
def get_user_input_and_predict_female_superhero(linear_model, neural_model, scaler, superheroes, num_classes):
|
| 200 |
+
st.write("Adjust the sliders for the following superhero attributes on a scale from 1 to 10:")
|
| 201 |
+
|
| 202 |
+
# Feature names corresponding to superhero attributes
|
| 203 |
+
feature_names = ['Forza', 'Velocità', 'Intelligenza', 'Resistenza', 'Proiezione di Energia']
|
| 204 |
+
|
| 205 |
+
# Initialize or retrieve user input from session state to preserve the values across reruns
|
| 206 |
+
if 'user_features' not in st.session_state:
|
| 207 |
+
st.session_state.user_features = [5] * len(feature_names) # Default slider values set to 5
|
| 208 |
+
|
| 209 |
+
# Create a form to group sliders and button
|
| 210 |
+
with st.form(key='superhero_form'):
|
| 211 |
+
for i, feature in enumerate(feature_names):
|
| 212 |
+
st.session_state.user_features[i] = st.slider(
|
| 213 |
+
feature, 1, 10, st.session_state.user_features[i], key=f'slider_{i}'
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# Form submission button
|
| 217 |
+
submit_button = st.form_submit_button(label='Calcola Previsioni')
|
| 218 |
+
|
| 219 |
+
# Proceed with prediction if the form is submitted
|
| 220 |
+
if submit_button:
|
| 221 |
+
# Copy user input values (superhero attributes)
|
| 222 |
+
user_features = st.session_state.user_features.copy()
|
| 223 |
+
|
| 224 |
+
# Calculate interaction term (interaction between Speed and Energy Projection)
|
| 225 |
+
interaction_term = np.sin(user_features[1]) * np.log(user_features[4])
|
| 226 |
+
|
| 227 |
+
# Append the interaction term to the original features
|
| 228 |
+
user_features.append(interaction_term)
|
| 229 |
+
|
| 230 |
+
# Convert to numpy array and reshape to match the expected input shape
|
| 231 |
+
user_features = np.array(user_features).reshape(1, -1)
|
| 232 |
+
|
| 233 |
+
# Normalize user inputs using the scaler that was fit during training
|
| 234 |
+
user_features_scaled = scaler.transform(user_features)
|
| 235 |
+
|
| 236 |
+
# Convert the scaled input into a torch tensor
|
| 237 |
+
user_tensor = torch.from_numpy(user_features_scaled).float()
|
| 238 |
+
|
| 239 |
+
# Make a random prediction for comparison
|
| 240 |
+
random_pred = np.random.randint(num_classes)
|
| 241 |
+
st.error(f"Previsione Casuale: {superheroes[random_pred]}")
|
| 242 |
+
|
| 243 |
+
# **Linear Model Prediction**
|
| 244 |
+
linear_model.eval() # Set model to evaluation mode
|
| 245 |
+
with torch.no_grad():
|
| 246 |
+
outputs = linear_model(user_tensor)
|
| 247 |
+
_, predicted = torch.max(outputs.data, 1)
|
| 248 |
+
linear_pred = predicted.item()
|
| 249 |
+
st.warning(f"Previsione Modello Lineare: {superheroes[linear_pred]}")
|
| 250 |
+
|
| 251 |
+
# **Neural Network Prediction**
|
| 252 |
+
neural_model.eval() # Set model to evaluation mode
|
| 253 |
+
with torch.no_grad():
|
| 254 |
+
outputs = neural_model(user_tensor)
|
| 255 |
+
_, predicted = torch.max(outputs.data, 1)
|
| 256 |
+
neural_pred = predicted.item()
|
| 257 |
+
st.success(f"Previsione Rete Neurale: {superheroes[neural_pred]}")
|
app.py
CHANGED
|
@@ -8,51 +8,107 @@ from sklearn.preprocessing import StandardScaler
|
|
| 8 |
from sklearn.linear_model import LogisticRegression
|
| 9 |
from sklearn.model_selection import train_test_split
|
| 10 |
|
| 11 |
-
from NdR_disease import run_disease_train,
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
if 'button_clicked' not in st.session_state:
|
| 14 |
-
st.session_state.button_clicked = False
|
| 15 |
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
st.write("Training Male Superhero model...")
|
| 20 |
-
# Male superhero training logic goes here
|
| 21 |
-
# Add dummy print statements as a placeholder
|
| 22 |
-
st.write("Male superhero model - Step 1: Data prepared.")
|
| 23 |
-
st.write("Male superhero model - Step 2: Model trained.")
|
| 24 |
-
st.write("Male superhero model - Step 3: Results evaluated.")
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
#
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
if st.button("Run Disease Task"):
|
| 57 |
-
linear_model, neural_model, scaler, conditions, num_classes = run_disease_train()
|
| 58 |
-
get_user_input_and_predict(linear_model, neural_model, scaler, conditions, num_classes)
|
|
|
|
| 8 |
from sklearn.linear_model import LogisticRegression
|
| 9 |
from sklearn.model_selection import train_test_split
|
| 10 |
|
| 11 |
+
from NdR_disease import run_disease_train, get_user_input_and_predict_disease
|
| 12 |
+
from NdR_female_superheros import run_female_superhero_train, get_user_input_and_predict_female_superhero
|
| 13 |
+
from NdR_male_superheros import run_male_superhero_train, get_user_input_and_predict_male_superhero
|
| 14 |
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
# Interfaccia utente Streamlit
|
| 17 |
+
st.title("Demo: Intelligenza Artificiale")
|
| 18 |
|
| 19 |
+
# Pulsanti di selezione del attività
|
| 20 |
+
task = st.selectbox("Scegli una attività:", ("Supereroe", "Malattie"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
if task == "Supereroe":
|
| 23 |
+
# Sotto-opzioni per Supereroe Maschile e Femminile
|
| 24 |
+
gender = st.selectbox("Scegli il genere:", ("Maschile", "Femminile"))
|
| 25 |
|
| 26 |
+
if gender == "Maschile":
|
| 27 |
+
if 'malesuper_models' not in st.session_state:
|
| 28 |
+
if st.button("Avvia attività Supereroe Maschile"):
|
| 29 |
+
# Carica i modelli e salvali nello stato di sessione
|
| 30 |
+
linear_model, neural_model, scaler, superheros, num_classes = run_male_superhero_train()
|
| 31 |
+
st.session_state.malesuper_models = {
|
| 32 |
+
'linear_model': linear_model,
|
| 33 |
+
'neural_model': neural_model,
|
| 34 |
+
'scaler': scaler,
|
| 35 |
+
'superheros': superheros,
|
| 36 |
+
'num_classes': num_classes
|
| 37 |
+
}
|
| 38 |
+
else:
|
| 39 |
+
st.write("I modelli di Supereroe Maschile sono già caricati.")
|
| 40 |
|
| 41 |
+
# Se i modelli sono caricati, ottieni input dall'utente e fai una previsione
|
| 42 |
+
if 'malesuper_models' in st.session_state:
|
| 43 |
+
models = st.session_state.malesuper_models
|
| 44 |
+
get_user_input_and_predict_male_superhero(
|
| 45 |
+
models['linear_model'],
|
| 46 |
+
models['neural_model'],
|
| 47 |
+
models['scaler'],
|
| 48 |
+
models['superheros'],
|
| 49 |
+
models['num_classes']
|
| 50 |
+
)
|
| 51 |
+
else:
|
| 52 |
+
st.write("Clicca 'Avvia attività Supereroe Maschile' per caricare i modelli.")
|
| 53 |
|
| 54 |
+
elif gender == "Femminile":
|
| 55 |
+
if 'femalesuper_models' not in st.session_state:
|
| 56 |
+
if st.button("Avvia attività Supereroe Femminile"):
|
| 57 |
+
# Carica i modelli e salvali nello stato di sessione
|
| 58 |
+
linear_model, neural_model, scaler, superheros, num_classes = run_female_superhero_train()
|
| 59 |
+
st.session_state.femalesuper_models = {
|
| 60 |
+
'linear_model': linear_model,
|
| 61 |
+
'neural_model': neural_model,
|
| 62 |
+
'scaler': scaler,
|
| 63 |
+
'superheros': superheros,
|
| 64 |
+
'num_classes': num_classes
|
| 65 |
+
}
|
| 66 |
+
else:
|
| 67 |
+
st.write("I modelli di Supereroe Femminile sono già caricati.")
|
| 68 |
|
| 69 |
+
# Se i modelli sono caricati, ottieni input dall'utente e fai una previsione
|
| 70 |
+
if 'femalesuper_models' in st.session_state:
|
| 71 |
+
models = st.session_state.femalesuper_models
|
| 72 |
+
get_user_input_and_predict_female_superhero(
|
| 73 |
+
models['linear_model'],
|
| 74 |
+
models['neural_model'],
|
| 75 |
+
models['scaler'],
|
| 76 |
+
models['superheros'],
|
| 77 |
+
models['num_classes']
|
| 78 |
+
)
|
| 79 |
+
else:
|
| 80 |
+
st.write("Clicca 'Avvia attività Supereroe Femminile' per caricare i modelli.")
|
| 81 |
|
| 82 |
+
elif task == "Malattie":
|
| 83 |
+
if 'disease_models' not in st.session_state:
|
| 84 |
+
if st.button("Avvia attività Malattie"):
|
| 85 |
+
# Carica i modelli e salvali nello stato di sessione
|
| 86 |
+
linear_model, neural_model, scaler, conditions, num_classes = run_disease_train()
|
| 87 |
+
st.session_state.disease_models = {
|
| 88 |
+
'linear_model': linear_model,
|
| 89 |
+
'neural_model': neural_model,
|
| 90 |
+
'scaler': scaler,
|
| 91 |
+
'conditions': conditions,
|
| 92 |
+
'num_classes': num_classes
|
| 93 |
+
}
|
| 94 |
+
else:
|
| 95 |
+
st.write("I modelli di malattie sono già caricati.")
|
| 96 |
|
| 97 |
+
# Se i modelli sono caricati, ottieni input dall'utente e fai una previsione
|
| 98 |
+
if 'disease_models' in st.session_state:
|
| 99 |
+
models = st.session_state.disease_models
|
| 100 |
+
get_user_input_and_predict_disease(
|
| 101 |
+
models['linear_model'],
|
| 102 |
+
models['neural_model'],
|
| 103 |
+
models['scaler'],
|
| 104 |
+
models['conditions'],
|
| 105 |
+
models['num_classes']
|
| 106 |
+
)
|
| 107 |
+
else:
|
| 108 |
+
st.write("Clicca 'Avvia attività Malattie' per caricare i modelli.")
|
| 109 |
|
| 110 |
+
if st.button('Ripristina'):
|
| 111 |
+
# Cancella solo lo stato di invio del modulo e gli input dell'utente
|
| 112 |
+
for key in list(st.session_state.keys()):
|
| 113 |
+
del st.session_state[key]
|
| 114 |
+
st.rerun()
|
|
|
|
|
|
|
|
|