import streamlit as st import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier, plot_tree from sklearn.metrics import accuracy_score, confusion_matrix, classification_report from sklearn.preprocessing import LabelEncoder # Konfigurasi Halaman st.set_page_config(page_title="Bank Marketing DT App", layout="wide") st.title("🌳 Decision Tree Classifier: Bank Marketing") st.markdown(""" Aplikasi ini diadaptasi dari notebook pertemuan EDA & Decision Tree. Silakan unggah dataset **bank-full.csv** untuk memulai analisis. """) # Sidebar untuk Input Data st.sidebar.header("📂 Menu Upload") uploaded_file = st.sidebar.file_uploader("Pilih file CSV", type=["csv"]) if uploaded_file is not None: # Membaca data (Gunakan sep=';' karena dataset bank marketing biasanya menggunakan titik koma) try: df = pd.read_csv(uploaded_file, sep=';') except Exception as e: st.error(f"Error membaca file: {e}") st.stop() # Navigasi di Sidebar menu = st.sidebar.radio("Navigasi", ["Eksplorasi Data (EDA)", "Modeling & Evaluasi"]) if menu == "Eksplorasi Data (EDA)": st.subheader("🔍 Statistik Deskriptif & Preview") col1, col2 = st.columns([2, 1]) with col1: st.write("5 Data Teratas:") st.dataframe(df.head()) with col2: st.write("Informasi Dataset:") st.write(f"Baris: {df.shape[0]}") st.write(f"Kolom: {df.shape[1]}") st.write(df.dtypes) st.divider() st.subheader("📊 Visualisasi Distribusi Target") fig, ax = plt.subplots(figsize=(8, 4)) sns.countplot(data=df, x='y', palette='viridis', ax=ax) st.pyplot(fig) elif menu == "Modeling & Evaluasi": st.subheader("⚙️ Training Decision Tree") # Preprocessing Sederhana sesuai Notebook df_model = df.copy() # Encoding categorical variables le = LabelEncoder() for col in df_model.select_dtypes(include=['object']).columns: df_model[col] = le.fit_transform(df_model[col]) # Split Fitur dan Target X = df_model.drop('y', axis=1) y = df_model['y'] # Pengaturan Hyperparameter di Sidebar st.sidebar.subheader("Hyperparameters") test_size = st.sidebar.slider("Test Size (%)", 10, 50, 30) max_depth = st.sidebar.slider("Max Depth Tree", 1, 20, 5) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=test_size/100, random_state=42 ) if st.button("🚀 Train Model"): model = DecisionTreeClassifier(max_depth=max_depth, random_state=42) model.fit(X_train, y_train) y_pred = model.predict(X_test) # Hasil Metrik acc = accuracy_score(y_test, y_pred) col_m1, col_m2 = st.columns(2) col_m1.metric("Accuracy Score", f"{acc:.2%}") # Confusion Matrix st.write("### Confusion Matrix") cm = confusion_matrix(y_test, y_pred) fig_cm, ax_cm = plt.subplots() sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', ax=ax_cm) plt.xlabel('Predicted') plt.ylabel('Actual') st.pyplot(fig_cm) # Visualisasi Pohon (Terbatas kedalaman agar tidak berat) st.write("### Pohon Keputusan (Visualisasi)") fig_tree, ax_tree = plt.subplots(figsize=(20, 10)) plot_tree(model, feature_names=X.columns, class_names=['No', 'Yes'], filled=True, max_depth=3, ax=ax_tree, fontsize=10) st.pyplot(fig_tree) st.write("### Classification Report") st.text(classification_report(y_test, y_pred)) else: st.warning("👈 Silakan unggah dataset di sidebar untuk memproses data.") st.info("Catatan: Gunakan dataset 'bank-full.csv' dari UCI Machine Learning Repository.")