eaglelandsonce commited on
Commit
95c53c2
·
verified ·
1 Parent(s): 3902c26

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +218 -0
app.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
+ import streamlit as st
4
+ import pandas as pd
5
+ import numpy as np
6
+ from sklearn.ensemble import RandomForestClassifier
7
+ from sklearn.model_selection import train_test_split
8
+ from sklearn.metrics import accuracy_score, roc_curve, auc
9
+ from sklearn.decomposition import PCA
10
+ import matplotlib.pyplot as plt
11
+ import seaborn as sns
12
+
13
+ # Set random seed for reproducibility
14
+ np.random.seed(42)
15
+
16
+ # Title of the app
17
+ st.title('Breast Cancer Treatment Outcome Prediction')
18
+
19
+ st.markdown("""
20
+ This Streamlit app simulates a precision medicine system that predicts the effectiveness of treatment for breast cancer patients based on clinical and genomic data.
21
+
22
+ **Disclaimer:** This is a simulation using synthetic data and is intended for educational purposes only. It should not be used for clinical decision-making.
23
+ """)
24
+
25
+ # --- Data Simulation ---
26
+
27
+ st.header('1. Data Simulation')
28
+
29
+ # Simulate clinical data
30
+ num_samples = 500
31
+ age = np.random.randint(30, 80, num_samples)
32
+ tumor_size = np.random.uniform(0.5, 5.0, num_samples)
33
+ lymph_nodes = np.random.randint(0, 10, num_samples)
34
+ tumor_grade = np.random.randint(1, 4, num_samples) # Grades 1 to 3
35
+ er_status = np.random.choice([0, 1], num_samples) # Estrogen Receptor status
36
+ pr_status = np.random.choice([0, 1], num_samples) # Progesterone Receptor status
37
+ her2_status = np.random.choice([0, 1], num_samples) # HER2 status
38
+
39
+ # Simulate genomic data (expression levels of 50 genes)
40
+ gene_expression = np.random.normal(0, 1, (num_samples, 50))
41
+
42
+ # Simulate treatment outcomes (0 = non-responsive, 1 = responsive)
43
+ outcome = (
44
+ (er_status == 1) &
45
+ (pr_status == 1) &
46
+ (her2_status == 0) &
47
+ (tumor_grade < 3) &
48
+ (tumor_size < 2.5)
49
+ ).astype(int)
50
+
51
+ # Create a DataFrame for clinical data
52
+ clinical_data = pd.DataFrame({
53
+ 'Age': age,
54
+ 'Tumor_Size': tumor_size,
55
+ 'Lymph_Nodes': lymph_nodes,
56
+ 'Tumor_Grade': tumor_grade,
57
+ 'ER_Status': er_status,
58
+ 'PR_Status': pr_status,
59
+ 'HER2_Status': her2_status,
60
+ 'Outcome': outcome
61
+ })
62
+
63
+ # Create a DataFrame for genomic data
64
+ gene_columns = [f'Gene_{i}' for i in range(1, 51)]
65
+ genomic_data = pd.DataFrame(gene_expression, columns=gene_columns)
66
+
67
+ # Combine clinical and genomic data
68
+ data = pd.concat([clinical_data, genomic_data], axis=1)
69
+
70
+ st.write('Simulated Data Preview:')
71
+ st.dataframe(data.head())
72
+
73
+ # --- Exploratory Data Analysis (EDA) ---
74
+
75
+ st.header('2. Exploratory Data Analysis')
76
+
77
+ # Correlation Matrix
78
+ st.subheader('Correlation Matrix')
79
+ corr = data.corr()
80
+ fig_corr, ax_corr = plt.subplots(figsize=(10, 8))
81
+ sns.heatmap(corr.iloc[:8, :8], annot=True, fmt=".2f", cmap='coolwarm', ax=ax_corr)
82
+ st.pyplot(fig_corr)
83
+
84
+ # Outcome Distribution
85
+ st.subheader('Outcome Distribution')
86
+ st.bar_chart(data['Outcome'].value_counts())
87
+
88
+ # --- Feature Selection ---
89
+
90
+ st.header('3. Feature Selection and Preprocessing')
91
+
92
+ # Features and Labels
93
+ features = data.drop('Outcome', axis=1)
94
+ labels = data['Outcome']
95
+
96
+ # Optional: Dimensionality Reduction on Genomic Data
97
+ pca_genes = PCA(n_components=5)
98
+ genes_pca = pca_genes.fit_transform(genomic_data)
99
+
100
+ # Create a new DataFrame with PCA components
101
+ genes_pca_df = pd.DataFrame(genes_pca, columns=[f'PC{i}' for i in range(1, 6)])
102
+
103
+ # Combine clinical data with PCA components
104
+ features_pca = pd.concat([clinical_data.drop('Outcome', axis=1), genes_pca_df], axis=1)
105
+
106
+ st.write('Features after PCA on Genomic Data:')
107
+ st.dataframe(features_pca.head())
108
+
109
+ # --- Model Development ---
110
+
111
+ st.header('4. Model Development and Evaluation')
112
+
113
+ # Split the data
114
+ X_train, X_test, y_train, y_test = train_test_split(features_pca, labels, test_size=0.2, random_state=42)
115
+
116
+ # Model Training
117
+ model = RandomForestClassifier(n_estimators=100, random_state=42)
118
+ model.fit(X_train, y_train)
119
+
120
+ # Model Prediction
121
+ y_pred = model.predict(X_test)
122
+ accuracy = accuracy_score(y_test, y_pred)
123
+
124
+ st.subheader('Model Accuracy')
125
+ st.write(f'Accuracy on test set: **{accuracy * 100:.2f}%**')
126
+
127
+ # ROC Curve
128
+ st.subheader('ROC Curve')
129
+ y_score = model.predict_proba(X_test)[:, 1]
130
+ fpr, tpr, thresholds = roc_curve(y_test, y_score)
131
+ roc_auc = auc(fpr, tpr)
132
+
133
+ fig_roc, ax_roc = plt.subplots()
134
+ ax_roc.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.2f})')
135
+ ax_roc.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
136
+ ax_roc.set_xlim([0.0, 1.0])
137
+ ax_roc.set_ylim([0.0, 1.05])
138
+ ax_roc.set_xlabel('False Positive Rate')
139
+ ax_roc.set_ylabel('True Positive Rate')
140
+ ax_roc.set_title('Receiver Operating Characteristic')
141
+ ax_roc.legend(loc='lower right')
142
+ st.pyplot(fig_roc)
143
+
144
+ # --- User Input Interface ---
145
+
146
+ st.header('5. Predictive Simulation')
147
+
148
+ st.sidebar.header('Input Patient Parameters')
149
+
150
+ def user_input_features():
151
+ age = st.sidebar.slider('Age', 30, 80, 50)
152
+ tumor_size = st.sidebar.slider('Tumor Size (cm)', 0.5, 5.0, 2.0)
153
+ lymph_nodes = st.sidebar.slider('Number of Lymph Nodes', 0, 10, 2)
154
+ tumor_grade = st.sidebar.selectbox('Tumor Grade', [1, 2, 3])
155
+ er_status = st.sidebar.selectbox('Estrogen Receptor Status (ER)', [0, 1])
156
+ pr_status = st.sidebar.selectbox('Progesterone Receptor Status (PR)', [0, 1])
157
+ her2_status = st.sidebar.selectbox('HER2 Status', [0, 1])
158
+
159
+ # Simulate gene expression levels for PCA components
160
+ gene_inputs = np.random.normal(0, 1, (1, 50))
161
+ genes_pca_input = pca_genes.transform(gene_inputs)
162
+ genes_pca_input_df = pd.DataFrame(genes_pca_input, columns=[f'PC{i}' for i in range(1, 6)])
163
+
164
+ data_input = pd.DataFrame({
165
+ 'Age': [age],
166
+ 'Tumor_Size': [tumor_size],
167
+ 'Lymph_Nodes': [lymph_nodes],
168
+ 'Tumor_Grade': [tumor_grade],
169
+ 'ER_Status': [er_status],
170
+ 'PR_Status': [pr_status],
171
+ 'HER2_Status': [her2_status]
172
+ })
173
+
174
+ features_input = pd.concat([data_input, genes_pca_input_df], axis=1)
175
+ return features_input
176
+
177
+ input_df = user_input_features()
178
+
179
+ st.subheader('Input Parameters')
180
+ st.write(input_df)
181
+
182
+ # Prediction
183
+ prediction = model.predict(input_df)
184
+ prediction_proba = model.predict_proba(input_df)
185
+
186
+ st.subheader('Prediction Outcome')
187
+ outcome_label = np.array(['Non-Responsive', 'Responsive'])
188
+ st.write(f'The model predicts that the patient is: **{outcome_label[prediction][0]}**')
189
+
190
+ st.subheader('Prediction Probability')
191
+ st.write(f'Probability of being Responsive: **{prediction_proba[0][1] * 100:.2f}%**')
192
+
193
+ # --- Feature Importance ---
194
+
195
+ st.header('6. Model Interpretation')
196
+
197
+ st.subheader('Feature Importances')
198
+ importances = model.feature_importances_
199
+ indices = np.argsort(importances)[::-1]
200
+ feature_names = features_pca.columns
201
+
202
+ fig_fi, ax_fi = plt.subplots()
203
+ ax_fi.bar(range(len(importances)), importances[indices], color='r', align='center')
204
+ ax_fi.set_xticks(range(len(importances)))
205
+ ax_fi.set_xticklabels(feature_names[indices], rotation=90)
206
+ ax_fi.set_title('Feature Importances')
207
+ ax_fi.set_ylabel('Importance Score')
208
+ st.pyplot(fig_fi)
209
+
210
+ # --- Conclusion ---
211
+
212
+ st.header('7. Conclusion')
213
+
214
+ st.markdown("""
215
+ This simulation demonstrates how integrating clinical and genomic data can aid in predicting breast cancer treatment outcomes. By adjusting the input parameters, you can see how different factors influence the prediction.
216
+
217
+ **Note:** This app uses synthetic data and a basic machine learning model. For real-world applications, a more sophisticated approach with validated data and models is required.
218
+ """)