{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":5260,"databundleVersionId":37827,"sourceType":"competition"}],"dockerImageVersionId":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(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","execution":{"iopub.status.busy":"2024-06-24T12:58:20.136921Z","iopub.execute_input":"2024-06-24T12:58:20.137324Z","iopub.status.idle":"2024-06-24T12:58:20.577735Z","shell.execute_reply.started":"2024-06-24T12:58:20.137293Z","shell.execute_reply":"2024-06-24T12:58:20.576644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style=\"border-radius:10px; padding: 12px; background-color: #ffffff; font-size:130%; text-align:left\">\n\n<h2 align=\"left\"><font color=#E1B12D>Introduction</font></h2>\n\nGrupo Bimbo, a leading multinational bakery company, faces a unique challenge in managing the inventory of its products. With a typical shelf life of just one week, the accuracy of daily inventory calculations is paramount. Currently, these calculations are performed by direct delivery sales employees who rely on their personal experiences to predict the forces of supply, demand, and consumer behavior at each store. The margin for error in this process is minimal. Underestimating demand results in empty shelves and lost sales, while overestimating demand leads to excess product returns and increased expenses.\n\nGrupo Bimbo aims to create a predictive model that can accurately forecast inventory needs based on historical data, thereby optimizing the supply chain and improving efficiency.","metadata":{}},{"cell_type":"markdown","source":"<h2 align=\"left\"><font color=#E1B12D>Approach</font></h2>\n\n<a id=\"toc\"></a>\n- [1.1 Import Libraries](#1.1)\n- [1.2 Import Data](#1.2)\n- [1.3 Quick overview](#1.3)\n- [1.4 Summary of the data](#1.4)\n- [2. Exploratory Data Analysis ](#2)","metadata":{}},{"cell_type":"markdown","source":"<a id=\"1.1\"></a>\n## <b>1.1 <span style='color:#E1B12D'>Import Libraries</span></b> ","metadata":{}},{"cell_type":"code","source":"#!pip install scikit-learn xgboost lightgbm catboost","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-06-24T12:58:20.579725Z","iopub.execute_input":"2024-06-24T12:58:20.580293Z","iopub.status.idle":"2024-06-24T12:58:20.585094Z","shell.execute_reply.started":"2024-06-24T12:58:20.580262Z","shell.execute_reply":"2024-06-24T12:58:20.583981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%capture\nimport pandas as pd\nimport numpy as np\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport warnings \nwarnings.filterwarnings('ignore')\n\nfrom sklearn.metrics import roc_auc_score, accuracy_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier\nfrom xgboost import XGBClassifier\nfrom lightgbm import LGBMClassifier\nfrom catboost import CatBoostClassifier\nimport path\nimport os\nimport plotly.express as px\nimport gc","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2024-06-24T12:58:20.586666Z","iopub.execute_input":"2024-06-24T12:58:20.587048Z","iopub.status.idle":"2024-06-24T12:58:23.993627Z","shell.execute_reply.started":"2024-06-24T12:58:20.587007Z","shell.execute_reply":"2024-06-24T12:58:23.992422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1.2\"></a>\n## <b>1.2 <span style='color:#E1B12D'>Configuration</span></b> ","metadata":{}},{"cell_type":"code","source":"#Seaborn settings for visualizations!\nrc = {\n    \"axes.facecolor\": \"#f7f9fc\",\n    \"figure.facecolor\": \"#f7f9fc\",\n    \"axes.edgecolor\": \"#000000\",\n    \"grid.color\": \"#EBEBE7\",\n    \"font.family\": \"serif\",\n    \"axes.labelcolor\": \"#000000\",\n    \"xtick.color\": \"#000000\",\n    \"ytick.color\": \"#000000\",\n    \"grid.alpha\": 0.4\n}\n\ndefault_palette = 'YlOrRd'\n\nsns.set(rc=rc)\npd.set_option('display.max_columns',35)\npd.options.display.float_format = '{:,.2f}'.format","metadata":{"execution":{"iopub.status.busy":"2024-06-24T12:58:23.996341Z","iopub.execute_input":"2024-06-24T12:58:23.996920Z","iopub.status.idle":"2024-06-24T12:58:24.004426Z","shell.execute_reply.started":"2024-06-24T12:58:23.996890Z","shell.execute_reply":"2024-06-24T12:58:24.003262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"1.2\"></a>\n## <b>1.2 <span style='color:#E1B12D'>Important Functions </span></b> ","metadata":{}},{"cell_type":"code","source":"# Defining some important function which will be used for the analysis of data\ndef inspect_columns(df, df_name):\n    \"\"\"A helper function that does a better job than df.info() and df.describe()\"\"\"\n    \n    total_rows = len(df)\n    result = pd.DataFrame({\n        'total_rows': [total_rows] * df.shape[1],\n        'rows_with_missing_values': df.isnull().sum(),\n        'unique': df.nunique() == total_rows,\n        'cardinality': df.nunique(),\n        'with_null': df.isna().any(),\n        'null_pct': round((df.isnull().sum() / total_rows) * 100, 2),\n        '1st_row': df.iloc[0],\n        'random_row': df.iloc[np.random.randint(low=0, high=total_rows)],\n        'last_row': df.iloc[-1],\n        'dtype': df.dtypes,\n    })\n    \n    # Print the name of the dataframe\n    print(f\"\\n{'='*10} {df_name} {'='*10}\\n\")\n    \n    # Print the head of the dataframe\n    print(\"First few rows of the dataframe:\\n\")\n    display(df.head())\n    \n    # Print the resulting statistics\n    print(\"Detailed statistics:\\n\")\n    display(result)\n    ","metadata":{"execution":{"iopub.status.busy":"2024-06-24T12:58:24.005687Z","iopub.execute_input":"2024-06-24T12:58:24.006001Z","iopub.status.idle":"2024-06-24T12:58:24.020219Z","shell.execute_reply.started":"2024-06-24T12:58:24.005975Z","shell.execute_reply":"2024-06-24T12:58:24.019111Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"toc\"></a>\n\n<a href=\"#toc\" style=\"background-color: #E1B12D; color: #ffffff; padding: 7px 10px; text-decoration: none; border-radius: 50px;\">Back to top</a><a id=\"toc\"></a>\n\n<a id=\"1.2\"></a>\n## <b>1.2 <span style='color:#E1B12D'>Import Data</span></b> ","metadata":{}},{"cell_type":"code","source":"dir = dirname\n\n# Define file paths\ntrain_file = os.path.join(dir, 'train.csv.zip')\nclient_file = os.path.join(dir, 'cliente_tabla.csv.zip')\nproducts_file = os.path.join(dir, 'producto_tabla.csv.zip')\ntest_file = os.path.join(dir, 'test.csv.zip')\ntown_state_file = os.path.join(dir, 'town_state.csv.zip')\n\n# Load datasets\ntrain_df = pd.read_csv(train_file, compression='zip')\nclient_df = pd.read_csv(client_file, compression='zip')\nproducts_df = pd.read_csv(products_file, compression='zip')\ntest_df = pd.read_csv(test_file, compression='zip')\ntown_state_df = pd.read_csv(town_state_file, compression='zip')","metadata":{"execution":{"iopub.status.busy":"2024-06-24T12:58:24.021522Z","iopub.execute_input":"2024-06-24T12:58:24.021916Z","iopub.status.idle":"2024-06-24T13:00:17.850863Z","shell.execute_reply.started":"2024-06-24T12:58:24.021882Z","shell.execute_reply":"2024-06-24T13:00:17.848384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id=\"toc\"></a>\n\n<a href=\"#toc\" style=\"background-color: #E1B12D; color: #ffffff; padding: 7px 10px; text-decoration: none; border-radius: 50px;\">Back to top</a><a id=\"toc\"></a>\n\n<a id=\"1.3\"></a>\n## <b>1.3 <span style='color:#E1B12D'>Quick overview</span></b> ","metadata":{}},{"cell_type":"code","source":"inspect_columns(train_df,\"Training Dataframe\")\ninspect_columns(client_df,\"Client Dataframe\")\ninspect_columns(products_df,\"Products Dataframe\")\ninspect_columns(test_df,\"Test Dataframe\")\ninspect_columns(town_state_df,\"Town and State Dataframe\")","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:00:17.852964Z","iopub.execute_input":"2024-06-24T13:00:17.853348Z","iopub.status.idle":"2024-06-24T13:00:33.744873Z","shell.execute_reply.started":"2024-06-24T13:00:17.853314Z","shell.execute_reply":"2024-06-24T13:00:33.743778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div style=\"border-radius:10px; padding: 12px; background-color: #ffffff; font-size:130%; text-align:left\">\n\n<b>About Data:</b><br>","metadata":{}},{"cell_type":"markdown","source":"<a id=\"toc\"></a>\n\n<a href=\"#toc\" style=\"background-color: #E1B12D; color: #ffffff; padding: 7px 10px; text-decoration: none; border-radius: 50px;\">Back to top</a><a id=\"toc\"></a>\n\n<a id=\"2\"></a>\n## <b>2 <span style='color:#E1B12D'> Exploratory Data Analysis</span></b> \n### <b>2.1 <span style='color:#E1B12D'> Data Transformation </span></b> ","metadata":{}},{"cell_type":"code","source":"train_df = train_df.merge(client_df,on = \"Cliente_ID\",how=\"left\")\ngc.collect()\ntrain_df = train_df.merge(products_df,on = \"Producto_ID\",how=\"left\")\ngc.collect()\ntrain_df = train_df.merge(town_state_df,on = \"Agencia_ID\",how=\"left\")\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:00:33.746398Z","iopub.execute_input":"2024-06-24T13:00:33.746775Z","iopub.status.idle":"2024-06-24T13:01:17.371692Z","shell.execute_reply.started":"2024-06-24T13:00:33.746746Z","shell.execute_reply":"2024-06-24T13:01:17.370613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = train_df.rename({'Semana':'Week', 'Agencia_ID':'Sales_Depot_ID', 'Canal_ID':'Sales_Channel_ID', 'Ruta_SAK':'Route_ID', 'Cliente_ID':'Client_ID',\n       'Producto_ID':'Product_ID', 'Venta_uni_hoy':'Sales_unit_this_week ', 'Venta_hoy':'Sales_this_week', 'Dev_uni_proxima':'Returns_unit_next_week',\n       'Dev_proxima':'Returns_next_week', 'Demanda_uni_equil':'Adjusted_Demand', 'NombreCliente':'Client_name', 'NombreProducto':'Product_Name',\n       'Town':'Town', 'State':'State'},axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:01:17.373131Z","iopub.execute_input":"2024-06-24T13:01:17.373473Z","iopub.status.idle":"2024-06-24T13:01:34.650699Z","shell.execute_reply.started":"2024-06-24T13:01:17.373438Z","shell.execute_reply":"2024-06-24T13:01:34.649661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:01:34.653962Z","iopub.execute_input":"2024-06-24T13:01:34.654323Z","iopub.status.idle":"2024-06-24T13:01:34.671229Z","shell.execute_reply.started":"2024-06-24T13:01:34.654292Z","shell.execute_reply":"2024-06-24T13:01:34.670055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:01:34.672657Z","iopub.execute_input":"2024-06-24T13:01:34.673562Z","iopub.status.idle":"2024-06-24T13:01:34.794795Z","shell.execute_reply.started":"2024-06-24T13:01:34.673509Z","shell.execute_reply":"2024-06-24T13:01:34.793448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Weekly_Demand = train_df.groupby('Week')['Adjusted_Demand'].sum().reset_index()","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:01:34.796074Z","iopub.execute_input":"2024-06-24T13:01:34.796393Z","iopub.status.idle":"2024-06-24T13:01:36.144100Z","shell.execute_reply.started":"2024-06-24T13:01:34.796367Z","shell.execute_reply":"2024-06-24T13:01:36.143180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = px.bar(data_frame=Weekly_Demand, x='Week',y='Adjusted_Demand',\n             title='Weekly Demand for Grupo Bimbo Products ',\n                 labels={'Week': 'Week', 'Adjusted_Demand': ''},\n                    text='Adjusted_Demand')\nfig.update_traces(texttemplate='%{text:.2s}', textposition='outside')\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:01:36.145401Z","iopub.execute_input":"2024-06-24T13:01:36.145734Z","iopub.status.idle":"2024-06-24T13:01:38.090286Z","shell.execute_reply.started":"2024-06-24T13:01:36.145705Z","shell.execute_reply":"2024-06-24T13:01:38.089186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Retrun_percentage_by_product = train_df.groupby('Product_Name')[['Sales_this_week','Returns_next_week']].sum().reset_index()\nRetrun_percentage_by_product['%_return']=Retrun_percentage_by_product['Returns_next_week']/Retrun_percentage_by_product['Sales_this_week']*100\nRetrun_percentage_by_product['%_return']=Retrun_percentage_by_product['%_return'].round(2)\nRetrun_percentage_by_product = Retrun_percentage_by_product.sort_values(by='Returns_next_week',ascending=False).head(10)","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:12:30.559622Z","iopub.execute_input":"2024-06-24T13:12:30.560089Z","iopub.status.idle":"2024-06-24T13:12:40.121951Z","shell.execute_reply.started":"2024-06-24T13:12:30.560047Z","shell.execute_reply":"2024-06-24T13:12:40.120503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Retrun_percentage_by_product","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:12:40.124106Z","iopub.execute_input":"2024-06-24T13:12:40.124580Z","iopub.status.idle":"2024-06-24T13:12:40.138562Z","shell.execute_reply.started":"2024-06-24T13:12:40.124537Z","shell.execute_reply":"2024-06-24T13:12:40.137435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = px.bar(\n    data_frame=Retrun_percentage_by_product, \n    x='Product_Name',\n    y='%_return',\n    title='% Return by Product',\n    labels={'Sales_Depot_ID': 'Sales Depot ID', '%_return': 'Percentage Return'},\n    text='Returns_next_week'\n)\nfig.update_traces(texttemplate='%{text:.2s}', textposition='outside')\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:14:57.709198Z","iopub.execute_input":"2024-06-24T13:14:57.710148Z","iopub.status.idle":"2024-06-24T13:14:57.797536Z","shell.execute_reply.started":"2024-06-24T13:14:57.710109Z","shell.execute_reply":"2024-06-24T13:14:57.796247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Retrun_percentage_by_sales_channel = train_df.groupby('Sales_Channel_ID')[['Sales_this_week','Returns_next_week']].sum().reset_index()\nRetrun_percentage_by_sales_channel['%_return']=Retrun_percentage_by_sales_channel['Returns_next_week']/Retrun_percentage_by_sales_channel['Sales_this_week']*100\nRetrun_percentage_by_sales_channel['%_return']=Retrun_percentage_by_sales_channel['%_return'].round(2)\nRetrun_percentage_by_sales_channel = Retrun_percentage_by_sales_channel.sort_values(by='Returns_next_week',ascending=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:30:50.241235Z","iopub.execute_input":"2024-06-24T13:30:50.241789Z","iopub.status.idle":"2024-06-24T13:30:52.049514Z","shell.execute_reply.started":"2024-06-24T13:30:50.241752Z","shell.execute_reply":"2024-06-24T13:30:52.048311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Retrun_percentage_by_sales_channel","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:31:36.474878Z","iopub.execute_input":"2024-06-24T13:31:36.475382Z","iopub.status.idle":"2024-06-24T13:31:36.496562Z","shell.execute_reply.started":"2024-06-24T13:31:36.475339Z","shell.execute_reply":"2024-06-24T13:31:36.495378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = px.bar(\n    data_frame=Retrun_percentage_by_sales_channel, \n    x='Sales_Channel_ID',\n    y='%_return',\n    title='% Return by Product',\n    labels={'Sales_Channel_ID': 'Sales_Channel_ID', '%_return': 'Percentage Return'},\n    text='Returns_next_week'\n)\nfig.update_traces(texttemplate='%{text:.2s}', textposition='outside')\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:31:17.993783Z","iopub.execute_input":"2024-06-24T13:31:17.994206Z","iopub.status.idle":"2024-06-24T13:31:18.072596Z","shell.execute_reply.started":"2024-06-24T13:31:17.994176Z","shell.execute_reply":"2024-06-24T13:31:18.071365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sampled = train_df.sample(frac=0.05, random_state=1)","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:52:20.621859Z","iopub.execute_input":"2024-06-24T13:52:20.622298Z","iopub.status.idle":"2024-06-24T13:52:33.531007Z","shell.execute_reply.started":"2024-06-24T13:52:20.622259Z","shell.execute_reply":"2024-06-24T13:52:33.529754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_sampled.to_csv('train.csv')","metadata":{"execution":{"iopub.status.busy":"2024-06-24T13:52:40.821942Z","iopub.execute_input":"2024-06-24T13:52:40.822517Z","iopub.status.idle":"2024-06-24T13:53:31.819514Z","shell.execute_reply.started":"2024-06-24T13:52:40.822478Z","shell.execute_reply":"2024-06-24T13:53:31.817776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}