Spaces:
Configuration error
Configuration error
| import os | |
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| import joblib | |
| import os | |
| from datetime import datetime | |
| from sklearn.preprocessing import MinMaxScaler | |
| import openpyxl | |
| from scipy.optimize import differential_evolution | |
| def predict_forward_from_params(product_name: str, params_dict: dict, model_folder: str) -> float: | |
| """ | |
| Jalankan forward modelling XGBoost many-to-one untuk 1 baris input parameter. | |
| Dipakai baik untuk Validasi maupun Simulasi agar konsisten. | |
| """ | |
| model_filename = f"model_checkpoint_xgb_{product_name}.joblib" | |
| model_path = os.path.join(model_folder, model_filename) | |
| if not os.path.exists(model_path): | |
| raise FileNotFoundError(f"File model untuk produk {product_name} tidak ditemukan: {model_path}") | |
| artifacts = joblib.load(model_path) | |
| # Struktur bundle: dict dengan kunci 'model', 'poly_transformer', 'input_features', 'poly_feature_names' | |
| if isinstance(artifacts, dict): | |
| fwd_model = artifacts.get("model", artifacts) | |
| poly_transformer = artifacts.get("poly_transformer", None) | |
| input_features = artifacts.get("input_features", list(params_dict.keys())) | |
| poly_feature_names = artifacts.get("poly_feature_names", None) | |
| else: | |
| # Fallback: kalau bukan dict, anggap langsung model | |
| fwd_model = artifacts | |
| poly_transformer = None | |
| input_features = list(params_dict.keys()) | |
| poly_feature_names = None | |
| # Susun DataFrame satu baris | |
| X_base = pd.DataFrame([params_dict]) | |
| # Pastikan semua fitur ada | |
| missing = [f for f in input_features if f not in X_base.columns] | |
| if missing: | |
| raise ValueError( | |
| "Fitur berikut dibutuhkan oleh model namun tidak ada di input: " | |
| + ", ".join(missing) | |
| ) | |
| # Urutkan kolom sesuai urutan training | |
| X_base = X_base[input_features] | |
| # Polynomial features jika ada | |
| if poly_transformer is not None: | |
| X_poly = poly_transformer.transform(X_base) | |
| if (poly_feature_names is not None) and (len(poly_feature_names) == X_poly.shape[1]): | |
| X_final = pd.DataFrame(X_poly, columns=poly_feature_names) | |
| else: | |
| X_final = pd.DataFrame(X_poly) | |
| else: | |
| X_final = X_base | |
| # Prediksi | |
| y_pred = fwd_model.predict(X_final)[0] | |
| return float(y_pred) | |