Anupam202224 commited on
Commit
5f741a4
·
verified ·
1 Parent(s): 6bda259

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -0
app.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import gradio as gr
4
+ from sklearn.preprocessing import StandardScaler
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.ensemble import RandomForestClassifier
7
+ from sklearn.metrics import accuracy_score, classification_report
8
+ import joblib
9
+
10
+ # Generate more realistic synthetic genetic data
11
+ def generate_realistic_genetic_data(n_samples=1000):
12
+ np.random.seed(42)
13
+
14
+ # Define genetic markers associated with different conditions
15
+ # Marker ranges based on typical genetic variation patterns
16
+ genetic_data = {
17
+ 'BRCA1_mutation': np.random.choice([0, 1], size=n_samples, p=[0.95, 0.05]), # BRCA1 mutation
18
+ 'P53_variation': np.random.normal(0.5, 0.1, n_samples), # P53 tumor suppressor variation
19
+ 'APOE_allele': np.random.choice([2, 3, 4], size=n_samples, p=[0.1, 0.7, 0.2]), # APOE allele types
20
+ 'DNA_methylation': np.random.beta(2, 5, n_samples), # DNA methylation levels
21
+ 'telomere_length': np.random.normal(6000, 1000, n_samples), # Telomere length
22
+ 'CYP2D6_activity': np.random.gamma(2, 2, n_samples), # CYP2D6 enzyme activity
23
+ 'inflammatory_markers': np.random.exponential(2, n_samples), # Inflammatory markers
24
+ 'glucose_metabolism': np.random.normal(100, 15, n_samples), # Glucose metabolism
25
+ 'oxidative_stress': np.random.gamma(3, 1, n_samples), # Oxidative stress levels
26
+ 'immune_response': np.random.normal(0.7, 0.1, n_samples) # Immune response strength
27
+ }
28
+
29
+ # Create DataFrame
30
+ df = pd.DataFrame(genetic_data)
31
+
32
+ # Generate disease status based on complex interactions
33
+ disease_probability = (
34
+ 0.3 * genetic_data['BRCA1_mutation'] +
35
+ 0.2 * (genetic_data['P53_variation'] > 0.7) +
36
+ 0.15 * (genetic_data['APOE_allele'] == 4) +
37
+ 0.1 * (genetic_data['DNA_methylation'] > 0.6) +
38
+ 0.05 * (genetic_data['telomere_length'] < 5000) +
39
+ 0.1 * (genetic_data['CYP2D6_activity'] > 5) +
40
+ 0.05 * (genetic_data['inflammatory_markers'] > 3) +
41
+ 0.05 * (genetic_data['glucose_metabolism'] > 120)
42
+ )
43
+
44
+ df['disease'] = (disease_probability > 0.5).astype(int)
45
+
46
+ return df
47
+
48
+ # Data preprocessing
49
+ def preprocess_data(data):
50
+ X = data.drop('disease', axis=1)
51
+ y = data['disease']
52
+
53
+ scaler = StandardScaler()
54
+ X_scaled = scaler.fit_transform(X)
55
+
56
+ return X_scaled, y, scaler
57
+
58
+ # Train and evaluate model
59
+ def train_and_evaluate_model():
60
+ # Generate and preprocess data
61
+ print("Generating synthetic genetic data...")
62
+ data = generate_realistic_genetic_data(1500)
63
+ print("\nData Sample:")
64
+ print(data.head())
65
+ print("\nData Statistics:")
66
+ print(data.describe())
67
+
68
+ # Preprocess data
69
+ X_scaled, y, scaler = preprocess_data(data)
70
+
71
+ # Split data
72
+ X_train, X_test, y_train, y_test = train_test_split(
73
+ X_scaled, y, test_size=0.2, random_state=42
74
+ )
75
+
76
+ # Train model
77
+ print("\nTraining Random Forest model...")
78
+ model = RandomForestClassifier(
79
+ n_estimators=100,
80
+ max_depth=5,
81
+ random_state=42
82
+ )
83
+ model.fit(X_train, y_train)
84
+
85
+ # Evaluate model
86
+ y_pred = model.predict(X_test)
87
+ accuracy = accuracy_score(y_test, y_pred)
88
+ print("\nModel Evaluation:")
89
+ print(f"Accuracy: {accuracy:.2f}")
90
+ print("\nClassification Report:")
91
+ print(classification_report(y_test, y_pred))
92
+
93
+ # Feature importance
94
+ feature_importance = pd.DataFrame({
95
+ 'feature': data.drop('disease', axis=1).columns,
96
+ 'importance': model.feature_importances_
97
+ })
98
+ print("\nFeature Importance:")
99
+ print(feature_importance.sort_values('importance', ascending=False))
100
+
101
+ return model, scaler
102
+
103
+ # Prediction function
104
+ def predict_disease(
105
+ brca1_mutation, p53_variation, apoe_allele, dna_methylation,
106
+ telomere_length, cyp2d6_activity, inflammatory_markers,
107
+ glucose_metabolism, oxidative_stress, immune_response
108
+ ):
109
+ # Create input array
110
+ input_data = np.array([
111
+ brca1_mutation, p53_variation, apoe_allele, dna_methylation,
112
+ telomere_length, cyp2d6_activity, inflammatory_markers,
113
+ glucose_metabolism, oxidative_stress, immune_response
114
+ ]).reshape(1, -1)
115
+
116
+ # Scale input data
117
+ scaled_data = scaler.transform(input_data)
118
+
119
+ # Make prediction
120
+ prediction = model.predict_proba(scaled_data)[0]
121
+
122
+ return {
123
+ "No Disease": float(prediction[0]),
124
+ "Disease": float(prediction[1])
125
+ }
126
+
127
+ # Train model and get scaler
128
+ print("Training model and preparing interface...")
129
+ model, scaler = train_and_evaluate_model()
130
+
131
+ # Create Gradio interface
132
+ iface = gr.Interface(
133
+ fn=predict_disease,
134
+ inputs=[
135
+ gr.Number(label="BRCA1 Mutation (0 or 1)", value=0),
136
+ gr.Number(label="P53 Variation (typically 0.3-0.7)", value=0.5),
137
+ gr.Number(label="APOE Allele (2, 3, or 4)", value=3),
138
+ gr.Number(label="DNA Methylation (0-1)", value=0.4),
139
+ gr.Number(label="Telomere Length (typically 4000-8000)", value=6000),
140
+ gr.Number(label="CYP2D6 Activity (typically 0-10)", value=4),
141
+ gr.Number(label="Inflammatory Markers (typically 0-10)", value=2),
142
+ gr.Number(label="Glucose Metabolism (typically 70-130)", value=100),
143
+ gr.Number(label="Oxidative Stress (typically 0-10)", value=3),
144
+ gr.Number(label="Immune Response (typically 0.5-0.9)", value=0.7)
145
+ ],
146
+ outputs=gr.Label(label="Disease Prediction"),
147
+ title="Genetic Disease Prediction System",
148
+ description="""This system predicts genetic disease risk based on various genetic markers and biological indicators.
149
+ Please input values within the suggested ranges for accurate predictions.""",
150
+ examples=[
151
+ # High-risk example
152
+ [1, 0.8, 4, 0.7, 4800, 6, 4, 125, 5, 0.6],
153
+ # Low-risk example
154
+ [0, 0.4, 3, 0.3, 6500, 3, 1, 95, 2, 0.8],
155
+ # Moderate-risk example
156
+ [0, 0.6, 3, 0.5, 5500, 4, 2, 110, 3, 0.7]
157
+ ]
158
+ )
159
+
160
+ # Launch the interface
161
+ iface.launch(share=True)