Spaces:
Sleeping
Sleeping
Create V2
Browse files
V2
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import seaborn as sns
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from sklearn.preprocessing import LabelEncoder
|
| 5 |
+
from sklearn.model_selection import train_test_split
|
| 6 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 7 |
+
from sklearn.metrics import confusion_matrix, classification_report, roc_curve, roc_auc_score
|
| 8 |
+
import streamlit as st
|
| 9 |
+
|
| 10 |
+
def process_and_evaluate(df):
|
| 11 |
+
# Encode categorical features
|
| 12 |
+
categorical_columns = df.select_dtypes(include=['object']).columns
|
| 13 |
+
label_encoders = {}
|
| 14 |
+
for col in categorical_columns:
|
| 15 |
+
le = LabelEncoder()
|
| 16 |
+
df[col] = le.fit_transform(df[col])
|
| 17 |
+
label_encoders[col] = le
|
| 18 |
+
|
| 19 |
+
# Define the target and features
|
| 20 |
+
target = 'target' # Assuming the target column is named 'target'
|
| 21 |
+
X = df.drop(columns=[target])
|
| 22 |
+
y = df[target]
|
| 23 |
+
|
| 24 |
+
# Split the data into training and testing sets
|
| 25 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 26 |
+
|
| 27 |
+
# Train a RandomForestClassifier
|
| 28 |
+
clf = RandomForestClassifier(random_state=42)
|
| 29 |
+
clf.fit(X_train, y_train)
|
| 30 |
+
|
| 31 |
+
# Predict on the test set
|
| 32 |
+
y_pred = clf.predict(X_test)
|
| 33 |
+
y_prob = clf.predict_proba(X_test)[:, 1] # Get probabilities for ROC
|
| 34 |
+
|
| 35 |
+
# Compute the confusion matrix and classification report
|
| 36 |
+
conf_matrix = confusion_matrix(y_test, y_pred)
|
| 37 |
+
classification_rep = classification_report(y_test, y_pred)
|
| 38 |
+
|
| 39 |
+
# Calculate and plot the correlation matrix
|
| 40 |
+
correlation_matrix = df.corr()
|
| 41 |
+
plt.figure(figsize=(10, 8))
|
| 42 |
+
sns.heatmap(correlation_matrix, annot=True, fmt=".2f", cmap='coolwarm')
|
| 43 |
+
plt.title('相依矩陣')
|
| 44 |
+
plt.savefig('correlation_matrix.png') # Save the plot as an image
|
| 45 |
+
plt.close() # Close the plot to free memory
|
| 46 |
+
|
| 47 |
+
# Compute ROC curve and AUC
|
| 48 |
+
fpr, tpr, thresholds = roc_curve(y_test, y_prob)
|
| 49 |
+
roc_auc = roc_auc_score(y_test, y_prob)
|
| 50 |
+
|
| 51 |
+
# Plot ROC curve
|
| 52 |
+
plt.figure(figsize=(10, 6))
|
| 53 |
+
plt.plot(fpr, tpr, color='blue', label='ROC 曲線 (AUC = {:.2f})'.format(roc_auc))
|
| 54 |
+
plt.plot([0, 1], [0, 1], color='red', linestyle='--')
|
| 55 |
+
plt.xlim([0.0, 1.0])
|
| 56 |
+
plt.ylim([0.0, 1.05])
|
| 57 |
+
plt.xlabel('假陽性率')
|
| 58 |
+
plt.ylabel('真正率')
|
| 59 |
+
plt.title('Receiver Operating Characteristic (ROC) 曲線')
|
| 60 |
+
plt.legend(loc='lower right')
|
| 61 |
+
plt.savefig('roc_curve.png') # Save the ROC curve as an image
|
| 62 |
+
plt.close() # Close the plot to free memory
|
| 63 |
+
|
| 64 |
+
return classification_rep, conf_matrix, 'correlation_matrix.png', 'roc_curve.png'
|
| 65 |
+
|
| 66 |
+
# Create the Streamlit app
|
| 67 |
+
st.set_page_config(page_title="心臟病預測系統", layout="wide")
|
| 68 |
+
|
| 69 |
+
st.title("心臟病預測系統")
|
| 70 |
+
st.markdown("<h5 style='text-align: center;'>上傳包含心臟病數據的 CSV 文件以獲取分類報告、相依矩陣和 ROC 曲線。</h5>", unsafe_allow_html=True)
|
| 71 |
+
|
| 72 |
+
uploaded_file = st.file_uploader("上傳 CSV 文件", type="csv")
|
| 73 |
+
|
| 74 |
+
if uploaded_file is not None:
|
| 75 |
+
# Load the dataset directly from the uploaded file
|
| 76 |
+
df = pd.read_csv(uploaded_file)
|
| 77 |
+
|
| 78 |
+
# Process the data and generate reports
|
| 79 |
+
classification_report, conf_matrix, correlation_matrix_path, roc_curve_path = process_and_evaluate(df)
|
| 80 |
+
|
| 81 |
+
st.subheader("分類報告")
|
| 82 |
+
st.text_area("分類報告", classification_report, height=400)
|
| 83 |
+
|
| 84 |
+
st.subheader("混淆矩陣")
|
| 85 |
+
# Plot and display the confusion matrix
|
| 86 |
+
plt.figure(figsize=(8, 6))
|
| 87 |
+
sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=['Negative', 'Positive'], yticklabels=['Negative', 'Positive'])
|
| 88 |
+
plt.ylabel('實際值')
|
| 89 |
+
plt.xlabel('預測值')
|
| 90 |
+
plt.title('混淆矩陣')
|
| 91 |
+
plt.savefig('confusion_matrix.png') # Save the confusion matrix as an image
|
| 92 |
+
plt.close() # Close the plot to free memory
|
| 93 |
+
st.image('confusion_matrix.png')
|
| 94 |
+
|
| 95 |
+
st.subheader("相依矩陣")
|
| 96 |
+
st.image(correlation_matrix_path)
|
| 97 |
+
|
| 98 |
+
st.subheader("ROC 曲
|