Spaces:
Sleeping
Sleeping
File size: 8,766 Bytes
4b9b315 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 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 57 58 59 60 61 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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import seaborn as sns
# Check for missing values
#Loading Data
data = pd.read_csv('Cardio_Vascular_Disease_by_Gut_Microbiota.csv')
print(data.head())
from sklearn.ensemble import RandomForestClassifier
# Define features and target
X = data.drop(columns=['patient_id', 'CVD_Status'])
y = data['CVD_Status']
# Train a RandomForest model
rf = RandomForestClassifier(random_state=42)
rf.fit(X, y)
# Feature importances
importances = rf.feature_importances_
# Plot feature importances
feature_importance_df = pd.DataFrame({'Feature': X.columns, 'Importance': importances})
feature_importance_df = feature_importance_df.sort_values('Importance', ascending=False)
plt.figure(figsize=(10,6))
sns.barplot(x='Importance', y='Feature', data=feature_importance_df)
plt.title('Feature Importance from Random Forest')
plt.show()
from sklearn.ensemble import GradientBoostingClassifier
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.metrics import accuracy_score, confusion_matrix, r2_score, mean_squared_error, mean_absolute_error
from math import sqrt
# Initialize the models
gradient_boosting = GradientBoostingClassifier(random_state=42)
# Split into training and testing sets (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train and evaluate Gradient Boosting
gradient_boosting.fit(X_train, y_train)
y_pred_gb = gradient_boosting.predict(X_test)
accuracy_gb = accuracy_score(y_test, y_pred_gb)
conf_matrix_gb = confusion_matrix(y_test, y_pred_gb)
# Print results
print(f"Gradient Boosting Accuracy: {accuracy_gb * 100:.2f}%")
print(f"Confusion Matrix:\n {conf_matrix_gb}\n")
# Predict probabilities
y_pred_prob_gb = gradient_boosting.predict_proba(X_test)[:, 1]
# Predict class labels
y_pred_gb = gradient_boosting.predict(X_test)
# Calculate R² Score, RMSE, MSE, and MAE for Gradient Boosting
r2_gb = r2_score(y_test, y_pred_prob_gb)
rmse_gb = sqrt(mean_squared_error(y_test, y_pred_prob_gb))
mse_gb = mean_squared_error(y_test, y_pred_prob_gb)
mae_gb = mean_absolute_error(y_test, y_pred_prob_gb)
# Print Accuracy, R², RMSE, MSE, and MAE for Gradient Boosting
print(f"Gradient Boosting Accuracy: {accuracy_gb * 100:.2f}%")
print(f"R² Score: {r2_gb:.4f}, RMSE: {rmse_gb:.4f}, MSE: {mse_gb:.4f}, MAE: {mae_gb:.4f}")
print(f"Confusion Matrix:\n {conf_matrix_gb}\n")
xgboost = XGBClassifier(use_label_encoder=False, eval_metric='logloss', random_state=42)
# Train and evaluate XGBoost
xgboost.fit(X_train, y_train)
y_pred_xgb = xgboost.predict(X_test)
accuracy_xgb = accuracy_score(y_test, y_pred_xgb)
conf_matrix_xgb = confusion_matrix(y_test, y_pred_xgb)
print(f"XGBoost Accuracy: {accuracy_xgb * 100:.2f}%")
print(f"Confusion Matrix:\n {conf_matrix_xgb}\n")
y_pred_prob_xgb = xgboost.predict_proba(X_test)[:, 1]
y_pred_xgb = xgboost.predict(X_test)
# Calculate R² Score, RMSE, MSE, and MAE for XGBoost
r2_xgb = r2_score(y_test, y_pred_prob_xgb)
rmse_xgb = sqrt(mean_squared_error(y_test, y_pred_prob_xgb))
mse_xgb = mean_squared_error(y_test, y_pred_prob_xgb)
mae_xgb = mean_absolute_error(y_test, y_pred_prob_xgb)
# Print Accuracy, R², RMSE, MSE, and MAE for XGBoost
print(f"XGBoost Accuracy: {accuracy_xgb * 100:.2f}%")
print(f"R² Score: {r2_xgb:.4f}, RMSE: {rmse_xgb:.4f}, MSE: {mse_xgb:.4f}, MAE: {mae_xgb:.4f}")
print(f"Confusion Matrix:\n {conf_matrix_xgb}\n")
lightgbm = LGBMClassifier(random_state=42)
# Train and evaluate LightGBM
lightgbm.fit(X_train, y_train)
y_pred_lgbm = lightgbm.predict(X_test)
accuracy_lgbm = accuracy_score(y_test, y_pred_lgbm)
conf_matrix_lgbm = confusion_matrix(y_test, y_pred_lgbm)
print(f"LightGBM Accuracy: {accuracy_lgbm * 100:.2f}%")
print(f"Confusion Matrix:\n {conf_matrix_lgbm}\n")
y_pred_prob_lgbm = lightgbm.predict_proba(X_test)[:, 1]
y_pred_lgbm = lightgbm.predict(X_test)
# Calculate R² Score, RMSE, MSE, and MAE for LightGBM
r2_lgbm = r2_score(y_test, y_pred_prob_lgbm)
rmse_lgbm = sqrt(mean_squared_error(y_test, y_pred_prob_lgbm))
mse_lgbm = mean_squared_error(y_test, y_pred_prob_lgbm)
mae_lgbm = mean_absolute_error(y_test, y_pred_prob_lgbm)
# Print Accuracy, R², RMSE, MSE, and MAE for LightGBM
print(f"LightGBM Accuracy: {accuracy_lgbm * 100:.2f}%")
print(f"R² Score: {r2_lgbm:.4f}, RMSE: {rmse_lgbm:.4f}, MSE: {mse_lgbm:.4f}, MAE: {mae_lgbm:.4f}")
print(f"Confusion Matrix:\n {conf_matrix_lgbm}\n")
import joblib
# Assuming you have already trained the model (e.g., GradientBoostingClassifier, XGBoost, etc.)
# Example with a Gradient Boosting model (replace with your trained model)
from sklearn.ensemble import GradientBoostingClassifier
# Assuming you have trained a model
model = GradientBoostingClassifier(random_state=42)
model.fit(X_train, y_train) # Replace this with your actual training code
# Save the trained model as a .pkl file
joblib.dump(model, 'trained_model.pkl')
print("Model saved successfully as trained_model.pkl")
def predict_cvd(Age, Gender, BMI, Blood_pressure, cholesterol, Bacteroides_fragilis, Faecalibacterium_prausnitzii,
Akkermansia_muciniphila, Ruminococcus_bromii, Microbiome_Diversity):
# Convert Gender to numerical (assuming Male: 0, Female: 1)
Gender = 1 if Gender.lower() == 'female' else 0
# Prepare the input data as a dataframe
input_data = pd.DataFrame({
'Age': [Age],
'Gender': [Gender],
'BMI': [BMI],
'Blood_pressure': [Blood_pressure],
'cholesterol': [cholesterol],
'Bacteroides_fragilis': [Bacteroides_fragilis],
'Faecalibacterium_prausnitzii': [Faecalibacterium_prausnitzii],
'Akkermansia_muciniphila': [Akkermansia_muciniphila],
'Ruminococcus_bromii': [Ruminococcus_bromii],
'Microbiome_Diversity': [Microbiome_Diversity]
})
print(input_data) # Print the input to debug
# Predict CVD status (0 or 1)
prediction = model.predict(input_data)
# Return the result
return "Cardiovascular Disease Detected" if prediction[0] == 1 else "No Cardiovascular Disease Detected"
import gradio as gr
import pandas as pd
import joblib
# Load the pre-trained model
model = joblib.load('trained_model.pkl')
# Define the prediction function
def predict_cvd(Age, Gender, BMI, Blood_pressure, Cholesterol, Bacteroides_fragilis, Faecalibacterium_prausnitzii,
Akkermansia_muciniphila, Ruminococcus_bromii, Microbiome_Diversity):
try:
# Convert Gender to numerical (assuming Male: 0, Female: 1)
Gender = 1 if Gender.lower() == 'female' else 0
# Prepare the input data as a dataframe with correctly capitalized feature names
input_data = pd.DataFrame({
'Age': [Age],
'Gender': [Gender],
'BMI': [BMI],
'Blood_pressure': [Blood_pressure],
'Cholesterol': [Cholesterol], # Note the capital "C"
'Bacteroides_fragilis': [Bacteroides_fragilis],
'Faecalibacterium_prausnitzii': [Faecalibacterium_prausnitzii],
'Akkermansia_muciniphila': [Akkermansia_muciniphila],
'Ruminococcus_bromii': [Ruminococcus_bromii],
'Microbiome_Diversity': [Microbiome_Diversity]
})
# Make prediction
prediction = model.predict(input_data)
# Return result based on prediction
return "Cardiovascular Disease Detected" if prediction[0] == 1 else "No Cardiovascular Disease Detected"
except Exception as e:
return f"An error occurred: {str(e)}"
# Define Gradio inputs with proper ranges and selections
inputs = [
gr.Slider(18, 100, step=1, value=50, label="Age"),
gr.Dropdown(['Male', 'Female'], label="Gender"),
gr.Slider(10.0, 50.0, step=0.1, value=25.0, label="BMI"),
gr.Slider(90, 200, step=1, value=120, label="Blood Pressure"),
gr.Slider(100, 300, step=1, value=180, label="Cholesterol"), # Corrected capitalization
gr.Slider(0.0, 10.0, step=0.1, value=5.0, label="Bacteroides Fragilis Level"),
gr.Slider(0.0, 10.0, step=0.1, value=5.0, label="Faecalibacterium Prausnitzii Level"),
gr.Slider(0.0, 10.0, step=0.1, value=5.0, label="Akkermansia Muciniphila Level"),
gr.Slider(0.0, 10.0, step=0.1, value=5.0, label="Ruminococcus Bromii Level"),
gr.Slider(0.0, 10.0, step=0.1, value=5.0, label="Microbiome Diversity"),
]
# Define Gradio interface
iface = gr.Interface(fn=predict_cvd, inputs=inputs, outputs="text", title="Cardiovascular Disease Prediction")
# Launch the interface
iface.launch() |