PMed / app.py
eaglelandsonce's picture
Update app.py
3f25d71 verified
# app.py
import sklearn
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_curve, auc
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import seaborn as sns
# Set random seed for reproducibility
np.random.seed(42)
# Title of the app
st.title('Breast Cancer Treatment Outcome Prediction')
st.markdown("""
This Streamlit app simulates a precision medicine system that predicts the effectiveness of treatment for breast cancer patients based on clinical and genomic data.
**Disclaimer:** This is a simulation using synthetic data and is intended for educational purposes only. It should not be used for clinical decision-making.
""")
# --- Data Simulation --
st.header('1. Data Simulation')
# Simulate clinical data
num_samples = 500
age = np.random.randint(30, 80, num_samples)
tumor_size = np.random.uniform(0.5, 5.0, num_samples)
lymph_nodes = np.random.randint(0, 10, num_samples)
tumor_grade = np.random.randint(1, 4, num_samples) # Grades 1 to 3
er_status = np.random.choice([0, 1], num_samples) # Estrogen Receptor status
pr_status = np.random.choice([0, 1], num_samples) # Progesterone Receptor status
her2_status = np.random.choice([0, 1], num_samples) # HER2 status
# Simulate genomic data (expression levels of 50 genes)
gene_expression = np.random.normal(0, 1, (num_samples, 50))
# Simulate treatment outcomes (0 = non-responsive, 1 = responsive)
outcome = (
(er_status == 1) &
(pr_status == 1) &
(her2_status == 0) &
(tumor_grade < 3) &
(tumor_size < 2.5)
).astype(int)
# Create a DataFrame for clinical data
clinical_data = pd.DataFrame({
'Age': age,
'Tumor_Size': tumor_size,
'Lymph_Nodes': lymph_nodes,
'Tumor_Grade': tumor_grade,
'ER_Status': er_status,
'PR_Status': pr_status,
'HER2_Status': her2_status,
'Outcome': outcome
})
# Create a DataFrame for genomic data
gene_columns = [f'Gene_{i}' for i in range(1, 51)]
genomic_data = pd.DataFrame(gene_expression, columns=gene_columns)
# Combine clinical and genomic data
data = pd.concat([clinical_data, genomic_data], axis=1)
st.write('Simulated Data Preview:')
st.dataframe(data.head())
# --- Exploratory Data Analysis (EDA) ---
st.header('2. Exploratory Data Analysis')
# Correlation Matrix
st.subheader('Correlation Matrix')
corr = data.corr()
fig_corr, ax_corr = plt.subplots(figsize=(10, 8))
sns.heatmap(corr.iloc[:8, :8], annot=True, fmt=".2f", cmap='coolwarm', ax=ax_corr)
st.pyplot(fig_corr)
# Outcome Distribution
st.subheader('Outcome Distribution')
st.bar_chart(data['Outcome'].value_counts())
# --- Feature Selection ---
st.header('3. Feature Selection and Preprocessing')
# Features and Labels
features = data.drop('Outcome', axis=1)
labels = data['Outcome']
# Optional: Dimensionality Reduction on Genomic Data
pca_genes = PCA(n_components=5)
genes_pca = pca_genes.fit_transform(genomic_data)
# Create a new DataFrame with PCA components
genes_pca_df = pd.DataFrame(genes_pca, columns=[f'PC{i}' for i in range(1, 6)])
# Combine clinical data with PCA components
features_pca = pd.concat([clinical_data.drop('Outcome', axis=1), genes_pca_df], axis=1)
st.write('Features after PCA on Genomic Data:')
st.dataframe(features_pca.head())
# --- Model Development ---
st.header('4. Model Development and Evaluation')
# Split the data
X_train, X_test, y_train, y_test = train_test_split(features_pca, labels, test_size=0.2, random_state=42)
# Model Training
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Model Prediction
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
st.subheader('Model Accuracy')
st.write(f'Accuracy on test set: **{accuracy * 100:.2f}%**')
# ROC Curve
st.subheader('ROC Curve')
y_score = model.predict_proba(X_test)[:, 1]
fpr, tpr, thresholds = roc_curve(y_test, y_score)
roc_auc = auc(fpr, tpr)
fig_roc, ax_roc = plt.subplots()
ax_roc.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC curve (AUC = {roc_auc:.2f})')
ax_roc.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
ax_roc.set_xlim([0.0, 1.0])
ax_roc.set_ylim([0.0, 1.05])
ax_roc.set_xlabel('False Positive Rate')
ax_roc.set_ylabel('True Positive Rate')
ax_roc.set_title('Receiver Operating Characteristic')
ax_roc.legend(loc='lower right')
st.pyplot(fig_roc)
# --- User Input Interface ---
st.header('5. Predictive Simulation')
st.sidebar.header('Input Patient Parameters')
def user_input_features():
age = st.sidebar.slider('Age', 30, 80, 50)
tumor_size = st.sidebar.slider('Tumor Size (cm)', 0.5, 5.0, 2.0)
lymph_nodes = st.sidebar.slider('Number of Lymph Nodes', 0, 10, 2)
tumor_grade = st.sidebar.selectbox('Tumor Grade', [1, 2, 3])
er_status = st.sidebar.selectbox('Estrogen Receptor Status (ER)', [0, 1])
pr_status = st.sidebar.selectbox('Progesterone Receptor Status (PR)', [0, 1])
her2_status = st.sidebar.selectbox('HER2 Status', [0, 1])
# Simulate gene expression levels for PCA components
gene_inputs = np.random.normal(0, 1, (1, 50))
genes_pca_input = pca_genes.transform(gene_inputs)
genes_pca_input_df = pd.DataFrame(genes_pca_input, columns=[f'PC{i}' for i in range(1, 6)])
data_input = pd.DataFrame({
'Age': [age],
'Tumor_Size': [tumor_size],
'Lymph_Nodes': [lymph_nodes],
'Tumor_Grade': [tumor_grade],
'ER_Status': [er_status],
'PR_Status': [pr_status],
'HER2_Status': [her2_status]
})
features_input = pd.concat([data_input, genes_pca_input_df], axis=1)
return features_input
input_df = user_input_features()
st.subheader('Input Parameters')
st.write(input_df)
# Prediction
prediction = model.predict(input_df)
prediction_proba = model.predict_proba(input_df)
st.subheader('Prediction Outcome')
outcome_label = np.array(['Non-Responsive', 'Responsive'])
st.write(f'The model predicts that the patient is: **{outcome_label[prediction][0]}**')
st.subheader('Prediction Probability')
st.write(f'Probability of being Responsive: **{prediction_proba[0][1] * 100:.2f}%**')
# --- Feature Importance ---
st.header('6. Model Interpretation')
st.subheader('Feature Importances')
importances = model.feature_importances_
indices = np.argsort(importances)[::-1]
feature_names = features_pca.columns
fig_fi, ax_fi = plt.subplots()
ax_fi.bar(range(len(importances)), importances[indices], color='r', align='center')
ax_fi.set_xticks(range(len(importances)))
ax_fi.set_xticklabels(feature_names[indices], rotation=90)
ax_fi.set_title('Feature Importances')
ax_fi.set_ylabel('Importance Score')
st.pyplot(fig_fi)
# --- Conclusion ---
st.header('7. Conclusion')
st.markdown("""
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.
**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.
""")