{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":7391,"databundleVersionId":44328,"sourceType":"competition"}],"dockerImageVersionId":30822,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T14:57:26.839073Z","iopub.execute_input":"2025-01-15T14:57:26.839493Z","iopub.status.idle":"2025-01-15T14:57:26.844173Z","shell.execute_reply.started":"2025-01-15T14:57:26.839463Z","shell.execute_reply":"2025-01-15T14:57:26.843Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\n\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\npaths = []\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        paths.append(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-01-15T14:57:26.845903Z","iopub.execute_input":"2025-01-15T14:57:26.846232Z","iopub.status.idle":"2025-01-15T14:57:26.870337Z","shell.execute_reply.started":"2025-01-15T14:57:26.846202Z","shell.execute_reply":"2025-01-15T14:57:26.869311Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install py7zr","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T14:57:26.872168Z","iopub.execute_input":"2025-01-15T14:57:26.872461Z","iopub.status.idle":"2025-01-15T14:57:35.245962Z","shell.execute_reply.started":"2025-01-15T14:57:26.872426Z","shell.execute_reply":"2025-01-15T14:57:35.244571Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import py7zr\nfor filenames in paths:\n    with py7zr.SevenZipFile(filenames, mode='r') as z_ref:\n        z_ref.extractall(path='/kaggle/working')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T14:57:35.247794Z","iopub.execute_input":"2025-01-15T14:57:35.248156Z","iopub.status.idle":"2025-01-15T14:59:06.054299Z","shell.execute_reply.started":"2025-01-15T14:57:35.248125Z","shell.execute_reply":"2025-01-15T14:59:06.051836Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Corporación Favorita Grocery Sales Forecasting\n\nPlease read data description: https://www.kaggle.com/c/favorita-grocery-sales-forecasting","metadata":{}},{"cell_type":"markdown","source":"## Splitting Data into Training and Test Sets\nThe data you are working with splited into **training** and **test** sets and stored in the following files:\n\n- **`/kaggle/working/train_data.csv`** – the training dataset used for model training.\n- **`/kaggle/working/test_data.csv`** – the test dataset used to evaluate the model's performance.","metadata":{}},{"cell_type":"code","source":"%%time\ndata = pd.read_csv(\"/kaggle/working/train.csv\")\ndata[\"date\"] =  pd.to_datetime(data[\"date\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T14:59:06.056823Z","iopub.execute_input":"2025-01-15T14:59:06.057361Z","iopub.status.idle":"2025-01-15T15:01:00.278875Z","shell.execute_reply.started":"2025-01-15T14:59:06.057315Z","shell.execute_reply":"2025-01-15T15:01:00.277469Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"monthly_counts_data = data['date'].dt.to_period('M').value_counts().sort_index()\n\nplt.figure(figsize=(12, 6))\nmonthly_counts_data.plot(kind='bar', color='skyblue')\nplt.title('Count of Data for Each Month for All data', fontsize=14)\nplt.xlabel('Month', fontsize=12)\nplt.ylabel('Count', fontsize=12)\nplt.xticks(rotation=45)\nplt.grid(axis='y', linestyle='--', alpha=0.7)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:01:00.28035Z","iopub.execute_input":"2025-01-15T15:01:00.280766Z","iopub.status.idle":"2025-01-15T15:01:07.828015Z","shell.execute_reply.started":"2025-01-15T15:01:00.280723Z","shell.execute_reply":"2025-01-15T15:01:07.826499Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%time\nTHRESHOLD_TRAIN_DATE = pd.to_datetime(\"2017-07-01\")\nTHRESHOLD_TEST_DATE = pd.to_datetime(\"2017-08-01\")\n\ndata[data[\"date\"] < THRESHOLD_TRAIN_DATE].to_csv(\"/kaggle/working/train_data.csv\")\ndata[(data[\"date\"] >= THRESHOLD_TRAIN_DATE)&(data[\"date\"] < THRESHOLD_TEST_DATE)].to_csv(\"/kaggle/working/test_data.csv\")\n\n%xdel data","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:01:07.829189Z","iopub.execute_input":"2025-01-15T15:01:07.829502Z","iopub.status.idle":"2025-01-15T15:08:21.144517Z","shell.execute_reply.started":"2025-01-15T15:01:07.829473Z","shell.execute_reply":"2025-01-15T15:08:21.142555Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"%%time\ndf = pd.read_csv(\"/kaggle/working/train_data.csv\")\ntest_df = pd.read_csv(\"/kaggle/working/test_data.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:08:21.146657Z","iopub.execute_input":"2025-01-15T15:08:21.14709Z","iopub.status.idle":"2025-01-15T15:10:11.758465Z","shell.execute_reply.started":"2025-01-15T15:08:21.147053Z","shell.execute_reply":"2025-01-15T15:10:11.757191Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df[\"date\"] = pd.to_datetime(df[\"date\"])\ntest_df[\"date\"] = pd.to_datetime(test_df[\"date\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:11.769069Z","iopub.execute_input":"2025-01-15T15:10:11.769537Z","iopub.status.idle":"2025-01-15T15:10:23.637934Z","shell.execute_reply.started":"2025-01-15T15:10:11.769495Z","shell.execute_reply":"2025-01-15T15:10:23.636873Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"monthly_counts = df['date'].dt.to_period('M').value_counts().sort_index().reset_index()\nmonthly_counts_test = test_df['date'].dt.to_period('M').value_counts().sort_index().reset_index()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:23.639438Z","iopub.execute_input":"2025-01-15T15:10:23.639789Z","iopub.status.idle":"2025-01-15T15:10:29.945456Z","shell.execute_reply.started":"2025-01-15T15:10:23.639756Z","shell.execute_reply":"2025-01-15T15:10:29.944338Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"monthly_counts['type'] = 'Train'\nmonthly_counts_test['type'] = 'Test'\ncombined = pd.concat([monthly_counts, monthly_counts_test])\n\nplt.figure(figsize=(12, 6))\nsns.barplot(data=combined, x='date', y='count', hue='type', palette=['blue', 'red'])\nplt.title('Count of Data for Each Month (Train vs Test)', fontsize=14)\nplt.xlabel('Month', fontsize=12)\nplt.ylabel('Count', fontsize=12)\nplt.xticks(rotation=45)\nplt.legend(title='Dataset')\nplt.grid(axis='y', linestyle='--', alpha=0.7)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:29.946634Z","iopub.execute_input":"2025-01-15T15:10:29.947039Z","iopub.status.idle":"2025-01-15T15:10:31.3353Z","shell.execute_reply.started":"2025-01-15T15:10:29.947Z","shell.execute_reply":"2025-01-15T15:10:31.334113Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:31.336529Z","iopub.execute_input":"2025-01-15T15:10:31.336978Z","iopub.status.idle":"2025-01-15T15:10:31.357794Z","shell.execute_reply.started":"2025-01-15T15:10:31.336934Z","shell.execute_reply":"2025-01-15T15:10:31.356622Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Additional Data\n\n\nTo make more effective use of the data, you also have access to several auxiliary datasets containing contextual information:\n\n#### 1. **`holidays_events.csv`**\n   - **Description**:\n     Contains information about holidays and events that may influence sales.\n   - **Useful Columns**:\n     - `date`: The date of the holiday or event.\n     - `type`: The type of event (national, regional, local).\n     - `locale`: The level of impact (national, regional, local).\n     - `description`: A description of the event.\n   - **How to Use**:\n     - Add a flag indicating whether a date is a holiday to the training and test sets.\n     - Categorize holidays by their `type` and consider their impact on sales.\n     - Use the `locale` column to analyze regional effects.","metadata":{"execution":{"iopub.status.busy":"2024-12-22T19:12:02.31896Z","iopub.execute_input":"2024-12-22T19:12:02.319553Z","iopub.status.idle":"2024-12-22T19:12:02.32548Z","shell.execute_reply.started":"2024-12-22T19:12:02.319516Z","shell.execute_reply":"2024-12-22T19:12:02.323891Z"}}},{"cell_type":"code","source":"holiday_events = pd.read_csv(\"/kaggle/working/holidays_events.csv\")\nprint(holiday_events.shape)\nholiday_events.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:31.359091Z","iopub.execute_input":"2025-01-15T15:10:31.359485Z","iopub.status.idle":"2025-01-15T15:10:31.377642Z","shell.execute_reply.started":"2025-01-15T15:10:31.359452Z","shell.execute_reply":"2025-01-15T15:10:31.376502Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### 2. **`items.csv`**\n   - **Description**:\n     Contains information about the items being sold.\n   - **Useful Columns**:\n     - `item_nbr`: Unique identifier for each item.\n     - `family`: The category or family the item belongs to (e.g., \"Beverages\").\n     - `class`: A finer categorization of items.\n     - `perishable`: A binary indicator for whether the item is perishable (1 for perishable, 0 otherwise).\n   - **How to Use**:\n     - Use `family` and `class` to group items and analyze trends across categories.\n     - Include the `perishable` indicator to weight predictions for perishable items.","metadata":{}},{"cell_type":"code","source":"items = pd.read_csv(\"/kaggle/working/items.csv\")\nprint(items.shape)\nitems.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:31.378798Z","iopub.execute_input":"2025-01-15T15:10:31.379236Z","iopub.status.idle":"2025-01-15T15:10:31.401089Z","shell.execute_reply.started":"2025-01-15T15:10:31.379195Z","shell.execute_reply":"2025-01-15T15:10:31.399965Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### 3. **`oil.csv`**\n   - **Description**:\n     Contains daily oil price data, which can serve as an external economic indicator.\n   - **Useful Columns**:\n     - `date`: The date corresponding to the oil price.\n     - `dcoilwtico`: The daily oil price.\n   - **How to Use**:\n     - Join this dataset with the training and test sets on the `date` column to include oil price as a feature.\n     - Analyze the correlation between oil price fluctuations and sales trends.","metadata":{}},{"cell_type":"code","source":"oil = pd.read_csv(\"/kaggle/working/oil.csv\")\nprint(oil.shape)\noil.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:31.402359Z","iopub.execute_input":"2025-01-15T15:10:31.40276Z","iopub.status.idle":"2025-01-15T15:10:31.421102Z","shell.execute_reply.started":"2025-01-15T15:10:31.402719Z","shell.execute_reply":"2025-01-15T15:10:31.419978Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### 4. **`stores.csv`**\n   - **Description**:\n     Contains information about the stores where items are sold.\n   - **Useful Columns**:\n     - `store_nbr`: Unique identifier for each store.\n     - `city`: The city where the store is located.\n     - `state`: The state where the store is located.\n     - `type`: The store type.\n     - `cluster`: A grouping of similar stores based on sales patterns.\n   - **How to Use**:\n     - Use `city` and `state` for regional analysis of sales trends.\n     - Incorporate `type` and `cluster` to identify patterns and group stores with similar behavior.\n","metadata":{}},{"cell_type":"code","source":"stores = pd.read_csv(\"/kaggle/working/stores.csv\")\nprint(stores.shape)\nstores.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:31.422348Z","iopub.execute_input":"2025-01-15T15:10:31.422651Z","iopub.status.idle":"2025-01-15T15:10:31.43728Z","shell.execute_reply.started":"2025-01-15T15:10:31.422617Z","shell.execute_reply":"2025-01-15T15:10:31.436059Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**[READ DATA DESCRIPTION CAREFULY](https://www.kaggle.com/competitions/favorita-grocery-sales-forecasting) !!!!** \n\n## Exploratory Data Analysis and Model Training\n\n### 1. Baseline Model\n- Consider which model would be suitable as `DummyModel` for this task, then create, train, and use its predictions as a baseline.\n\n### 2. Feature Engineering\n- Generate new features by incorporating data from additional datasets to enhance the model's predictive capabilities.\n\n### 3. Model Training and Optimization\n- Utilize advanced regression models, such as **LGBM Regression** or **CatBoost Regression**, to achieve the best results. Focus on hyperparameter tuning and evaluation metrics to optimize performance. **Use foremention Normalized Weighted Root Mean Squared Logarithmic Error**.  \n\n### Thats All :-)\n","metadata":{}},{"cell_type":"code","source":"# Basic Data Cleaning for the 'df' dataset\n\n# 1. Handle missing values\n# For 'onpromotion', fill NaN with 0 (assuming missing values mean no promotion)\ndf['onpromotion'].fillna(0, inplace=True)\n\n# 2. Remove duplicates\ndf.drop_duplicates(inplace=True)\n\n# 3. Convert 'date' to datetime type\ndf['date'] = pd.to_datetime(df['date'])\n\n# 4. Handle negative values in 'unit_sales'\n# Replace negative values (returns) with 0 or take their absolute value, based on business rules\n# Option 1: Replace negatives with 0\ndf['unit_sales'] = df['unit_sales'].apply(lambda x: max(x, 0))\n\n# 5. Check for outliers (optional)\n# Apply clipping to remove extreme values\nunit_sales_threshold = np.percentile(df['unit_sales'], 99)\ndf['unit_sales'] = np.clip(df['unit_sales'], 0, unit_sales_threshold)\n\n# 6. Add a simple flag for 'is_holiday' to prepare for later feature engineering\n# Note: Requires merging with 'holidays_events.csv' dataset during feature engineering\n# Here, we create a placeholder for now (e.g., all dates are non-holidays)\ndf['is_holiday'] = 0  # Placeholder flag, to be updated in feature engineering\n\n# Verify the cleaned dataset\nprint(df.info())  # Check non-null counts and data types\nprint(df.describe())  # Summary statistics for numerical columns\nprint(df.head())  # Inspect the first few rows\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:27:39.295031Z","iopub.execute_input":"2025-01-15T15:27:39.295509Z","execution_failed":"2025-01-15T15:27:55.955Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.dummy import DummyRegressor\nfrom sklearn.model_selection import train_test_split\n\nX = df.drop(columns=['unit_sales', 'date'])\ny = df['unit_sales']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\ndummy_model = DummyRegressor(strategy=\"mean\")\ndummy_model.fit(X_train, y_train)\n\ny_pred_dummy = dummy_model.predict(X_test)\n\ndef nwrmsle(y_true, y_pred):\n    return np.sqrt(np.sum((np.log1p(y_true) - np.log1p(y_pred)) ** 2) / len(y_true))\n\nnwrmsle_score = nwrmsle(y_test, y_pred_dummy)\nprint(f\"Baseline Model NWRMSLE: {nwrmsle_score}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-01-15T15:10:31.438327Z","iopub.execute_input":"2025-01-15T15:10:31.438631Z","iopub.status.idle":"2025-01-15T15:11:31.822103Z","shell.execute_reply.started":"2025-01-15T15:10:31.438596Z","shell.execute_reply":"2025-01-15T15:11:31.820773Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Convert date column to datetime for easier manipulation\ndf['date'] = pd.to_datetime(df['date'])\n\n# Extract date-related features\ndf['day_of_week'] = df['date'].dt.dayofweek\ndf['month'] = df['date'].dt.month\ndf['quarter'] = df['date'].dt.quarter\ndf['year'] = df['date'].dt.year\n\n# Merge holiday events to add holiday-related features\nholiday_events['date'] = pd.to_datetime(holiday_events['date'])\ndf = df.merge(holiday_events[['date', 'type']], on='date', how='left')\n\n# Create a binary column for whether the day is a holiday\ndf['is_holiday'] = df['type'].notnull().astype(int)\n\n# Merge oil price data (dcoilwtico)\noil['date'] = pd.to_datetime(oil['date'])\ndf = df.merge(oil[['date', 'dcoilwtico']], on='date', how='left')\n\n# Merge store data to add store-related features\ndf = df.merge(stores[['store_nbr', 'city', 'state', 'type', 'cluster']], on='store_nbr', how='left')\n\n# Merge item data to add item-related features\ndf = df.merge(items[['item_nbr', 'family', 'class', 'perishable']], on='item_nbr', how='left')\n\n# Drop rows with missing target variable (if any)\ndf.dropna(subset=['unit_sales'], inplace=True)\n\n# Let's check the resulting data\nprint(df.head())\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}