Spaces:
Running
Running
Upload 2 files
Browse files- datacreation.ipynb +0 -0
- pythonanalysis.ipynb +1450 -0
datacreation.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pythonanalysis.ipynb
ADDED
|
@@ -0,0 +1,1450 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "85361b58",
|
| 6 |
+
"metadata": {
|
| 7 |
+
"id": "85361b58"
|
| 8 |
+
},
|
| 9 |
+
"source": [
|
| 10 |
+
"# Step 2 — Python Analysis / Modeling\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"Clean version for the Hugging Face SE21 app template. It creates dashboard artifacts."
|
| 13 |
+
]
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "markdown",
|
| 17 |
+
"source": [
|
| 18 |
+
"2.1 Environment setup & modeling"
|
| 19 |
+
],
|
| 20 |
+
"metadata": {
|
| 21 |
+
"id": "WP6akOm_IupL"
|
| 22 |
+
},
|
| 23 |
+
"id": "WP6akOm_IupL"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"execution_count": 2,
|
| 28 |
+
"id": "c88b847c",
|
| 29 |
+
"metadata": {
|
| 30 |
+
"colab": {
|
| 31 |
+
"base_uri": "https://localhost:8080/"
|
| 32 |
+
},
|
| 33 |
+
"id": "c88b847c",
|
| 34 |
+
"outputId": "ee60c93f-29b8-4dcc-9fc4-a5b6aa4b9398"
|
| 35 |
+
},
|
| 36 |
+
"outputs": [
|
| 37 |
+
{
|
| 38 |
+
"output_type": "stream",
|
| 39 |
+
"name": "stdout",
|
| 40 |
+
"text": [
|
| 41 |
+
"Environment ready.\n",
|
| 42 |
+
"BASE_PATH: /content\n",
|
| 43 |
+
"CSV files found:\n",
|
| 44 |
+
"- /content/Womens Clothing E-Commerce Reviews.csv\n",
|
| 45 |
+
"- /content/ecommerce_returns_cleaned.csv\n",
|
| 46 |
+
"Using reviews file: /content/Womens Clothing E-Commerce Reviews.csv\n",
|
| 47 |
+
"Using returns file: /content/ecommerce_returns_cleaned.csv\n",
|
| 48 |
+
"Reviews shape: (23486, 10)\n",
|
| 49 |
+
"Returns shape: (113314, 29)\n",
|
| 50 |
+
"Reviews columns: ['Clothing ID', 'Age', 'Title', 'Review Text', 'Rating', 'Recommended IND', 'Positive Feedback Count', 'Division Name', 'Department Name', 'Class Name']\n",
|
| 51 |
+
"Returns columns: ['order_id', 'order_item_id', 'product_id', 'seller_id', 'customer_id', 'order_status', 'order_purchase_timestamp', 'order_delivered_customer_date', 'order_estimated_delivery_date', 'review_score', 'review_comment_title', 'review_comment_message', 'price', 'freight_value', 'total_cost', 'product_category_name', 'product_name_lenght', 'product_description_lenght', 'product_photos_qty', 'product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm', 'has_review_text', 'review_text_length', 'delivery_delay_days', 'negative_keyword_flag', 'synthetic_return_risk', 'likely_return']\n",
|
| 52 |
+
"Data loaded and cleaned.\n"
|
| 53 |
+
]
|
| 54 |
+
}
|
| 55 |
+
],
|
| 56 |
+
"source": [
|
| 57 |
+
"# ==================================================\n",
|
| 58 |
+
"# STEP 2: UNIVERSAL ANALYSIS SETUP\n",
|
| 59 |
+
"# Works in BOTH Hugging Face Spaces and Google Colab\n",
|
| 60 |
+
"# ==================================================\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"import os\n",
|
| 63 |
+
"import json\n",
|
| 64 |
+
"import random\n",
|
| 65 |
+
"import warnings\n",
|
| 66 |
+
"from pathlib import Path\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"os.environ.setdefault(\"MPLCONFIGDIR\", \"/tmp/matplotlib\")\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"import numpy as np\n",
|
| 71 |
+
"import pandas as pd\n",
|
| 72 |
+
"import matplotlib.pyplot as plt\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"warnings.filterwarnings(\"ignore\")\n",
|
| 75 |
+
"random.seed(42)\n",
|
| 76 |
+
"np.random.seed(42)\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"# Pick the correct runtime folder automatically.\n",
|
| 79 |
+
"# Hugging Face Space uses /app. Colab uses /content.\n",
|
| 80 |
+
"candidate_roots = [Path(\"/app\"), Path(\"/content\"), Path.cwd(), Path(\"/mnt/data\")]\n",
|
| 81 |
+
"BASE_PATH = None\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"for root in candidate_roots:\n",
|
| 84 |
+
" if root.exists():\n",
|
| 85 |
+
" csvs = []\n",
|
| 86 |
+
" for p in root.rglob(\"*.csv\"):\n",
|
| 87 |
+
" parts = {part.lower() for part in p.parts}\n",
|
| 88 |
+
" if \"sample_data\" in parts:\n",
|
| 89 |
+
" continue\n",
|
| 90 |
+
" if \"outputs\" in parts or \"figures\" in parts or \"tables\" in parts or \"artifacts\" in parts:\n",
|
| 91 |
+
" continue\n",
|
| 92 |
+
" csvs.append(p)\n",
|
| 93 |
+
" if csvs:\n",
|
| 94 |
+
" BASE_PATH = root\n",
|
| 95 |
+
" break\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"if BASE_PATH is None:\n",
|
| 98 |
+
" if Path(\"/app\").exists():\n",
|
| 99 |
+
" BASE_PATH = Path(\"/app\")\n",
|
| 100 |
+
" elif Path(\"/content\").exists():\n",
|
| 101 |
+
" BASE_PATH = Path(\"/content\")\n",
|
| 102 |
+
" else:\n",
|
| 103 |
+
" BASE_PATH = Path.cwd()\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"DATA_PROCESSED = BASE_PATH / \"data_processed\"\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"OUTPUTS = BASE_PATH / \"outputs\"\n",
|
| 108 |
+
"FIGURES = BASE_PATH / \"figures\"\n",
|
| 109 |
+
"TABLES = BASE_PATH / \"tables\"\n",
|
| 110 |
+
"ARTIFACTS = BASE_PATH / \"artifacts\"\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"# Extra folders because different templates check different places\n",
|
| 113 |
+
"OUTPUT_FIGURES = OUTPUTS / \"figures\"\n",
|
| 114 |
+
"OUTPUT_TABLES = OUTPUTS / \"tables\"\n",
|
| 115 |
+
"ARTIFACT_FIGURES = ARTIFACTS / \"figures\"\n",
|
| 116 |
+
"ARTIFACT_TABLES = ARTIFACTS / \"tables\"\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"ALL_OUTPUT_DIRS = [\n",
|
| 119 |
+
" DATA_PROCESSED,\n",
|
| 120 |
+
" OUTPUTS,\n",
|
| 121 |
+
" FIGURES,\n",
|
| 122 |
+
" TABLES,\n",
|
| 123 |
+
" ARTIFACTS,\n",
|
| 124 |
+
" OUTPUT_FIGURES,\n",
|
| 125 |
+
" OUTPUT_TABLES,\n",
|
| 126 |
+
" ARTIFACT_FIGURES,\n",
|
| 127 |
+
" ARTIFACT_TABLES,\n",
|
| 128 |
+
"]\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"for folder in ALL_OUTPUT_DIRS:\n",
|
| 131 |
+
" folder.mkdir(parents=True, exist_ok=True)\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"print(\"Environment ready.\")\n",
|
| 134 |
+
"print(\"BASE_PATH:\", BASE_PATH)\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"# Load data created by Step 1 if available.\n",
|
| 137 |
+
"csv_paths = []\n",
|
| 138 |
+
"for p in BASE_PATH.rglob(\"*.csv\"):\n",
|
| 139 |
+
" parts = {part.lower() for part in p.parts}\n",
|
| 140 |
+
" if \"sample_data\" in parts:\n",
|
| 141 |
+
" continue\n",
|
| 142 |
+
" if \"outputs\" in parts or \"figures\" in parts or \"tables\" in parts or \"artifacts\" in parts:\n",
|
| 143 |
+
" continue\n",
|
| 144 |
+
" csv_paths.append(p)\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"print(\"CSV files found:\")\n",
|
| 147 |
+
"for p in csv_paths:\n",
|
| 148 |
+
" print(\"-\", p)\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"def first_existing(paths):\n",
|
| 151 |
+
" for p in paths:\n",
|
| 152 |
+
" if Path(p).exists():\n",
|
| 153 |
+
" return Path(p)\n",
|
| 154 |
+
" return None\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"reviews_path = first_existing([\n",
|
| 157 |
+
" DATA_PROCESSED / \"reviews_cleaned.csv\",\n",
|
| 158 |
+
" DATA_PROCESSED / \"womens_reviews_cleaned.csv\",\n",
|
| 159 |
+
" BASE_PATH / \"Womens Clothing E-Commerce Reviews.csv\",\n",
|
| 160 |
+
"])\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"returns_path = first_existing([\n",
|
| 163 |
+
" DATA_PROCESSED / \"returns_input.csv\",\n",
|
| 164 |
+
" DATA_PROCESSED / \"returns_cleaned.csv\",\n",
|
| 165 |
+
" BASE_PATH / \"ecommerce_returns_cleaned.csv\",\n",
|
| 166 |
+
" DATA_PROCESSED / \"synthetic_return_risk.csv\",\n",
|
| 167 |
+
"])\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"# Fallback search.\n",
|
| 170 |
+
"if reviews_path is None:\n",
|
| 171 |
+
" review_matches = [\n",
|
| 172 |
+
" p for p in csv_paths\n",
|
| 173 |
+
" if (\"clothing\" in p.name.lower()) or (\"review\" in p.name.lower() and \"return\" not in p.name.lower())\n",
|
| 174 |
+
" ]\n",
|
| 175 |
+
" reviews_path = review_matches[0] if review_matches else None\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"if returns_path is None:\n",
|
| 178 |
+
" return_matches = [\n",
|
| 179 |
+
" p for p in csv_paths\n",
|
| 180 |
+
" if \"return\" in p.name.lower()\n",
|
| 181 |
+
" ]\n",
|
| 182 |
+
" returns_path = return_matches[0] if return_matches else None\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"if returns_path is None:\n",
|
| 186 |
+
" raise FileNotFoundError(\"Step 2 could not find the ecommerce returns CSV.\")\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"print(\"Using reviews file:\", reviews_path)\n",
|
| 189 |
+
"print(\"Using returns file:\", returns_path)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"reviews_df = pd.read_csv(reviews_path).drop(columns=[\"Unnamed: 0\"], errors=\"ignore\")\n",
|
| 192 |
+
"returns_df = pd.read_csv(returns_path).drop(columns=[\"Unnamed: 0\"], errors=\"ignore\")\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"print(\"Reviews shape:\", reviews_df.shape)\n",
|
| 195 |
+
"print(\"Returns shape:\", returns_df.shape)\n",
|
| 196 |
+
"print(\"Reviews columns:\", reviews_df.columns.tolist())\n",
|
| 197 |
+
"print(\"Returns columns:\", returns_df.columns.tolist())\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"# Basic cleanup / type safety\n",
|
| 200 |
+
"for col in [\"Age\", \"Rating\", \"Recommended IND\", \"Positive Feedback Count\"]:\n",
|
| 201 |
+
" if col in reviews_df.columns:\n",
|
| 202 |
+
" reviews_df[col] = pd.to_numeric(reviews_df[col], errors=\"coerce\")\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"if \"Review Text\" in reviews_df.columns:\n",
|
| 205 |
+
" reviews_df[\"Review Text\"] = reviews_df[\"Review Text\"].fillna(\"\").astype(str)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"if \"Class Name\" in reviews_df.columns:\n",
|
| 208 |
+
" reviews_df[\"Class Name\"] = reviews_df[\"Class Name\"].fillna(\"Unknown\").astype(str)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"for col in [\"review_score\", \"likely_return\", \"price\", \"freight_value\", \"delivery_delay_days\", \"synthetic_return_risk\"]:\n",
|
| 211 |
+
" if col in returns_df.columns:\n",
|
| 212 |
+
" returns_df[col] = pd.to_numeric(returns_df[col], errors=\"coerce\")\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"print(\"Data loaded and cleaned.\")"
|
| 215 |
+
]
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"cell_type": "markdown",
|
| 219 |
+
"source": [
|
| 220 |
+
"2.2 Dashboard visualization"
|
| 221 |
+
],
|
| 222 |
+
"metadata": {
|
| 223 |
+
"id": "KAj-RspZI2EI"
|
| 224 |
+
},
|
| 225 |
+
"id": "KAj-RspZI2EI"
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"execution_count": 3,
|
| 230 |
+
"id": "f9eb3801",
|
| 231 |
+
"metadata": {
|
| 232 |
+
"id": "f9eb3801"
|
| 233 |
+
},
|
| 234 |
+
"outputs": [],
|
| 235 |
+
"source": [
|
| 236 |
+
"# ==================================================\n",
|
| 237 |
+
"# HELPERS: save artifacts where the app can find them\n",
|
| 238 |
+
"# ==================================================\n",
|
| 239 |
+
"# ==================================================\n",
|
| 240 |
+
"# HELPERS: save artifacts everywhere the app may check\n",
|
| 241 |
+
"# ==================================================\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"def safe_write_csv(df, path):\n",
|
| 244 |
+
" try:\n",
|
| 245 |
+
" df.to_csv(path)\n",
|
| 246 |
+
" return True\n",
|
| 247 |
+
" except Exception as e:\n",
|
| 248 |
+
" print(f\"Could not save {path}: {e}\")\n",
|
| 249 |
+
" return False\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"def safe_savefig(path):\n",
|
| 253 |
+
" try:\n",
|
| 254 |
+
" plt.savefig(path, dpi=150, bbox_inches=\"tight\")\n",
|
| 255 |
+
" return True\n",
|
| 256 |
+
" except Exception as e:\n",
|
| 257 |
+
" print(f\"Could not save {path}: {e}\")\n",
|
| 258 |
+
" return False\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"\n",
|
| 261 |
+
"def safe_write_text(text, path):\n",
|
| 262 |
+
" try:\n",
|
| 263 |
+
" path.write_text(text, encoding=\"utf-8\")\n",
|
| 264 |
+
" return True\n",
|
| 265 |
+
" except Exception as e:\n",
|
| 266 |
+
" print(f\"Could not save {path}: {e}\")\n",
|
| 267 |
+
" return False\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"def save_table(df, name):\n",
|
| 271 |
+
" if isinstance(df, pd.Series):\n",
|
| 272 |
+
" df = df.to_frame()\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" table_folders = [\n",
|
| 275 |
+
" TABLES,\n",
|
| 276 |
+
" OUTPUT_TABLES,\n",
|
| 277 |
+
" OUTPUTS,\n",
|
| 278 |
+
" ARTIFACT_TABLES,\n",
|
| 279 |
+
" ARTIFACTS,\n",
|
| 280 |
+
" ]\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" saved_anywhere = False\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" for folder in table_folders:\n",
|
| 285 |
+
" folder.mkdir(parents=True, exist_ok=True)\n",
|
| 286 |
+
" path = folder / f\"{name}.csv\"\n",
|
| 287 |
+
" saved_anywhere = safe_write_csv(df, path) or saved_anywhere\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" if saved_anywhere:\n",
|
| 290 |
+
" print(f\"Saved table everywhere: {name}.csv\")\n",
|
| 291 |
+
" else:\n",
|
| 292 |
+
" raise RuntimeError(f\"Could not save table {name}.csv\")\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"def save_figure(name):\n",
|
| 296 |
+
" figure_folders = [\n",
|
| 297 |
+
" FIGURES,\n",
|
| 298 |
+
" OUTPUT_FIGURES,\n",
|
| 299 |
+
" OUTPUTS,\n",
|
| 300 |
+
" ARTIFACT_FIGURES,\n",
|
| 301 |
+
" ARTIFACTS,\n",
|
| 302 |
+
" ]\n",
|
| 303 |
+
"\n",
|
| 304 |
+
" saved_anywhere = False\n",
|
| 305 |
+
"\n",
|
| 306 |
+
" for folder in figure_folders:\n",
|
| 307 |
+
" folder.mkdir(parents=True, exist_ok=True)\n",
|
| 308 |
+
" path = folder / f\"{name}.png\"\n",
|
| 309 |
+
" saved_anywhere = safe_savefig(path) or saved_anywhere\n",
|
| 310 |
+
"\n",
|
| 311 |
+
" if saved_anywhere:\n",
|
| 312 |
+
" print(f\"Saved figure everywhere: {name}.png\")\n",
|
| 313 |
+
" else:\n",
|
| 314 |
+
" raise RuntimeError(f\"Could not save figure {name}.png\")\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"def save_text(text, name):\n",
|
| 318 |
+
" text_folders = [\n",
|
| 319 |
+
" TABLES,\n",
|
| 320 |
+
" OUTPUT_TABLES,\n",
|
| 321 |
+
" OUTPUTS,\n",
|
| 322 |
+
" ARTIFACT_TABLES,\n",
|
| 323 |
+
" ARTIFACTS,\n",
|
| 324 |
+
" ]\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" saved_anywhere = False\n",
|
| 327 |
+
"\n",
|
| 328 |
+
" for folder in text_folders:\n",
|
| 329 |
+
" folder.mkdir(parents=True, exist_ok=True)\n",
|
| 330 |
+
" path = folder / f\"{name}.txt\"\n",
|
| 331 |
+
" saved_anywhere = safe_write_text(text, path) or saved_anywhere\n",
|
| 332 |
+
"\n",
|
| 333 |
+
" if saved_anywhere:\n",
|
| 334 |
+
" print(f\"Saved text everywhere: {name}.txt\")\n",
|
| 335 |
+
" else:\n",
|
| 336 |
+
" raise RuntimeError(f\"Could not save text {name}.txt\")"
|
| 337 |
+
]
|
| 338 |
+
},
|
| 339 |
+
{
|
| 340 |
+
"cell_type": "code",
|
| 341 |
+
"execution_count": 4,
|
| 342 |
+
"id": "a99949ac",
|
| 343 |
+
"metadata": {
|
| 344 |
+
"colab": {
|
| 345 |
+
"base_uri": "https://localhost:8080/"
|
| 346 |
+
},
|
| 347 |
+
"id": "a99949ac",
|
| 348 |
+
"outputId": "012f8a9b-e72b-4288-d471-de548e9d35e0"
|
| 349 |
+
},
|
| 350 |
+
"outputs": [
|
| 351 |
+
{
|
| 352 |
+
"output_type": "stream",
|
| 353 |
+
"name": "stdout",
|
| 354 |
+
"text": [
|
| 355 |
+
"Saved table everywhere: rating_distribution.csv\n",
|
| 356 |
+
"Saved figure everywhere: rating_distribution.png\n",
|
| 357 |
+
"Saved table everywhere: recommendation_by_class.csv\n",
|
| 358 |
+
"Saved figure everywhere: recommendation_by_class.png\n",
|
| 359 |
+
"Saved table everywhere: average_rating_by_age.csv\n",
|
| 360 |
+
"Saved figure everywhere: average_rating_by_age.png\n",
|
| 361 |
+
"Saved table everywhere: negative_keyword_counts.csv\n",
|
| 362 |
+
"Saved figure everywhere: negative_keyword_counts.png\n",
|
| 363 |
+
"Saved table everywhere: category_return_rate.csv\n",
|
| 364 |
+
"Saved figure everywhere: category_return_rate.png\n",
|
| 365 |
+
"Saved table everywhere: monthly_return_rate.csv\n",
|
| 366 |
+
"Saved figure everywhere: monthly_return_rate.png\n",
|
| 367 |
+
"Saved table everywhere: feature_importance.csv\n",
|
| 368 |
+
"Saved figure everywhere: feature_importance.png\n",
|
| 369 |
+
"Saved text everywhere: classification_report.txt\n",
|
| 370 |
+
"Artifact creation section finished.\n"
|
| 371 |
+
]
|
| 372 |
+
}
|
| 373 |
+
],
|
| 374 |
+
"source": [
|
| 375 |
+
"# ==================================================\n",
|
| 376 |
+
"# CREATE DASHBOARD ARTIFACTS\n",
|
| 377 |
+
"# ==================================================\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"created_figures = []\n",
|
| 380 |
+
"created_tables = []\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"# 1) Rating distribution\n",
|
| 383 |
+
"if \"Rating\" in reviews_df.columns:\n",
|
| 384 |
+
" rating_distribution = reviews_df[\"Rating\"].dropna().value_counts().sort_index().to_frame(\"count\")\n",
|
| 385 |
+
" save_table(rating_distribution, \"rating_distribution\")\n",
|
| 386 |
+
" created_tables.append(\"rating_distribution.csv\")\n",
|
| 387 |
+
"\n",
|
| 388 |
+
" plt.figure(figsize=(7, 4))\n",
|
| 389 |
+
" plt.bar(rating_distribution.index.astype(str), rating_distribution[\"count\"])\n",
|
| 390 |
+
" plt.title(\"Distribution of Customer Ratings\")\n",
|
| 391 |
+
" plt.xlabel(\"Rating\")\n",
|
| 392 |
+
" plt.ylabel(\"Number of Reviews\")\n",
|
| 393 |
+
" plt.tight_layout()\n",
|
| 394 |
+
" save_figure(\"rating_distribution\")\n",
|
| 395 |
+
" created_figures.append(\"rating_distribution.png\")\n",
|
| 396 |
+
" plt.close()\n",
|
| 397 |
+
"\n",
|
| 398 |
+
"# 2) Recommendation rate by clothing class\n",
|
| 399 |
+
"if {\"Class Name\", \"Recommended IND\"}.issubset(reviews_df.columns):\n",
|
| 400 |
+
" recommendation_by_class = (\n",
|
| 401 |
+
" reviews_df.groupby(\"Class Name\")[\"Recommended IND\"]\n",
|
| 402 |
+
" .mean()\n",
|
| 403 |
+
" .sort_values(ascending=False)\n",
|
| 404 |
+
" .head(10)\n",
|
| 405 |
+
" .to_frame(\"recommendation_rate\")\n",
|
| 406 |
+
" )\n",
|
| 407 |
+
" save_table(recommendation_by_class, \"recommendation_by_class\")\n",
|
| 408 |
+
" created_tables.append(\"recommendation_by_class.csv\")\n",
|
| 409 |
+
"\n",
|
| 410 |
+
" plt.figure(figsize=(10, 5))\n",
|
| 411 |
+
" plt.bar(recommendation_by_class.index.astype(str), recommendation_by_class[\"recommendation_rate\"])\n",
|
| 412 |
+
" plt.title(\"Top 10 Most Recommended Clothing Classes\")\n",
|
| 413 |
+
" plt.xlabel(\"Class Name\")\n",
|
| 414 |
+
" plt.ylabel(\"Recommendation Rate\")\n",
|
| 415 |
+
" plt.xticks(rotation=75)\n",
|
| 416 |
+
" plt.tight_layout()\n",
|
| 417 |
+
" save_figure(\"recommendation_by_class\")\n",
|
| 418 |
+
" created_figures.append(\"recommendation_by_class.png\")\n",
|
| 419 |
+
" plt.close()\n",
|
| 420 |
+
"\n",
|
| 421 |
+
"# 3) Average rating by age\n",
|
| 422 |
+
"if {\"Age\", \"Rating\"}.issubset(reviews_df.columns):\n",
|
| 423 |
+
" average_rating_by_age = (\n",
|
| 424 |
+
" reviews_df.groupby(\"Age\")[\"Rating\"]\n",
|
| 425 |
+
" .mean()\n",
|
| 426 |
+
" .dropna()\n",
|
| 427 |
+
" .to_frame(\"average_rating\")\n",
|
| 428 |
+
" )\n",
|
| 429 |
+
" save_table(average_rating_by_age, \"average_rating_by_age\")\n",
|
| 430 |
+
" created_tables.append(\"average_rating_by_age.csv\")\n",
|
| 431 |
+
"\n",
|
| 432 |
+
" plt.figure(figsize=(10, 4))\n",
|
| 433 |
+
" plt.plot(average_rating_by_age.index, average_rating_by_age[\"average_rating\"])\n",
|
| 434 |
+
" plt.title(\"Average Rating by Customer Age\")\n",
|
| 435 |
+
" plt.xlabel(\"Age\")\n",
|
| 436 |
+
" plt.ylabel(\"Average Rating\")\n",
|
| 437 |
+
" plt.tight_layout()\n",
|
| 438 |
+
" save_figure(\"average_rating_by_age\")\n",
|
| 439 |
+
" created_figures.append(\"average_rating_by_age.png\")\n",
|
| 440 |
+
" plt.close()\n",
|
| 441 |
+
"\n",
|
| 442 |
+
"# 4) Complaint / return-risk keyword counts\n",
|
| 443 |
+
"review_text_column = None\n",
|
| 444 |
+
"for candidate in [\"Review Text\", \"review_text\", \"review_comment_message\"]:\n",
|
| 445 |
+
" if candidate in reviews_df.columns:\n",
|
| 446 |
+
" review_text_column = candidate\n",
|
| 447 |
+
" break\n",
|
| 448 |
+
"\n",
|
| 449 |
+
"if review_text_column is not None:\n",
|
| 450 |
+
" keywords = [\n",
|
| 451 |
+
" \"bad\", \"poor\", \"cheap\", \"small\", \"large\", \"tight\", \"loose\",\n",
|
| 452 |
+
" \"scratchy\", \"thin\", \"return\", \"returned\", \"disappointed\",\n",
|
| 453 |
+
" \"quality\", \"fit\", \"sizing\", \"fabric\", \"uncomfortable\"\n",
|
| 454 |
+
" ]\n",
|
| 455 |
+
" text_series = reviews_df[review_text_column].fillna(\"\").astype(str).str.lower()\n",
|
| 456 |
+
" keyword_counts = {}\n",
|
| 457 |
+
" for word in keywords:\n",
|
| 458 |
+
" keyword_counts[word] = int(text_series.str.contains(word, regex=False).sum())\n",
|
| 459 |
+
"\n",
|
| 460 |
+
" negative_keyword_counts = (\n",
|
| 461 |
+
" pd.DataFrame(keyword_counts.items(), columns=[\"keyword\", \"review_count\"])\n",
|
| 462 |
+
" .sort_values(\"review_count\", ascending=False)\n",
|
| 463 |
+
" .set_index(\"keyword\")\n",
|
| 464 |
+
" )\n",
|
| 465 |
+
" save_table(negative_keyword_counts, \"negative_keyword_counts\")\n",
|
| 466 |
+
" created_tables.append(\"negative_keyword_counts.csv\")\n",
|
| 467 |
+
"\n",
|
| 468 |
+
" top_keywords = negative_keyword_counts.head(10)\n",
|
| 469 |
+
" plt.figure(figsize=(9, 4))\n",
|
| 470 |
+
" plt.bar(top_keywords.index.astype(str), top_keywords[\"review_count\"])\n",
|
| 471 |
+
" plt.title(\"Most Common Return-Risk Keywords in Reviews\")\n",
|
| 472 |
+
" plt.xlabel(\"Keyword\")\n",
|
| 473 |
+
" plt.ylabel(\"Number of Reviews\")\n",
|
| 474 |
+
" plt.xticks(rotation=45)\n",
|
| 475 |
+
" plt.tight_layout()\n",
|
| 476 |
+
" save_figure(\"negative_keyword_counts\")\n",
|
| 477 |
+
" created_figures.append(\"negative_keyword_counts.png\")\n",
|
| 478 |
+
" plt.close()\n",
|
| 479 |
+
"\n",
|
| 480 |
+
"# 5) Product category return rate\n",
|
| 481 |
+
"if {\"product_category_name\", \"likely_return\"}.issubset(returns_df.columns):\n",
|
| 482 |
+
" category_return_rate = (\n",
|
| 483 |
+
" returns_df.groupby(\"product_category_name\")[\"likely_return\"]\n",
|
| 484 |
+
" .mean()\n",
|
| 485 |
+
" .sort_values(ascending=False)\n",
|
| 486 |
+
" .head(15)\n",
|
| 487 |
+
" .to_frame(\"return_rate\")\n",
|
| 488 |
+
" )\n",
|
| 489 |
+
" save_table(category_return_rate, \"category_return_rate\")\n",
|
| 490 |
+
" created_tables.append(\"category_return_rate.csv\")\n",
|
| 491 |
+
"\n",
|
| 492 |
+
" plt.figure(figsize=(11, 5))\n",
|
| 493 |
+
" plt.bar(category_return_rate.index.astype(str), category_return_rate[\"return_rate\"])\n",
|
| 494 |
+
" plt.title(\"Top Product Categories by Estimated Return Rate\")\n",
|
| 495 |
+
" plt.xlabel(\"Product Category\")\n",
|
| 496 |
+
" plt.ylabel(\"Return Rate\")\n",
|
| 497 |
+
" plt.xticks(rotation=75)\n",
|
| 498 |
+
" plt.tight_layout()\n",
|
| 499 |
+
" save_figure(\"category_return_rate\")\n",
|
| 500 |
+
" created_figures.append(\"category_return_rate.png\")\n",
|
| 501 |
+
" plt.close()\n",
|
| 502 |
+
"\n",
|
| 503 |
+
"# 6) Monthly return rate\n",
|
| 504 |
+
"if {\"order_purchase_timestamp\", \"likely_return\"}.issubset(returns_df.columns):\n",
|
| 505 |
+
" monthly_df = returns_df.copy()\n",
|
| 506 |
+
" monthly_df[\"order_purchase_timestamp\"] = pd.to_datetime(monthly_df[\"order_purchase_timestamp\"], errors=\"coerce\")\n",
|
| 507 |
+
" monthly_df = monthly_df.dropna(subset=[\"order_purchase_timestamp\"])\n",
|
| 508 |
+
"\n",
|
| 509 |
+
" if len(monthly_df) > 0:\n",
|
| 510 |
+
" monthly_return_rate = (\n",
|
| 511 |
+
" monthly_df.set_index(\"order_purchase_timestamp\")\n",
|
| 512 |
+
" .resample(\"M\")[\"likely_return\"]\n",
|
| 513 |
+
" .mean()\n",
|
| 514 |
+
" .dropna()\n",
|
| 515 |
+
" .to_frame(\"return_rate\")\n",
|
| 516 |
+
" )\n",
|
| 517 |
+
" save_table(monthly_return_rate, \"monthly_return_rate\")\n",
|
| 518 |
+
" created_tables.append(\"monthly_return_rate.csv\")\n",
|
| 519 |
+
"\n",
|
| 520 |
+
" plt.figure(figsize=(10, 4))\n",
|
| 521 |
+
" plt.plot(monthly_return_rate.index, monthly_return_rate[\"return_rate\"])\n",
|
| 522 |
+
" plt.title(\"Monthly Estimated Return Rate\")\n",
|
| 523 |
+
" plt.xlabel(\"Month\")\n",
|
| 524 |
+
" plt.ylabel(\"Return Rate\")\n",
|
| 525 |
+
" plt.tight_layout()\n",
|
| 526 |
+
" save_figure(\"monthly_return_rate\")\n",
|
| 527 |
+
" created_figures.append(\"monthly_return_rate.png\")\n",
|
| 528 |
+
" plt.close()\n",
|
| 529 |
+
"\n",
|
| 530 |
+
"# 7) Simple feature importance if sklearn is available\n",
|
| 531 |
+
"try:\n",
|
| 532 |
+
" from sklearn.ensemble import RandomForestClassifier\n",
|
| 533 |
+
" from sklearn.model_selection import train_test_split\n",
|
| 534 |
+
" from sklearn.metrics import accuracy_score, classification_report\n",
|
| 535 |
+
"\n",
|
| 536 |
+
" feature_columns = [c for c in [\"Age\", \"Rating\", \"Positive Feedback Count\"] if c in reviews_df.columns]\n",
|
| 537 |
+
" if \"Recommended IND\" in reviews_df.columns and len(feature_columns) > 0:\n",
|
| 538 |
+
" model_df = reviews_df[feature_columns + [\"Recommended IND\"]].dropna().copy()\n",
|
| 539 |
+
" if model_df[\"Recommended IND\"].nunique() >= 2:\n",
|
| 540 |
+
" X = model_df[feature_columns]\n",
|
| 541 |
+
" y = model_df[\"Recommended IND\"].astype(int)\n",
|
| 542 |
+
" X_train, X_test, y_train, y_test = train_test_split(\n",
|
| 543 |
+
" X, y, test_size=0.2, random_state=42, stratify=y\n",
|
| 544 |
+
" )\n",
|
| 545 |
+
"\n",
|
| 546 |
+
" clf = RandomForestClassifier(n_estimators=100, random_state=42)\n",
|
| 547 |
+
" clf.fit(X_train, y_train)\n",
|
| 548 |
+
" predictions = clf.predict(X_test)\n",
|
| 549 |
+
" accuracy = accuracy_score(y_test, predictions)\n",
|
| 550 |
+
"\n",
|
| 551 |
+
" feature_importance = (\n",
|
| 552 |
+
" pd.Series(clf.feature_importances_, index=feature_columns)\n",
|
| 553 |
+
" .sort_values(ascending=False)\n",
|
| 554 |
+
" .to_frame(\"importance\")\n",
|
| 555 |
+
" )\n",
|
| 556 |
+
" save_table(feature_importance, \"feature_importance\")\n",
|
| 557 |
+
" created_tables.append(\"feature_importance.csv\")\n",
|
| 558 |
+
"\n",
|
| 559 |
+
" plt.figure(figsize=(7, 4))\n",
|
| 560 |
+
" plt.bar(feature_importance.index.astype(str), feature_importance[\"importance\"])\n",
|
| 561 |
+
" plt.title(\"Feature Importance for Recommendation Prediction\")\n",
|
| 562 |
+
" plt.xlabel(\"Feature\")\n",
|
| 563 |
+
" plt.ylabel(\"Importance\")\n",
|
| 564 |
+
" plt.tight_layout()\n",
|
| 565 |
+
" save_figure(\"feature_importance\")\n",
|
| 566 |
+
" created_figures.append(\"feature_importance.png\")\n",
|
| 567 |
+
" plt.close()\n",
|
| 568 |
+
"\n",
|
| 569 |
+
" report = \"Model accuracy: {:.4f}\\n\\n{}\".format(\n",
|
| 570 |
+
" accuracy,\n",
|
| 571 |
+
" classification_report(y_test, predictions)\n",
|
| 572 |
+
" )\n",
|
| 573 |
+
" save_text(report, \"classification_report\")\n",
|
| 574 |
+
"except Exception as e:\n",
|
| 575 |
+
" print(\"ML section skipped:\", repr(e))\n",
|
| 576 |
+
"\n",
|
| 577 |
+
"print(\"Artifact creation section finished.\")"
|
| 578 |
+
]
|
| 579 |
+
},
|
| 580 |
+
{
|
| 581 |
+
"cell_type": "code",
|
| 582 |
+
"execution_count": 5,
|
| 583 |
+
"id": "c4bbc916",
|
| 584 |
+
"metadata": {
|
| 585 |
+
"colab": {
|
| 586 |
+
"base_uri": "https://localhost:8080/"
|
| 587 |
+
},
|
| 588 |
+
"id": "c4bbc916",
|
| 589 |
+
"outputId": "1b70021e-6125-457a-bcd8-be0c896dfa58"
|
| 590 |
+
},
|
| 591 |
+
"outputs": [
|
| 592 |
+
{
|
| 593 |
+
"output_type": "stream",
|
| 594 |
+
"name": "stdout",
|
| 595 |
+
"text": [
|
| 596 |
+
"Saved table everywhere: dashboard_summary.csv\n",
|
| 597 |
+
"Saved text everywhere: business_insights_report.txt\n",
|
| 598 |
+
"STEP 2 COMPLETE.\n",
|
| 599 |
+
"Figures: ['average_rating_by_age.png', 'category_return_rate.png', 'feature_importance.png', 'monthly_return_rate.png', 'negative_keyword_counts.png', 'rating_distribution.png', 'recommendation_by_class.png']\n",
|
| 600 |
+
"Tables: ['average_rating_by_age.csv', 'category_return_rate.csv', 'dashboard_summary.csv', 'feature_importance.csv', 'monthly_return_rate.csv', 'negative_keyword_counts.csv', 'rating_distribution.csv', 'recommendation_by_class.csv']\n",
|
| 601 |
+
"Outputs: ['average_rating_by_age.csv', 'average_rating_by_age.png', 'business_insights_report.txt', 'category_return_rate.csv', 'category_return_rate.png', 'classification_report.txt', 'dashboard_summary.csv', 'feature_importance.csv', 'feature_importance.png', 'monthly_return_rate.csv', 'monthly_return_rate.png', 'negative_keyword_counts.csv', 'negative_keyword_counts.png', 'rating_distribution.csv', 'rating_distribution.png', 'recommendation_by_class.csv', 'recommendation_by_class.png']\n"
|
| 602 |
+
]
|
| 603 |
+
}
|
| 604 |
+
],
|
| 605 |
+
"source": [
|
| 606 |
+
"# ==================================================\n",
|
| 607 |
+
"# FINAL REPORT + MANIFEST\n",
|
| 608 |
+
"# ==================================================\n",
|
| 609 |
+
"\n",
|
| 610 |
+
"summary_rows = [\n",
|
| 611 |
+
" {\"metric\": \"reviews_rows\", \"value\": int(len(reviews_df))},\n",
|
| 612 |
+
" {\"metric\": \"returns_rows\", \"value\": int(len(returns_df))},\n",
|
| 613 |
+
" {\"metric\": \"figures_created\", \"value\": int(len(list(FIGURES.glob(\"*.png\"))))},\n",
|
| 614 |
+
" {\"metric\": \"tables_created\", \"value\": int(len(list(TABLES.glob(\"*.csv\"))))},\n",
|
| 615 |
+
"]\n",
|
| 616 |
+
"\n",
|
| 617 |
+
"summary_df = pd.DataFrame(summary_rows).set_index(\"metric\")\n",
|
| 618 |
+
"save_table(summary_df, \"dashboard_summary\")\n",
|
| 619 |
+
"\n",
|
| 620 |
+
"insights = \"\"\"\n",
|
| 621 |
+
"FINAL BUSINESS INSIGHTS\n",
|
| 622 |
+
"=======================\n",
|
| 623 |
+
"\n",
|
| 624 |
+
"This analysis supports an e-commerce return prediction and review intelligence assistant.\n",
|
| 625 |
+
"\n",
|
| 626 |
+
"Main findings:\n",
|
| 627 |
+
"- Customer ratings and recommendation behavior are useful signals for product satisfaction.\n",
|
| 628 |
+
"- Review text reveals return-risk themes such as fit, sizing, fabric, quality, and discomfort.\n",
|
| 629 |
+
"- Product categories with higher estimated return rates should be prioritized for improvement.\n",
|
| 630 |
+
"- Monthly return-rate tracking can help the business monitor operational or seasonal changes.\n",
|
| 631 |
+
"\n",
|
| 632 |
+
"Recommended automations:\n",
|
| 633 |
+
"1. Automatically scan new reviews for return-risk keywords.\n",
|
| 634 |
+
"2. Automatically rank products and categories by estimated return risk.\n",
|
| 635 |
+
"3. Automatically generate business recommendations for product pages, sizing guidance, and quality control.\n",
|
| 636 |
+
"\"\"\"\n",
|
| 637 |
+
"\n",
|
| 638 |
+
"save_text(insights, \"business_insights_report\")\n",
|
| 639 |
+
"\n",
|
| 640 |
+
"manifest = {\n",
|
| 641 |
+
" \"base_path\": str(BASE_PATH),\n",
|
| 642 |
+
" \"figures\": sorted([p.name for p in FIGURES.glob(\"*.png\")]),\n",
|
| 643 |
+
" \"tables\": sorted([p.name for p in TABLES.glob(\"*.csv\")]),\n",
|
| 644 |
+
" \"outputs\": sorted([p.name for p in OUTPUTS.iterdir() if p.is_file()]),\n",
|
| 645 |
+
"}\n",
|
| 646 |
+
"\n",
|
| 647 |
+
"for folder in [OUTPUTS, ARTIFACTS, TABLES]:\n",
|
| 648 |
+
" try:\n",
|
| 649 |
+
" with open(folder / \"artifacts_manifest.json\", \"w\", encoding=\"utf-8\") as f:\n",
|
| 650 |
+
" json.dump(manifest, f, indent=2)\n",
|
| 651 |
+
" except Exception as e:\n",
|
| 652 |
+
" print(f\"Could not save manifest in {folder}: {e}\")\n",
|
| 653 |
+
"\n",
|
| 654 |
+
"print(\"STEP 2 COMPLETE.\")\n",
|
| 655 |
+
"print(\"Figures:\", manifest[\"figures\"])\n",
|
| 656 |
+
"print(\"Tables:\", manifest[\"tables\"])\n",
|
| 657 |
+
"print(\"Outputs:\", manifest[\"outputs\"])"
|
| 658 |
+
]
|
| 659 |
+
},
|
| 660 |
+
{
|
| 661 |
+
"cell_type": "code",
|
| 662 |
+
"source": [
|
| 663 |
+
"print(\"\\nFINAL ARTIFACT CHECK\")\n",
|
| 664 |
+
"\n",
|
| 665 |
+
"check_dirs = {\n",
|
| 666 |
+
" \"FIGURES\": FIGURES,\n",
|
| 667 |
+
" \"TABLES\": TABLES,\n",
|
| 668 |
+
" \"OUTPUTS\": OUTPUTS,\n",
|
| 669 |
+
" \"OUTPUT_FIGURES\": OUTPUT_FIGURES,\n",
|
| 670 |
+
" \"OUTPUT_TABLES\": OUTPUT_TABLES,\n",
|
| 671 |
+
" \"ARTIFACTS\": ARTIFACTS,\n",
|
| 672 |
+
" \"ARTIFACT_FIGURES\": ARTIFACT_FIGURES,\n",
|
| 673 |
+
" \"ARTIFACT_TABLES\": ARTIFACT_TABLES,\n",
|
| 674 |
+
"}\n",
|
| 675 |
+
"\n",
|
| 676 |
+
"for label, folder in check_dirs.items():\n",
|
| 677 |
+
" files = sorted([p.name for p in folder.iterdir() if p.is_file()])\n",
|
| 678 |
+
" print(label, \"=\", files)"
|
| 679 |
+
],
|
| 680 |
+
"metadata": {
|
| 681 |
+
"colab": {
|
| 682 |
+
"base_uri": "https://localhost:8080/"
|
| 683 |
+
},
|
| 684 |
+
"id": "fexa62gDM2c7",
|
| 685 |
+
"outputId": "92a75649-5c5b-4202-ba1c-839682d28eee"
|
| 686 |
+
},
|
| 687 |
+
"id": "fexa62gDM2c7",
|
| 688 |
+
"execution_count": 6,
|
| 689 |
+
"outputs": [
|
| 690 |
+
{
|
| 691 |
+
"output_type": "stream",
|
| 692 |
+
"name": "stdout",
|
| 693 |
+
"text": [
|
| 694 |
+
"\n",
|
| 695 |
+
"FINAL ARTIFACT CHECK\n",
|
| 696 |
+
"FIGURES = ['average_rating_by_age.png', 'category_return_rate.png', 'feature_importance.png', 'monthly_return_rate.png', 'negative_keyword_counts.png', 'rating_distribution.png', 'recommendation_by_class.png']\n",
|
| 697 |
+
"TABLES = ['artifacts_manifest.json', 'average_rating_by_age.csv', 'business_insights_report.txt', 'category_return_rate.csv', 'classification_report.txt', 'dashboard_summary.csv', 'feature_importance.csv', 'monthly_return_rate.csv', 'negative_keyword_counts.csv', 'rating_distribution.csv', 'recommendation_by_class.csv']\n",
|
| 698 |
+
"OUTPUTS = ['artifacts_manifest.json', 'average_rating_by_age.csv', 'average_rating_by_age.png', 'business_insights_report.txt', 'category_return_rate.csv', 'category_return_rate.png', 'classification_report.txt', 'dashboard_summary.csv', 'feature_importance.csv', 'feature_importance.png', 'monthly_return_rate.csv', 'monthly_return_rate.png', 'negative_keyword_counts.csv', 'negative_keyword_counts.png', 'rating_distribution.csv', 'rating_distribution.png', 'recommendation_by_class.csv', 'recommendation_by_class.png']\n",
|
| 699 |
+
"OUTPUT_FIGURES = ['average_rating_by_age.png', 'category_return_rate.png', 'feature_importance.png', 'monthly_return_rate.png', 'negative_keyword_counts.png', 'rating_distribution.png', 'recommendation_by_class.png']\n",
|
| 700 |
+
"OUTPUT_TABLES = ['average_rating_by_age.csv', 'business_insights_report.txt', 'category_return_rate.csv', 'classification_report.txt', 'dashboard_summary.csv', 'feature_importance.csv', 'monthly_return_rate.csv', 'negative_keyword_counts.csv', 'rating_distribution.csv', 'recommendation_by_class.csv']\n",
|
| 701 |
+
"ARTIFACTS = ['artifacts_manifest.json', 'average_rating_by_age.csv', 'average_rating_by_age.png', 'business_insights_report.txt', 'category_return_rate.csv', 'category_return_rate.png', 'classification_report.txt', 'dashboard_summary.csv', 'feature_importance.csv', 'feature_importance.png', 'monthly_return_rate.csv', 'monthly_return_rate.png', 'negative_keyword_counts.csv', 'negative_keyword_counts.png', 'rating_distribution.csv', 'rating_distribution.png', 'recommendation_by_class.csv', 'recommendation_by_class.png']\n",
|
| 702 |
+
"ARTIFACT_FIGURES = ['average_rating_by_age.png', 'category_return_rate.png', 'feature_importance.png', 'monthly_return_rate.png', 'negative_keyword_counts.png', 'rating_distribution.png', 'recommendation_by_class.png']\n",
|
| 703 |
+
"ARTIFACT_TABLES = ['average_rating_by_age.csv', 'business_insights_report.txt', 'category_return_rate.csv', 'classification_report.txt', 'dashboard_summary.csv', 'feature_importance.csv', 'monthly_return_rate.csv', 'negative_keyword_counts.csv', 'rating_distribution.csv', 'recommendation_by_class.csv']\n"
|
| 704 |
+
]
|
| 705 |
+
}
|
| 706 |
+
]
|
| 707 |
+
},
|
| 708 |
+
{
|
| 709 |
+
"cell_type": "code",
|
| 710 |
+
"source": [
|
| 711 |
+
"# ==================================================\n",
|
| 712 |
+
"# FORCE DASHBOARD ARTIFACTS FOR SE21 HUGGING FACE APP\n",
|
| 713 |
+
"# Put this as the VERY LAST CELL of pythonanalysis.ipynb\n",
|
| 714 |
+
"# ==================================================\n",
|
| 715 |
+
"\n",
|
| 716 |
+
"import os\n",
|
| 717 |
+
"import json\n",
|
| 718 |
+
"from pathlib import Path\n",
|
| 719 |
+
"\n",
|
| 720 |
+
"import pandas as pd\n",
|
| 721 |
+
"import numpy as np\n",
|
| 722 |
+
"\n",
|
| 723 |
+
"import matplotlib\n",
|
| 724 |
+
"matplotlib.use(\"Agg\")\n",
|
| 725 |
+
"import matplotlib.pyplot as plt\n",
|
| 726 |
+
"\n",
|
| 727 |
+
"# Detect runtime\n",
|
| 728 |
+
"if Path(\"/app\").exists():\n",
|
| 729 |
+
" BASE_PATH = Path(\"/app\")\n",
|
| 730 |
+
"elif Path(\"/content\").exists():\n",
|
| 731 |
+
" BASE_PATH = Path(\"/content\")\n",
|
| 732 |
+
"else:\n",
|
| 733 |
+
" BASE_PATH = Path.cwd()\n",
|
| 734 |
+
"\n",
|
| 735 |
+
"# THESE ARE THE EXACT FOLDERS app.py READS\n",
|
| 736 |
+
"PY_FIG_DIR = BASE_PATH / \"artifacts\" / \"py\" / \"figures\"\n",
|
| 737 |
+
"PY_TAB_DIR = BASE_PATH / \"artifacts\" / \"py\" / \"tables\"\n",
|
| 738 |
+
"\n",
|
| 739 |
+
"PY_FIG_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 740 |
+
"PY_TAB_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 741 |
+
"\n",
|
| 742 |
+
"print(\"Saving dashboard artifacts to:\")\n",
|
| 743 |
+
"print(\"Figures:\", PY_FIG_DIR)\n",
|
| 744 |
+
"print(\"Tables:\", PY_TAB_DIR)\n",
|
| 745 |
+
"\n",
|
| 746 |
+
"# Find CSV files\n",
|
| 747 |
+
"csv_paths = [\n",
|
| 748 |
+
" p for p in BASE_PATH.rglob(\"*.csv\")\n",
|
| 749 |
+
" if \"sample_data\" not in str(p)\n",
|
| 750 |
+
" and \"artifacts\" not in str(p)\n",
|
| 751 |
+
" and \"outputs\" not in str(p)\n",
|
| 752 |
+
" and \"figures\" not in str(p)\n",
|
| 753 |
+
" and \"tables\" not in str(p)\n",
|
| 754 |
+
"]\n",
|
| 755 |
+
"\n",
|
| 756 |
+
"print(\"CSV files found:\")\n",
|
| 757 |
+
"for p in csv_paths:\n",
|
| 758 |
+
" print(\"-\", p)\n",
|
| 759 |
+
"\n",
|
| 760 |
+
"# Find reviews dataset\n",
|
| 761 |
+
"reviews_candidates = [\n",
|
| 762 |
+
" BASE_PATH / \"data_processed\" / \"reviews_cleaned.csv\",\n",
|
| 763 |
+
" BASE_PATH / \"Womens Clothing E-Commerce Reviews.csv\",\n",
|
| 764 |
+
"]\n",
|
| 765 |
+
"\n",
|
| 766 |
+
"reviews_path = next((p for p in reviews_candidates if p.exists()), None)\n",
|
| 767 |
+
"\n",
|
| 768 |
+
"if reviews_path is None:\n",
|
| 769 |
+
" matches = [\n",
|
| 770 |
+
" p for p in csv_paths\n",
|
| 771 |
+
" if \"clothing\" in p.name.lower() or \"review\" in p.name.lower()\n",
|
| 772 |
+
" ]\n",
|
| 773 |
+
" reviews_path = matches[0] if matches else None\n",
|
| 774 |
+
"\n",
|
| 775 |
+
"# Find returns dataset\n",
|
| 776 |
+
"returns_candidates = [\n",
|
| 777 |
+
" BASE_PATH / \"data_processed\" / \"returns_input.csv\",\n",
|
| 778 |
+
" BASE_PATH / \"data_processed\" / \"returns_cleaned.csv\",\n",
|
| 779 |
+
" BASE_PATH / \"ecommerce_returns_cleaned.csv\",\n",
|
| 780 |
+
" BASE_PATH / \"data_processed\" / \"synthetic_return_risk.csv\",\n",
|
| 781 |
+
"]\n",
|
| 782 |
+
"\n",
|
| 783 |
+
"returns_path = next((p for p in returns_candidates if p.exists()), None)\n",
|
| 784 |
+
"\n",
|
| 785 |
+
"if returns_path is None:\n",
|
| 786 |
+
" matches = [\n",
|
| 787 |
+
" p for p in csv_paths\n",
|
| 788 |
+
" if \"return\" in p.name.lower()\n",
|
| 789 |
+
" ]\n",
|
| 790 |
+
" returns_path = matches[0] if matches else None\n",
|
| 791 |
+
"\n",
|
| 792 |
+
"if reviews_path is None:\n",
|
| 793 |
+
" raise FileNotFoundError(\"Could not find reviews CSV.\")\n",
|
| 794 |
+
"\n",
|
| 795 |
+
"if returns_path is None:\n",
|
| 796 |
+
" raise FileNotFoundError(\"Could not find returns CSV.\")\n",
|
| 797 |
+
"\n",
|
| 798 |
+
"print(\"Using reviews:\", reviews_path)\n",
|
| 799 |
+
"print(\"Using returns:\", returns_path)\n",
|
| 800 |
+
"\n",
|
| 801 |
+
"reviews_df = pd.read_csv(reviews_path).drop(columns=[\"Unnamed: 0\"], errors=\"ignore\")\n",
|
| 802 |
+
"returns_df = pd.read_csv(returns_path).drop(columns=[\"Unnamed: 0\"], errors=\"ignore\")\n",
|
| 803 |
+
"\n",
|
| 804 |
+
"print(\"Reviews shape:\", reviews_df.shape)\n",
|
| 805 |
+
"print(\"Returns shape:\", returns_df.shape)\n",
|
| 806 |
+
"\n",
|
| 807 |
+
"# --------------------------------------------------\n",
|
| 808 |
+
"# 1. Rating distribution\n",
|
| 809 |
+
"# --------------------------------------------------\n",
|
| 810 |
+
"if \"Rating\" in reviews_df.columns:\n",
|
| 811 |
+
" rating_distribution = (\n",
|
| 812 |
+
" reviews_df[\"Rating\"]\n",
|
| 813 |
+
" .dropna()\n",
|
| 814 |
+
" .value_counts()\n",
|
| 815 |
+
" .sort_index()\n",
|
| 816 |
+
" .reset_index()\n",
|
| 817 |
+
" )\n",
|
| 818 |
+
" rating_distribution.columns = [\"rating\", \"count\"]\n",
|
| 819 |
+
"\n",
|
| 820 |
+
" rating_distribution.to_csv(PY_TAB_DIR / \"rating_distribution.csv\", index=False)\n",
|
| 821 |
+
"\n",
|
| 822 |
+
" plt.figure(figsize=(7, 4))\n",
|
| 823 |
+
" plt.bar(rating_distribution[\"rating\"].astype(str), rating_distribution[\"count\"])\n",
|
| 824 |
+
" plt.title(\"Distribution of Customer Ratings\")\n",
|
| 825 |
+
" plt.xlabel(\"Rating\")\n",
|
| 826 |
+
" plt.ylabel(\"Number of Reviews\")\n",
|
| 827 |
+
" plt.tight_layout()\n",
|
| 828 |
+
" plt.savefig(PY_FIG_DIR / \"rating_distribution.png\", dpi=150, bbox_inches=\"tight\")\n",
|
| 829 |
+
" plt.close()\n",
|
| 830 |
+
"\n",
|
| 831 |
+
"# --------------------------------------------------\n",
|
| 832 |
+
"# 2. Sentiment counts for app's sentiment chart\n",
|
| 833 |
+
"# The app specifically looks for sentiment_counts_sampled.csv\n",
|
| 834 |
+
"# --------------------------------------------------\n",
|
| 835 |
+
"if \"Rating\" in reviews_df.columns:\n",
|
| 836 |
+
" temp = reviews_df.copy()\n",
|
| 837 |
+
"\n",
|
| 838 |
+
" def rating_to_sentiment(r):\n",
|
| 839 |
+
" try:\n",
|
| 840 |
+
" r = float(r)\n",
|
| 841 |
+
" if r <= 2:\n",
|
| 842 |
+
" return \"negative\"\n",
|
| 843 |
+
" elif r == 3:\n",
|
| 844 |
+
" return \"neutral\"\n",
|
| 845 |
+
" else:\n",
|
| 846 |
+
" return \"positive\"\n",
|
| 847 |
+
" except:\n",
|
| 848 |
+
" return \"neutral\"\n",
|
| 849 |
+
"\n",
|
| 850 |
+
" temp[\"sentiment\"] = temp[\"Rating\"].apply(rating_to_sentiment)\n",
|
| 851 |
+
"\n",
|
| 852 |
+
" group_col = \"Class Name\" if \"Class Name\" in temp.columns else None\n",
|
| 853 |
+
"\n",
|
| 854 |
+
" if group_col:\n",
|
| 855 |
+
" sentiment_counts = (\n",
|
| 856 |
+
" temp.groupby([group_col, \"sentiment\"])\n",
|
| 857 |
+
" .size()\n",
|
| 858 |
+
" .unstack(fill_value=0)\n",
|
| 859 |
+
" .reset_index()\n",
|
| 860 |
+
" .head(15)\n",
|
| 861 |
+
" )\n",
|
| 862 |
+
" sentiment_counts = sentiment_counts.rename(columns={group_col: \"title\"})\n",
|
| 863 |
+
" else:\n",
|
| 864 |
+
" sentiment_counts = (\n",
|
| 865 |
+
" temp[\"sentiment\"]\n",
|
| 866 |
+
" .value_counts()\n",
|
| 867 |
+
" .to_frame()\n",
|
| 868 |
+
" .T\n",
|
| 869 |
+
" .reset_index(drop=True)\n",
|
| 870 |
+
" )\n",
|
| 871 |
+
" sentiment_counts.insert(0, \"title\", \"All Reviews\")\n",
|
| 872 |
+
"\n",
|
| 873 |
+
" for col in [\"negative\", \"neutral\", \"positive\"]:\n",
|
| 874 |
+
" if col not in sentiment_counts.columns:\n",
|
| 875 |
+
" sentiment_counts[col] = 0\n",
|
| 876 |
+
"\n",
|
| 877 |
+
" sentiment_counts[[\"title\", \"negative\", \"neutral\", \"positive\"]].to_csv(\n",
|
| 878 |
+
" PY_TAB_DIR / \"sentiment_counts_sampled.csv\",\n",
|
| 879 |
+
" index=False\n",
|
| 880 |
+
" )\n",
|
| 881 |
+
"\n",
|
| 882 |
+
" # Also save a normal figure\n",
|
| 883 |
+
" sentiment_total = temp[\"sentiment\"].value_counts().reindex(\n",
|
| 884 |
+
" [\"negative\", \"neutral\", \"positive\"],\n",
|
| 885 |
+
" fill_value=0\n",
|
| 886 |
+
" )\n",
|
| 887 |
+
"\n",
|
| 888 |
+
" plt.figure(figsize=(7, 4))\n",
|
| 889 |
+
" plt.bar(sentiment_total.index, sentiment_total.values)\n",
|
| 890 |
+
" plt.title(\"Review Sentiment Distribution\")\n",
|
| 891 |
+
" plt.xlabel(\"Sentiment\")\n",
|
| 892 |
+
" plt.ylabel(\"Number of Reviews\")\n",
|
| 893 |
+
" plt.tight_layout()\n",
|
| 894 |
+
" plt.savefig(PY_FIG_DIR / \"sentiment_distribution.png\", dpi=150, bbox_inches=\"tight\")\n",
|
| 895 |
+
" plt.close()\n",
|
| 896 |
+
"\n",
|
| 897 |
+
"# --------------------------------------------------\n",
|
| 898 |
+
"# 3. Category return rate\n",
|
| 899 |
+
"# --------------------------------------------------\n",
|
| 900 |
+
"return_col = None\n",
|
| 901 |
+
"for candidate in [\"likely_return\", \"synthetic_return_risk\", \"returned\", \"return_flag\"]:\n",
|
| 902 |
+
" if candidate in returns_df.columns:\n",
|
| 903 |
+
" return_col = candidate\n",
|
| 904 |
+
" break\n",
|
| 905 |
+
"\n",
|
| 906 |
+
"category_col = None\n",
|
| 907 |
+
"for candidate in [\"product_category_name\", \"category\", \"Class Name\", \"product_id\"]:\n",
|
| 908 |
+
" if candidate in returns_df.columns:\n",
|
| 909 |
+
" category_col = candidate\n",
|
| 910 |
+
" break\n",
|
| 911 |
+
"\n",
|
| 912 |
+
"if return_col is not None:\n",
|
| 913 |
+
" returns_df[return_col] = pd.to_numeric(returns_df[return_col], errors=\"coerce\")\n",
|
| 914 |
+
"\n",
|
| 915 |
+
"if return_col is not None and category_col is not None:\n",
|
| 916 |
+
" category_return_rate = (\n",
|
| 917 |
+
" returns_df.groupby(category_col)[return_col]\n",
|
| 918 |
+
" .mean()\n",
|
| 919 |
+
" .sort_values(ascending=False)\n",
|
| 920 |
+
" .head(15)\n",
|
| 921 |
+
" .reset_index()\n",
|
| 922 |
+
" )\n",
|
| 923 |
+
" category_return_rate.columns = [\"category\", \"return_rate\"]\n",
|
| 924 |
+
"\n",
|
| 925 |
+
" category_return_rate.to_csv(PY_TAB_DIR / \"category_return_rate.csv\", index=False)\n",
|
| 926 |
+
"\n",
|
| 927 |
+
" plt.figure(figsize=(11, 5))\n",
|
| 928 |
+
" plt.bar(category_return_rate[\"category\"].astype(str), category_return_rate[\"return_rate\"])\n",
|
| 929 |
+
" plt.title(\"Highest Return-Rate Categories\")\n",
|
| 930 |
+
" plt.xlabel(\"Category\")\n",
|
| 931 |
+
" plt.ylabel(\"Return Rate\")\n",
|
| 932 |
+
" plt.xticks(rotation=75)\n",
|
| 933 |
+
" plt.tight_layout()\n",
|
| 934 |
+
" plt.savefig(PY_FIG_DIR / \"category_return_rate.png\", dpi=150, bbox_inches=\"tight\")\n",
|
| 935 |
+
" plt.close()\n",
|
| 936 |
+
"\n",
|
| 937 |
+
" # The template's AI fallback weirdly expects this filename for \"top\" questions.\n",
|
| 938 |
+
" # We reuse it to show highest return-risk categories.\n",
|
| 939 |
+
" top_titles_by_units_sold = category_return_rate.copy()\n",
|
| 940 |
+
" top_titles_by_units_sold.columns = [\"title\", \"units_sold\"]\n",
|
| 941 |
+
" top_titles_by_units_sold.to_csv(PY_TAB_DIR / \"top_titles_by_units_sold.csv\", index=False)\n",
|
| 942 |
+
"\n",
|
| 943 |
+
"# --------------------------------------------------\n",
|
| 944 |
+
"# 4. Dashboard time-series file\n",
|
| 945 |
+
"# The app's dashboard chart specifically looks for df_dashboard.csv\n",
|
| 946 |
+
"# --------------------------------------------------\n",
|
| 947 |
+
"if \"order_purchase_timestamp\" in returns_df.columns and return_col is not None:\n",
|
| 948 |
+
" ts = returns_df.copy()\n",
|
| 949 |
+
" ts[\"order_purchase_timestamp\"] = pd.to_datetime(\n",
|
| 950 |
+
" ts[\"order_purchase_timestamp\"],\n",
|
| 951 |
+
" errors=\"coerce\"\n",
|
| 952 |
+
" )\n",
|
| 953 |
+
" ts = ts.dropna(subset=[\"order_purchase_timestamp\"])\n",
|
| 954 |
+
"\n",
|
| 955 |
+
" if not ts.empty:\n",
|
| 956 |
+
" dashboard_df = (\n",
|
| 957 |
+
" ts.set_index(\"order_purchase_timestamp\")\n",
|
| 958 |
+
" .resample(\"M\")\n",
|
| 959 |
+
" .agg(\n",
|
| 960 |
+
" return_rate=(return_col, \"mean\"),\n",
|
| 961 |
+
" orders=(return_col, \"count\")\n",
|
| 962 |
+
" )\n",
|
| 963 |
+
" .reset_index()\n",
|
| 964 |
+
" )\n",
|
| 965 |
+
" dashboard_df = dashboard_df.rename(columns={\"order_purchase_timestamp\": \"month\"})\n",
|
| 966 |
+
" else:\n",
|
| 967 |
+
" dashboard_df = pd.DataFrame({\n",
|
| 968 |
+
" \"month\": pd.date_range(\"2024-01-01\", periods=3, freq=\"M\"),\n",
|
| 969 |
+
" \"return_rate\": [0, 0, 0],\n",
|
| 970 |
+
" \"orders\": [0, 0, 0],\n",
|
| 971 |
+
" })\n",
|
| 972 |
+
"else:\n",
|
| 973 |
+
" dashboard_df = pd.DataFrame({\n",
|
| 974 |
+
" \"month\": pd.date_range(\"2024-01-01\", periods=3, freq=\"M\"),\n",
|
| 975 |
+
" \"return_rate\": [0, 0, 0],\n",
|
| 976 |
+
" \"orders\": [0, 0, 0],\n",
|
| 977 |
+
" })\n",
|
| 978 |
+
"\n",
|
| 979 |
+
"dashboard_df.to_csv(PY_TAB_DIR / \"df_dashboard.csv\", index=False)\n",
|
| 980 |
+
"\n",
|
| 981 |
+
"plt.figure(figsize=(9, 4))\n",
|
| 982 |
+
"plt.plot(pd.to_datetime(dashboard_df[\"month\"]), dashboard_df[\"return_rate\"], marker=\"o\")\n",
|
| 983 |
+
"plt.title(\"Monthly Estimated Return Rate\")\n",
|
| 984 |
+
"plt.xlabel(\"Month\")\n",
|
| 985 |
+
"plt.ylabel(\"Return Rate\")\n",
|
| 986 |
+
"plt.tight_layout()\n",
|
| 987 |
+
"plt.savefig(PY_FIG_DIR / \"monthly_return_rate.png\", dpi=150, bbox_inches=\"tight\")\n",
|
| 988 |
+
"plt.close()\n",
|
| 989 |
+
"\n",
|
| 990 |
+
"# --------------------------------------------------\n",
|
| 991 |
+
"# 5. KPIs\n",
|
| 992 |
+
"# --------------------------------------------------\n",
|
| 993 |
+
"kpis = {\n",
|
| 994 |
+
" \"reviews_rows\": int(len(reviews_df)),\n",
|
| 995 |
+
" \"returns_rows\": int(len(returns_df)),\n",
|
| 996 |
+
" \"n_titles\": int(reviews_df[\"Clothing ID\"].nunique()) if \"Clothing ID\" in reviews_df.columns else int(len(reviews_df)),\n",
|
| 997 |
+
" \"n_months\": int(len(dashboard_df)),\n",
|
| 998 |
+
" \"total_units_sold\": int(len(returns_df)),\n",
|
| 999 |
+
" \"estimated_return_rate\": float(returns_df[return_col].mean()) if return_col is not None else None,\n",
|
| 1000 |
+
"}\n",
|
| 1001 |
+
"\n",
|
| 1002 |
+
"with open(PY_TAB_DIR / \"kpis.json\", \"w\", encoding=\"utf-8\") as f:\n",
|
| 1003 |
+
" json.dump(kpis, f, indent=2)\n",
|
| 1004 |
+
"\n",
|
| 1005 |
+
"# --------------------------------------------------\n",
|
| 1006 |
+
"# Final verification\n",
|
| 1007 |
+
"# --------------------------------------------------\n",
|
| 1008 |
+
"print(\"\\nFORCE ARTIFACT CELL RAN SUCCESSFULLY\")\n",
|
| 1009 |
+
"print(\"Figures now in app-readable folder:\")\n",
|
| 1010 |
+
"print(sorted([p.name for p in PY_FIG_DIR.glob(\"*\")]))\n",
|
| 1011 |
+
"\n",
|
| 1012 |
+
"print(\"Tables now in app-readable folder:\")\n",
|
| 1013 |
+
"print(sorted([p.name for p in PY_TAB_DIR.glob(\"*\")]))"
|
| 1014 |
+
],
|
| 1015 |
+
"metadata": {
|
| 1016 |
+
"id": "G-jXRriWP1TW",
|
| 1017 |
+
"outputId": "69ac490c-cb7b-479f-b5b9-d85e02b0ba1d",
|
| 1018 |
+
"colab": {
|
| 1019 |
+
"base_uri": "https://localhost:8080/"
|
| 1020 |
+
}
|
| 1021 |
+
},
|
| 1022 |
+
"id": "G-jXRriWP1TW",
|
| 1023 |
+
"execution_count": 7,
|
| 1024 |
+
"outputs": [
|
| 1025 |
+
{
|
| 1026 |
+
"output_type": "stream",
|
| 1027 |
+
"name": "stdout",
|
| 1028 |
+
"text": [
|
| 1029 |
+
"Saving dashboard artifacts to:\n",
|
| 1030 |
+
"Figures: /content/artifacts/py/figures\n",
|
| 1031 |
+
"Tables: /content/artifacts/py/tables\n",
|
| 1032 |
+
"CSV files found:\n",
|
| 1033 |
+
"- /content/Womens Clothing E-Commerce Reviews.csv\n",
|
| 1034 |
+
"- /content/ecommerce_returns_cleaned.csv\n",
|
| 1035 |
+
"Using reviews: /content/Womens Clothing E-Commerce Reviews.csv\n",
|
| 1036 |
+
"Using returns: /content/ecommerce_returns_cleaned.csv\n",
|
| 1037 |
+
"Reviews shape: (23486, 10)\n",
|
| 1038 |
+
"Returns shape: (113314, 29)\n",
|
| 1039 |
+
"\n",
|
| 1040 |
+
"FORCE ARTIFACT CELL RAN SUCCESSFULLY\n",
|
| 1041 |
+
"Figures now in app-readable folder:\n",
|
| 1042 |
+
"['category_return_rate.png', 'monthly_return_rate.png', 'rating_distribution.png', 'sentiment_distribution.png']\n",
|
| 1043 |
+
"Tables now in app-readable folder:\n",
|
| 1044 |
+
"['category_return_rate.csv', 'df_dashboard.csv', 'kpis.json', 'rating_distribution.csv', 'sentiment_counts_sampled.csv', 'top_titles_by_units_sold.csv']\n"
|
| 1045 |
+
]
|
| 1046 |
+
}
|
| 1047 |
+
]
|
| 1048 |
+
},
|
| 1049 |
+
{
|
| 1050 |
+
"cell_type": "markdown",
|
| 1051 |
+
"source": [
|
| 1052 |
+
"2.3 ARIMA Pricfe Forecasting"
|
| 1053 |
+
],
|
| 1054 |
+
"metadata": {
|
| 1055 |
+
"id": "WztEFgicJAfE"
|
| 1056 |
+
},
|
| 1057 |
+
"id": "WztEFgicJAfE"
|
| 1058 |
+
},
|
| 1059 |
+
{
|
| 1060 |
+
"cell_type": "code",
|
| 1061 |
+
"source": [
|
| 1062 |
+
"# ==================================================\n",
|
| 1063 |
+
"# ARIMA PRICE FORECASTING\n",
|
| 1064 |
+
"# ==================================================\n",
|
| 1065 |
+
"\n",
|
| 1066 |
+
"!pip install statsmodels --quiet\n",
|
| 1067 |
+
"\n",
|
| 1068 |
+
"from statsmodels.tsa.arima.model import ARIMA\n",
|
| 1069 |
+
"from statsmodels.tsa.stattools import adfuller\n",
|
| 1070 |
+
"import matplotlib.pyplot as plt\n",
|
| 1071 |
+
"import warnings\n",
|
| 1072 |
+
"warnings.filterwarnings(\"ignore\")\n",
|
| 1073 |
+
"\n",
|
| 1074 |
+
"# Build a monthly average price time series from returns data\n",
|
| 1075 |
+
"if \"price\" in returns_df.columns and \"order_purchase_timestamp\" in returns_df.columns:\n",
|
| 1076 |
+
" ts_price = returns_df.copy()\n",
|
| 1077 |
+
" ts_price[\"order_purchase_timestamp\"] = pd.to_datetime(\n",
|
| 1078 |
+
" ts_price[\"order_purchase_timestamp\"], errors=\"coerce\"\n",
|
| 1079 |
+
" )\n",
|
| 1080 |
+
" ts_price = ts_price.dropna(subset=[\"order_purchase_timestamp\", \"price\"])\n",
|
| 1081 |
+
"\n",
|
| 1082 |
+
" monthly_price = (\n",
|
| 1083 |
+
" ts_price.set_index(\"order_purchase_timestamp\")\n",
|
| 1084 |
+
" .resample(\"M\")[\"price\"]\n",
|
| 1085 |
+
" .mean()\n",
|
| 1086 |
+
" .dropna()\n",
|
| 1087 |
+
" )\n",
|
| 1088 |
+
"\n",
|
| 1089 |
+
" print(\"Monthly price series shape:\", monthly_price.shape)\n",
|
| 1090 |
+
" print(monthly_price.tail())\n",
|
| 1091 |
+
"\n",
|
| 1092 |
+
" # --- Stationarity check ---\n",
|
| 1093 |
+
" adf_result = adfuller(monthly_price)\n",
|
| 1094 |
+
" print(f\"\\nADF Statistic: {adf_result[0]:.4f}\")\n",
|
| 1095 |
+
" print(f\"p-value: {adf_result[1]:.4f}\")\n",
|
| 1096 |
+
" if adf_result[1] < 0.05:\n",
|
| 1097 |
+
" print(\"Series is stationary — good for ARIMA.\")\n",
|
| 1098 |
+
" else:\n",
|
| 1099 |
+
" print(\"Series is NOT stationary — differencing will be applied (d=1).\")\n",
|
| 1100 |
+
"\n",
|
| 1101 |
+
" # --- Fit ARIMA ---\n",
|
| 1102 |
+
" # p=2 (autoregression), d=1 (differencing), q=1 (moving average)\n",
|
| 1103 |
+
" model = ARIMA(monthly_price, order=(2, 1, 1))\n",
|
| 1104 |
+
" model_fit = model.fit()\n",
|
| 1105 |
+
" print(\"\\nARIMA Model Summary:\")\n",
|
| 1106 |
+
" print(model_fit.summary())\n",
|
| 1107 |
+
"\n",
|
| 1108 |
+
" # --- Forecast next 6 months ---\n",
|
| 1109 |
+
" forecast_steps = 6\n",
|
| 1110 |
+
" forecast = model_fit.forecast(steps=forecast_steps)\n",
|
| 1111 |
+
" forecast_index = pd.date_range(\n",
|
| 1112 |
+
" start=monthly_price.index[-1] + pd.DateOffset(months=1),\n",
|
| 1113 |
+
" periods=forecast_steps,\n",
|
| 1114 |
+
" freq=\"M\"\n",
|
| 1115 |
+
" )\n",
|
| 1116 |
+
" forecast_series = pd.Series(forecast.values, index=forecast_index)\n",
|
| 1117 |
+
"\n",
|
| 1118 |
+
" # --- Plot ---\n",
|
| 1119 |
+
" plt.figure(figsize=(12, 5))\n",
|
| 1120 |
+
" plt.plot(monthly_price, label=\"Historical Price\", marker=\"o\")\n",
|
| 1121 |
+
" plt.plot(forecast_series, label=\"ARIMA Forecast (6 months)\",\n",
|
| 1122 |
+
" marker=\"o\", linestyle=\"--\", color=\"orange\")\n",
|
| 1123 |
+
" plt.axvline(x=monthly_price.index[-1], color=\"gray\",\n",
|
| 1124 |
+
" linestyle=\":\", label=\"Forecast Start\")\n",
|
| 1125 |
+
" plt.title(\"Monthly Average Price — ARIMA Forecast\")\n",
|
| 1126 |
+
" plt.xlabel(\"Month\")\n",
|
| 1127 |
+
" plt.ylabel(\"Average Price (€)\")\n",
|
| 1128 |
+
" plt.legend()\n",
|
| 1129 |
+
" plt.tight_layout()\n",
|
| 1130 |
+
" plt.savefig(PY_FIG_DIR / \"arima_price_forecast.png\", dpi=150, bbox_inches=\"tight\")\n",
|
| 1131 |
+
" plt.show()\n",
|
| 1132 |
+
" plt.close()\n",
|
| 1133 |
+
"\n",
|
| 1134 |
+
" # --- Save forecast table ---\n",
|
| 1135 |
+
" forecast_df = pd.DataFrame({\n",
|
| 1136 |
+
" \"month\": forecast_series.index,\n",
|
| 1137 |
+
" \"forecasted_price\": forecast_series.values.round(2)\n",
|
| 1138 |
+
" })\n",
|
| 1139 |
+
" forecast_df.to_csv(PY_TAB_DIR / \"arima_price_forecast.csv\", index=False)\n",
|
| 1140 |
+
"\n",
|
| 1141 |
+
" print(\"\\nForecast for next 6 months:\")\n",
|
| 1142 |
+
" display(forecast_df)\n",
|
| 1143 |
+
" print(\"Saved forecast to arima_price_forecast.csv\")\n",
|
| 1144 |
+
"\n",
|
| 1145 |
+
"else:\n",
|
| 1146 |
+
" print(\"Required columns 'price' or 'order_purchase_timestamp' not found in returns_df.\")\n",
|
| 1147 |
+
" print(\"Available columns:\", returns_df.columns.tolist())"
|
| 1148 |
+
],
|
| 1149 |
+
"metadata": {
|
| 1150 |
+
"colab": {
|
| 1151 |
+
"base_uri": "https://localhost:8080/",
|
| 1152 |
+
"height": 1000
|
| 1153 |
+
},
|
| 1154 |
+
"id": "3gv4S_a-Gyt8",
|
| 1155 |
+
"outputId": "63b8278e-772d-41ed-9c05-acfd5b0e3a3c"
|
| 1156 |
+
},
|
| 1157 |
+
"id": "3gv4S_a-Gyt8",
|
| 1158 |
+
"execution_count": 8,
|
| 1159 |
+
"outputs": [
|
| 1160 |
+
{
|
| 1161 |
+
"output_type": "stream",
|
| 1162 |
+
"name": "stdout",
|
| 1163 |
+
"text": [
|
| 1164 |
+
"Monthly price series shape: (24,)\n",
|
| 1165 |
+
"order_purchase_timestamp\n",
|
| 1166 |
+
"2018-05-31 125.654273\n",
|
| 1167 |
+
"2018-06-30 122.241141\n",
|
| 1168 |
+
"2018-07-31 126.141411\n",
|
| 1169 |
+
"2018-08-31 117.897993\n",
|
| 1170 |
+
"2018-09-30 145.000000\n",
|
| 1171 |
+
"Name: price, dtype: float64\n",
|
| 1172 |
+
"\n",
|
| 1173 |
+
"ADF Statistic: -6.4329\n",
|
| 1174 |
+
"p-value: 0.0000\n",
|
| 1175 |
+
"Series is stationary — good for ARIMA.\n",
|
| 1176 |
+
"\n",
|
| 1177 |
+
"ARIMA Model Summary:\n",
|
| 1178 |
+
" SARIMAX Results \n",
|
| 1179 |
+
"==============================================================================\n",
|
| 1180 |
+
"Dep. Variable: price No. Observations: 24\n",
|
| 1181 |
+
"Model: ARIMA(2, 1, 1) Log Likelihood -107.606\n",
|
| 1182 |
+
"Date: Mon, 27 Apr 2026 AIC 223.212\n",
|
| 1183 |
+
"Time: 18:02:47 BIC 227.754\n",
|
| 1184 |
+
"Sample: 0 HQIC 224.354\n",
|
| 1185 |
+
" - 24 \n",
|
| 1186 |
+
"Covariance Type: opg \n",
|
| 1187 |
+
"==============================================================================\n",
|
| 1188 |
+
" coef std err z P>|z| [0.025 0.975]\n",
|
| 1189 |
+
"------------------------------------------------------------------------------\n",
|
| 1190 |
+
"ar.L1 -0.2139 0.785 -0.273 0.785 -1.752 1.324\n",
|
| 1191 |
+
"ar.L2 0.4311 0.684 0.630 0.529 -0.910 1.772\n",
|
| 1192 |
+
"ma.L1 -0.8209 0.849 -0.966 0.334 -2.486 0.844\n",
|
| 1193 |
+
"sigma2 636.5748 198.429 3.208 0.001 247.661 1025.488\n",
|
| 1194 |
+
"===================================================================================\n",
|
| 1195 |
+
"Ljung-Box (L1) (Q): 0.10 Jarque-Bera (JB): 19.72\n",
|
| 1196 |
+
"Prob(Q): 0.75 Prob(JB): 0.00\n",
|
| 1197 |
+
"Heteroskedasticity (H): 0.06 Skew: 1.13\n",
|
| 1198 |
+
"Prob(H) (two-sided): 0.00 Kurtosis: 6.94\n",
|
| 1199 |
+
"===================================================================================\n",
|
| 1200 |
+
"\n",
|
| 1201 |
+
"Warnings:\n",
|
| 1202 |
+
"[1] Covariance matrix calculated using the outer product of gradients (complex-step).\n",
|
| 1203 |
+
"\n",
|
| 1204 |
+
"Forecast for next 6 months:\n"
|
| 1205 |
+
]
|
| 1206 |
+
},
|
| 1207 |
+
{
|
| 1208 |
+
"output_type": "display_data",
|
| 1209 |
+
"data": {
|
| 1210 |
+
"text/plain": [
|
| 1211 |
+
" month forecasted_price\n",
|
| 1212 |
+
"0 2018-10-31 118.22\n",
|
| 1213 |
+
"1 2018-11-30 135.63\n",
|
| 1214 |
+
"2 2018-12-31 120.36\n",
|
| 1215 |
+
"3 2019-01-31 131.13\n",
|
| 1216 |
+
"4 2019-02-28 122.25\n",
|
| 1217 |
+
"5 2019-03-31 128.79"
|
| 1218 |
+
],
|
| 1219 |
+
"text/html": [
|
| 1220 |
+
"\n",
|
| 1221 |
+
" <div id=\"df-a42cb869-67b3-409e-aeab-5052ae9df540\" class=\"colab-df-container\">\n",
|
| 1222 |
+
" <div>\n",
|
| 1223 |
+
"<style scoped>\n",
|
| 1224 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
| 1225 |
+
" vertical-align: middle;\n",
|
| 1226 |
+
" }\n",
|
| 1227 |
+
"\n",
|
| 1228 |
+
" .dataframe tbody tr th {\n",
|
| 1229 |
+
" vertical-align: top;\n",
|
| 1230 |
+
" }\n",
|
| 1231 |
+
"\n",
|
| 1232 |
+
" .dataframe thead th {\n",
|
| 1233 |
+
" text-align: right;\n",
|
| 1234 |
+
" }\n",
|
| 1235 |
+
"</style>\n",
|
| 1236 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
| 1237 |
+
" <thead>\n",
|
| 1238 |
+
" <tr style=\"text-align: right;\">\n",
|
| 1239 |
+
" <th></th>\n",
|
| 1240 |
+
" <th>month</th>\n",
|
| 1241 |
+
" <th>forecasted_price</th>\n",
|
| 1242 |
+
" </tr>\n",
|
| 1243 |
+
" </thead>\n",
|
| 1244 |
+
" <tbody>\n",
|
| 1245 |
+
" <tr>\n",
|
| 1246 |
+
" <th>0</th>\n",
|
| 1247 |
+
" <td>2018-10-31</td>\n",
|
| 1248 |
+
" <td>118.22</td>\n",
|
| 1249 |
+
" </tr>\n",
|
| 1250 |
+
" <tr>\n",
|
| 1251 |
+
" <th>1</th>\n",
|
| 1252 |
+
" <td>2018-11-30</td>\n",
|
| 1253 |
+
" <td>135.63</td>\n",
|
| 1254 |
+
" </tr>\n",
|
| 1255 |
+
" <tr>\n",
|
| 1256 |
+
" <th>2</th>\n",
|
| 1257 |
+
" <td>2018-12-31</td>\n",
|
| 1258 |
+
" <td>120.36</td>\n",
|
| 1259 |
+
" </tr>\n",
|
| 1260 |
+
" <tr>\n",
|
| 1261 |
+
" <th>3</th>\n",
|
| 1262 |
+
" <td>2019-01-31</td>\n",
|
| 1263 |
+
" <td>131.13</td>\n",
|
| 1264 |
+
" </tr>\n",
|
| 1265 |
+
" <tr>\n",
|
| 1266 |
+
" <th>4</th>\n",
|
| 1267 |
+
" <td>2019-02-28</td>\n",
|
| 1268 |
+
" <td>122.25</td>\n",
|
| 1269 |
+
" </tr>\n",
|
| 1270 |
+
" <tr>\n",
|
| 1271 |
+
" <th>5</th>\n",
|
| 1272 |
+
" <td>2019-03-31</td>\n",
|
| 1273 |
+
" <td>128.79</td>\n",
|
| 1274 |
+
" </tr>\n",
|
| 1275 |
+
" </tbody>\n",
|
| 1276 |
+
"</table>\n",
|
| 1277 |
+
"</div>\n",
|
| 1278 |
+
" <div class=\"colab-df-buttons\">\n",
|
| 1279 |
+
"\n",
|
| 1280 |
+
" <div class=\"colab-df-container\">\n",
|
| 1281 |
+
" <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-a42cb869-67b3-409e-aeab-5052ae9df540')\"\n",
|
| 1282 |
+
" title=\"Convert this dataframe to an interactive table.\"\n",
|
| 1283 |
+
" style=\"display:none;\">\n",
|
| 1284 |
+
"\n",
|
| 1285 |
+
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
|
| 1286 |
+
" <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
|
| 1287 |
+
" </svg>\n",
|
| 1288 |
+
" </button>\n",
|
| 1289 |
+
"\n",
|
| 1290 |
+
" <style>\n",
|
| 1291 |
+
" .colab-df-container {\n",
|
| 1292 |
+
" display:flex;\n",
|
| 1293 |
+
" gap: 12px;\n",
|
| 1294 |
+
" }\n",
|
| 1295 |
+
"\n",
|
| 1296 |
+
" .colab-df-convert {\n",
|
| 1297 |
+
" background-color: #E8F0FE;\n",
|
| 1298 |
+
" border: none;\n",
|
| 1299 |
+
" border-radius: 50%;\n",
|
| 1300 |
+
" cursor: pointer;\n",
|
| 1301 |
+
" display: none;\n",
|
| 1302 |
+
" fill: #1967D2;\n",
|
| 1303 |
+
" height: 32px;\n",
|
| 1304 |
+
" padding: 0 0 0 0;\n",
|
| 1305 |
+
" width: 32px;\n",
|
| 1306 |
+
" }\n",
|
| 1307 |
+
"\n",
|
| 1308 |
+
" .colab-df-convert:hover {\n",
|
| 1309 |
+
" background-color: #E2EBFA;\n",
|
| 1310 |
+
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
|
| 1311 |
+
" fill: #174EA6;\n",
|
| 1312 |
+
" }\n",
|
| 1313 |
+
"\n",
|
| 1314 |
+
" .colab-df-buttons div {\n",
|
| 1315 |
+
" margin-bottom: 4px;\n",
|
| 1316 |
+
" }\n",
|
| 1317 |
+
"\n",
|
| 1318 |
+
" [theme=dark] .colab-df-convert {\n",
|
| 1319 |
+
" background-color: #3B4455;\n",
|
| 1320 |
+
" fill: #D2E3FC;\n",
|
| 1321 |
+
" }\n",
|
| 1322 |
+
"\n",
|
| 1323 |
+
" [theme=dark] .colab-df-convert:hover {\n",
|
| 1324 |
+
" background-color: #434B5C;\n",
|
| 1325 |
+
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
|
| 1326 |
+
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
|
| 1327 |
+
" fill: #FFFFFF;\n",
|
| 1328 |
+
" }\n",
|
| 1329 |
+
" </style>\n",
|
| 1330 |
+
"\n",
|
| 1331 |
+
" <script>\n",
|
| 1332 |
+
" const buttonEl =\n",
|
| 1333 |
+
" document.querySelector('#df-a42cb869-67b3-409e-aeab-5052ae9df540 button.colab-df-convert');\n",
|
| 1334 |
+
" buttonEl.style.display =\n",
|
| 1335 |
+
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
|
| 1336 |
+
"\n",
|
| 1337 |
+
" async function convertToInteractive(key) {\n",
|
| 1338 |
+
" const element = document.querySelector('#df-a42cb869-67b3-409e-aeab-5052ae9df540');\n",
|
| 1339 |
+
" const dataTable =\n",
|
| 1340 |
+
" await google.colab.kernel.invokeFunction('convertToInteractive',\n",
|
| 1341 |
+
" [key], {});\n",
|
| 1342 |
+
" if (!dataTable) return;\n",
|
| 1343 |
+
"\n",
|
| 1344 |
+
" const docLinkHtml = 'Like what you see? Visit the ' +\n",
|
| 1345 |
+
" '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
|
| 1346 |
+
" + ' to learn more about interactive tables.';\n",
|
| 1347 |
+
" element.innerHTML = '';\n",
|
| 1348 |
+
" dataTable['output_type'] = 'display_data';\n",
|
| 1349 |
+
" await google.colab.output.renderOutput(dataTable, element);\n",
|
| 1350 |
+
" const docLink = document.createElement('div');\n",
|
| 1351 |
+
" docLink.innerHTML = docLinkHtml;\n",
|
| 1352 |
+
" element.appendChild(docLink);\n",
|
| 1353 |
+
" }\n",
|
| 1354 |
+
" </script>\n",
|
| 1355 |
+
" </div>\n",
|
| 1356 |
+
"\n",
|
| 1357 |
+
"\n",
|
| 1358 |
+
" <div id=\"id_212a5a0a-67cd-4f84-b790-76c21fb20928\">\n",
|
| 1359 |
+
" <style>\n",
|
| 1360 |
+
" .colab-df-generate {\n",
|
| 1361 |
+
" background-color: #E8F0FE;\n",
|
| 1362 |
+
" border: none;\n",
|
| 1363 |
+
" border-radius: 50%;\n",
|
| 1364 |
+
" cursor: pointer;\n",
|
| 1365 |
+
" display: none;\n",
|
| 1366 |
+
" fill: #1967D2;\n",
|
| 1367 |
+
" height: 32px;\n",
|
| 1368 |
+
" padding: 0 0 0 0;\n",
|
| 1369 |
+
" width: 32px;\n",
|
| 1370 |
+
" }\n",
|
| 1371 |
+
"\n",
|
| 1372 |
+
" .colab-df-generate:hover {\n",
|
| 1373 |
+
" background-color: #E2EBFA;\n",
|
| 1374 |
+
" box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
|
| 1375 |
+
" fill: #174EA6;\n",
|
| 1376 |
+
" }\n",
|
| 1377 |
+
"\n",
|
| 1378 |
+
" [theme=dark] .colab-df-generate {\n",
|
| 1379 |
+
" background-color: #3B4455;\n",
|
| 1380 |
+
" fill: #D2E3FC;\n",
|
| 1381 |
+
" }\n",
|
| 1382 |
+
"\n",
|
| 1383 |
+
" [theme=dark] .colab-df-generate:hover {\n",
|
| 1384 |
+
" background-color: #434B5C;\n",
|
| 1385 |
+
" box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
|
| 1386 |
+
" filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
|
| 1387 |
+
" fill: #FFFFFF;\n",
|
| 1388 |
+
" }\n",
|
| 1389 |
+
" </style>\n",
|
| 1390 |
+
" <button class=\"colab-df-generate\" onclick=\"generateWithVariable('forecast_df')\"\n",
|
| 1391 |
+
" title=\"Generate code using this dataframe.\"\n",
|
| 1392 |
+
" style=\"display:none;\">\n",
|
| 1393 |
+
"\n",
|
| 1394 |
+
" <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\"viewBox=\"0 0 24 24\"\n",
|
| 1395 |
+
" width=\"24px\">\n",
|
| 1396 |
+
" <path d=\"M7,19H8.4L18.45,9,17,7.55,7,17.6ZM5,21V16.75L18.45,3.32a2,2,0,0,1,2.83,0l1.4,1.43a1.91,1.91,0,0,1,.58,1.4,1.91,1.91,0,0,1-.58,1.4L9.25,21ZM18.45,9,17,7.55Zm-12,3A5.31,5.31,0,0,0,4.9,8.1,5.31,5.31,0,0,0,1,6.5,5.31,5.31,0,0,0,4.9,4.9,5.31,5.31,0,0,0,6.5,1,5.31,5.31,0,0,0,8.1,4.9,5.31,5.31,0,0,0,12,6.5,5.46,5.46,0,0,0,6.5,12Z\"/>\n",
|
| 1397 |
+
" </svg>\n",
|
| 1398 |
+
" </button>\n",
|
| 1399 |
+
" <script>\n",
|
| 1400 |
+
" (() => {\n",
|
| 1401 |
+
" const buttonEl =\n",
|
| 1402 |
+
" document.querySelector('#id_212a5a0a-67cd-4f84-b790-76c21fb20928 button.colab-df-generate');\n",
|
| 1403 |
+
" buttonEl.style.display =\n",
|
| 1404 |
+
" google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
|
| 1405 |
+
"\n",
|
| 1406 |
+
" buttonEl.onclick = () => {\n",
|
| 1407 |
+
" google.colab.notebook.generateWithVariable('forecast_df');\n",
|
| 1408 |
+
" }\n",
|
| 1409 |
+
" })();\n",
|
| 1410 |
+
" </script>\n",
|
| 1411 |
+
" </div>\n",
|
| 1412 |
+
"\n",
|
| 1413 |
+
" </div>\n",
|
| 1414 |
+
" </div>\n"
|
| 1415 |
+
],
|
| 1416 |
+
"application/vnd.google.colaboratory.intrinsic+json": {
|
| 1417 |
+
"type": "dataframe",
|
| 1418 |
+
"variable_name": "forecast_df",
|
| 1419 |
+
"summary": "{\n \"name\": \"forecast_df\",\n \"rows\": 6,\n \"fields\": [\n {\n \"column\": \"month\",\n \"properties\": {\n \"dtype\": \"date\",\n \"min\": \"2018-10-31 00:00:00\",\n \"max\": \"2019-03-31 00:00:00\",\n \"num_unique_values\": 6,\n \"samples\": [\n \"2018-10-31 00:00:00\",\n \"2018-11-30 00:00:00\",\n \"2019-03-31 00:00:00\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"forecasted_price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 6.829558306850204,\n \"min\": 118.22,\n \"max\": 135.63,\n \"num_unique_values\": 6,\n \"samples\": [\n 118.22,\n 135.63,\n 128.79\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
|
| 1420 |
+
}
|
| 1421 |
+
},
|
| 1422 |
+
"metadata": {}
|
| 1423 |
+
},
|
| 1424 |
+
{
|
| 1425 |
+
"output_type": "stream",
|
| 1426 |
+
"name": "stdout",
|
| 1427 |
+
"text": [
|
| 1428 |
+
"Saved forecast to arima_price_forecast.csv\n"
|
| 1429 |
+
]
|
| 1430 |
+
}
|
| 1431 |
+
]
|
| 1432 |
+
}
|
| 1433 |
+
],
|
| 1434 |
+
"metadata": {
|
| 1435 |
+
"kernelspec": {
|
| 1436 |
+
"display_name": "Python 3",
|
| 1437 |
+
"language": "python",
|
| 1438 |
+
"name": "python3"
|
| 1439 |
+
},
|
| 1440 |
+
"language_info": {
|
| 1441 |
+
"name": "python",
|
| 1442 |
+
"version": "3.10"
|
| 1443 |
+
},
|
| 1444 |
+
"colab": {
|
| 1445 |
+
"provenance": []
|
| 1446 |
+
}
|
| 1447 |
+
},
|
| 1448 |
+
"nbformat": 4,
|
| 1449 |
+
"nbformat_minor": 5
|
| 1450 |
+
}
|