Spaces:
Runtime error
Runtime error
Download src/master.py from ketsar/sand-production-predictor: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/ketsar/sand-production-predictor/resolve/main/src/master.py
- Command line
-
hf download hf://spaces/ketsar/sand-production-predictor/src/master.py
-
curl -L -o master.py https://huggingface.co/spaces/ketsar/sand-production-predictor/resolve/main/src/master.py
10.1 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| Created on Fri Sep 19 08:19:36 2025 | |
| @author: KETSAR | |
| """ | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| import pickle | |
| import warnings | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.metrics import classification_report, confusion_matrix, ConfusionMatrixDisplay | |
| from imblearn.over_sampling import RandomOverSampler | |
| import streamlit as st | |
| warnings.filterwarnings('ignore') | |
| st.set_page_config( | |
| page_title="KPC - Sand Production", | |
| page_icon='🛢️', | |
| layout='wide', | |
| initial_sidebar_state='expanded' | |
| ) | |
| def load_model(model_path): | |
| try: | |
| with open(model_path, 'rb') as file : | |
| model = pickle.load(file) | |
| return model | |
| except FileNotFoundError: | |
| return None | |
| def load_and_prep_data(data_path, _model): | |
| try: | |
| df = pd.read_excel(data_path) | |
| df.dropna(axis=0, inplace=True, subset=['Type']) | |
| correct_feature_order = _model.feature_names_in_ | |
| X_selected = df[correct_feature_order] | |
| y = df['Type'] | |
| print(len(X_selected.columns)) | |
| ros = RandomOverSampler(sampling_strategy='auto', random_state=42) | |
| X_ros, y_ros = ros.fit_resample(X_selected, y) | |
| _, X_test, _,y_test = train_test_split(X_ros, y_ros, test_size=0.2, random_state=0) | |
| return X_selected, X_test, y_test, df | |
| except (FileNotFoundError, KeyError) as e: | |
| st.error(f"Error saat memuat data atau mencocokkan kolom: {e}") | |
| return None, None, None, None | |
| def calculate_metrics(_model, X_test, y_test): | |
| print(len(X_test.columns)) | |
| X_test_ordered = X_test[_model.feature_names_in_] | |
| y_pred = _model.predict(X_test_ordered) | |
| report = classification_report(y_test, y_pred, target_names=['No Sand', 'Sand'], output_dict=True) | |
| cm = confusion_matrix(y_test, y_pred) | |
| try: | |
| feature_names = _model.named_steps['preprocessing'].get_feature_names_out() | |
| importances = _model.named_steps['xgb'].feature_importances_ | |
| importances_df = pd.DataFrame({'Features' : feature_names, 'Importances': importances}).sort_values(by='Importances', ascending=False) | |
| importances_df['Features'] = importances_df['Features'].str.replace('num__', '').str.replace('cat__', '') | |
| except Exception : | |
| importances_df = None | |
| return report, cm, importances_df | |
| model = load_model('classification_model_sand2.pkl') | |
| if model: | |
| input_df, X_test, y_test, ori_df = load_and_prep_data('sand production.xlsx', model) | |
| else: | |
| input_df = None | |
| if model is None or input_df is None: | |
| st.error('Model gagal load `classification_model_sand.pkl` atau data `sand production.xlsx`. Pastikan file tersebut ada di direktori yang sama') | |
| else: | |
| with st.sidebar: | |
| st.title('Parameter Sumur') | |
| st.markdown('Set parameter di bawah buat mensimulasikan sumur baru') | |
| inputs = {} | |
| for col in input_df.columns: | |
| if pd.api.types.is_numeric_dtype(input_df[col]): | |
| min_val, max_val, mean_val = float(input_df[col].min()), float(input_df[col].max()), float(input_df[col].mean()) | |
| inputs[col] = st.slider(f'**{col}**', min_val, max_val, mean_val) | |
| else: | |
| unique_vals = input_df[col].unique().tolist() | |
| inputs[col] = st.selectbox(f'**{col}**', unique_vals) | |
| input_df = pd.DataFrame([inputs]) | |
| st.divider() | |
| st.info('Kamu bisa ubah tema dashboard ini baik itu ***dark mode*** atau ***light mode*** melalui menu (:) > Settings > Theme.') | |
| st.title('🛢️ KPC - Dashboard Prediksi Produksi Minyak') | |
| tab1, tab2, tab3, tab4 = st.tabs(["**Beranda**", "**Simulator Prediksi**", "**Performa Model**", "**Insight Model**"]) | |
| with tab1: | |
| st.header('Tantangan bisnis & solusi analitik') | |
| st.markdown(""" | |
| Produksi pasir adalah masalah kritis di KPC yang berdampak langsung pada **biaya operasional** dan **keamanan aset**. Keputusan untuk memasang membran penyaring pasir yang sangat mahal memerlukan pertimbangan yang cermat. | |
| - **Dilema**: Memasang membran di semua sumur adalah pemborosan, namun tidak memasangnya di sumur yang berisiko dapat menyebabkan kerusakan katastropik. | |
| - **Solusi**: Dashboard ini memanfaatkan model *machine learning* (XGBoost) yang telah dilatih pada data historis untuk memberikan **prediksi risiko yang obyektif dan berbasis data**, memungkinkan pengambilan keputusan yang lebih cerdas dan efisien. | |
| """) | |
| st.image('sand.png', use_container_width=True, caption='Proses produksi minyak di lapangan') | |
| with tab2: | |
| st.header('Analisis resiko untuk sumur baru') | |
| st.write('set parameter di sidebar, lalu klik tombol dibawah ini untuk bisa melihat hasil analisis resiko') | |
| if st.button('**Kirim data & Lihat hasilnya**', type='primary', use_container_width=True): | |
| prediction = model.predict(input_df) | |
| prediction_proba = model.predict_proba(input_df) | |
| prob_sand = np.round(float(prediction_proba[:,1]),4) | |
| print(prob_sand) | |
| st.divider() | |
| st.subheader('Hasil analisis:') | |
| col1, col2 = st.columns([1,2]) | |
| with col1: | |
| st.markdown('#### **Status resiko**') | |
| if prediction[0] == 1: | |
| st.error('**Resiko tinggi : ADA PASIR**', icon="⚠️") | |
| else: | |
| st.success('**Resiko rendah : AMAN/TIDAK ADA PASIR**', icon='✅') | |
| st.metric(label='tingkat kepercayaan (prob. ada pasir)', value=f'{prob_sand*100:.2f}%') | |
| st.progress(prob_sand) | |
| with col2: | |
| st.markdown("#### **Rekomendasi**") | |
| if prediction[0] == 1: | |
| st.warning(""" | |
| - **Rekomendasi:** Lakukan evaluasi teknis lebih lanjut dan **prioritaskan pemasangan membran penyaring pasir** pada sumur ini. | |
| - **Potensi Dampak Dicegah:** Kerusakan peralatan, *downtime* produksi, dan biaya perbaikan. | |
| """) | |
| else: | |
| st.info(''' | |
| - **Rekomendasi:** Pemasangan membran penyaring **dapat ditunda atau tidak diperlukan** untuk sumur ini. | |
| - **Potensi Dampak Positif:** Penghematan biaya CAPEX & OPEX yang signifikan. | |
| ''') | |
| with st.expander('Lihat detail parameter sumur yang di analisis'): | |
| st.dataframe(input_df) | |
| else: | |
| st.info('silakan masukan parameter di sidebar dan klik tombol diatas ini untuk melihat hasilnya') | |
| with tab3: | |
| st.header('Akurasi Prediksi Model') | |
| st.write('Model ini sudah di uji dengan data historis untuk memastikan kendalanya') | |
| report, cm, _ = calculate_metrics(model, X_test, y_test) | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.subheader('Confusion Matrix') | |
| disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['Tidak ada Pasir', 'Ada Pasir']) | |
| fig, ax = plt.subplots() | |
| text_color = 'white' if st.get_option('theme.base') == 'dark' else 'black' | |
| disp.plot(ax=ax, cmap=plt.cm.summer, text_kw={'color': text_color}) | |
| st.pyplot(fig) | |
| with col2: | |
| st.subheader('Metrik utama') | |
| recall_sand = report['Sand']['recall'] | |
| precision_sand = report['Sand']['precision'] | |
| _, fp, fn, _ = cm.ravel() | |
| st.metric('recall (kemampuan mendeteksi sumur berpasir)', f'{recall_sand:.2%}', help='model ini berhasil mendeteksi banyaknya persetanse sumur yang benar-benar berpasir') | |
| st.metric('precision (kemampuan mendeteksi sumur berpasir)', f'{precision_sand:.2%}', help='model ini berhasil mendeteksi banyaknya persetanse sumur yang benar-benar berpasir') | |
| st.markdown(f"<p style='color:red;'><b>False Negatif</b> <i>(Prediksi ga ada pasir, Aslinya ada pasir)</i> : {fn}</p>", unsafe_allow_html=True) | |
| st.caption(f'Jumlah sumur berpasir yang salah di prediksi sebagai kategori **Aman**. (Sangat kritis - Di minimalkan)') | |
| st.markdown(f"<p style='color:orange;'><b>False Positif</b> <i>(Prediksi ada pasir, Aslinya ga ada pasir)</i> : {fp}</p>", unsafe_allow_html=True) | |
| st.caption(f'Jumlah sumur tanpa pasir yang salah di prediksi sebagai kategori **Tidak aman**. (Cukup kritis - Di minimalkan)') | |
| with tab4: | |
| st.header('Faktor pendorong produksi pasir') | |
| st.write('Berikut faktor-faktor yang perlu dipertimbangkan dalam membuat keputusan') | |
| _, _, importances_df = calculate_metrics(model, X_test, y_test) | |
| if importances_df is not None: | |
| fig, ax = plt.subplots(figsize=(10,8)) | |
| top_10_features = importances_df.head(10) | |
| sns.barplot(x='Importances', y='Features', data=top_10_features, palette='viridis', ax=ax) | |
| ax.set_title('Top 10 variabel paling berpengaruh') | |
| ax.set_xlabel('Tingkat kepentingan') | |
| ax.set_ylabel('Nama variabel') | |
| st.pyplot(fig) | |
| st.markdown(''' | |
| - **Variabel di atas** adalah faktor yang paling dominan. Perubahan pada nilai-nilai ini akan sangat mempengaruhi hasil prediksi. | |
| - **Insight yang di dapat** Data variabel ini memberikan konfirmasi mengenai kondisi geologi dan fluida mana yang harus diwaspadai. | |
| ''') | |