{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7d1ad2c6-b86a-48f3-be70-4223a592e8f8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sedang memproses data...\n",
      "Sedang melatih model Random Forest (100 pohon)...\n",
      "\n",
      "========================================\n",
      "HASIL EVALUASI MODEL\n",
      "========================================\n",
      "1. Single Split Test:\n",
      "   - R2 Score (Akurasi) : 0.8569 (85.69%)\n",
      "   - RMSE (Error Kuadrat): 0.9084\n",
      "   - MAE (Rata-rata Error): 0.5492 poin\n",
      "\n",
      "2. Cross Validation (5-Fold):\n",
      "   - Skor per tes : [0.54879999 0.77793875 0.82384791 0.84153289 0.8144776 ]\n",
      "   - Rata-rata R2 : 0.7613\n",
      "   - Kestabilan   : +/- 0.1083\n",
      "\n",
      "========================================\n",
      "FAKTOR PENENTU RATING (Feature Importance)\n",
      "========================================\n",
      "                    Fitur  Kepentingan\n",
      "               vote_count     0.833263\n",
      "               popularity     0.066340\n",
      "             release_year     0.048906\n",
      "            release_month     0.027821\n",
      "original_language_encoded     0.023670\n",
      "\n",
      "========================================\n",
      "Contoh Prediksi: Rating Asli 7.0 | Prediksi Model 5.17\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split, cross_val_score\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n",
    "\n",
    "# ==========================================\n",
    "# 1. LOAD DATA & PREPROCESSING\n",
    "# ==========================================\n",
    "print(\"Sedang memproses data...\")\n",
    "df = pd.read_csv('Latest 2025 movies Datasets.csv')\n",
    "\n",
    "# Membersihkan nilai kosong (NaN)\n",
    "df = df.dropna(subset=['release_date', 'vote_average', 'popularity', 'vote_count'])\n",
    "df['release_date'] = pd.to_datetime(df['release_date'], errors='coerce')\n",
    "df = df.dropna(subset=['release_date'])\n",
    "\n",
    "# Feature Engineering: Mengambil Tahun & Bulan\n",
    "df['release_year'] = df['release_date'].dt.year\n",
    "df['release_month'] = df['release_date'].dt.month\n",
    "\n",
    "# Mengubah Bahasa (teks) menjadi Angka\n",
    "le = LabelEncoder()\n",
    "df['original_language_encoded'] = le.fit_transform(df['original_language'])\n",
    "\n",
    "# Menentukan Fitur (X) dan Target (y)\n",
    "features = ['popularity', 'vote_count', 'release_year', 'release_month', 'original_language_encoded']\n",
    "X = df[features]\n",
    "y = df['vote_average']\n",
    "\n",
    "# Membagi Data (80% Latih, 20% Uji)\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "# ==========================================\n",
    "# 2. TRAINING MODEL (RANDOM FOREST)\n",
    "# ==========================================\n",
    "print(\"Sedang melatih model Random Forest (100 pohon)...\")\n",
    "# Kita menggunakan algoritma JUARA kita\n",
    "model = RandomForestRegressor(n_estimators=100, random_state=42)\n",
    "model.fit(X_train, y_train)\n",
    "\n",
    "# ==========================================\n",
    "# 3. EVALUASI LENGKAP\n",
    "# ==========================================\n",
    "print(\"\\n\" + \"=\"*40)\n",
    "print(\"HASIL EVALUASI MODEL\")\n",
    "print(\"=\"*40)\n",
    "\n",
    "# Prediksi data test\n",
    "y_pred = model.predict(X_test)\n",
    "\n",
    "# Menghitung Metrik\n",
    "r2 = r2_score(y_test, y_pred)\n",
    "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n",
    "mae = mean_absolute_error(y_test, y_pred)\n",
    "\n",
    "print(f\"1. Single Split Test:\")\n",
    "print(f\"   - R2 Score (Akurasi) : {r2:.4f} ({r2*100:.2f}%)\")\n",
    "print(f\"   - RMSE (Error Kuadrat): {rmse:.4f}\")\n",
    "print(f\"   - MAE (Rata-rata Error): {mae:.4f} poin\")\n",
    "\n",
    "# Cross Validation (5-Fold)\n",
    "print(f\"\\n2. Cross Validation (5-Fold):\")\n",
    "cv_scores = cross_val_score(model, X, y, cv=5, scoring='r2')\n",
    "print(f\"   - Skor per tes : {cv_scores}\")\n",
    "print(f\"   - Rata-rata R2 : {cv_scores.mean():.4f}\")\n",
    "print(f\"   - Kestabilan   : +/- {cv_scores.std():.4f}\")\n",
    "\n",
    "# ==========================================\n",
    "# 4. FEATURE IMPORTANCE (RAHASIA MODEL)\n",
    "# ==========================================\n",
    "print(\"\\n\" + \"=\"*40)\n",
    "print(\"FAKTOR PENENTU RATING (Feature Importance)\")\n",
    "print(\"=\"*40)\n",
    "\n",
    "importances = model.feature_importances_\n",
    "feature_importance_df = pd.DataFrame({'Fitur': features, 'Kepentingan': importances})\n",
    "feature_importance_df = feature_importance_df.sort_values(by='Kepentingan', ascending=False)\n",
    "\n",
    "print(feature_importance_df.to_string(index=False))\n",
    "\n",
    "# Contoh Prediksi\n",
    "print(\"\\n\" + \"=\"*40)\n",
    "print(f\"Contoh Prediksi: Rating Asli {y_test.iloc[0]} | Prediksi Model {y_pred[0]:.2f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af168121-0540-4186-a725-e6c493397535",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
