├── KaggleWB.png
├── LICENSE
├── README.md
├── chapter_01
├── workbook-blend.ipynb
├── workbook-dae.ipynb
└── workbook-lgb.ipynb
├── chapter_02
├── m5-aggregations.ipynb
├── m5-predict-private-leaderboard.ipynb
├── m5-predict-public-leaderboard.ipynb
├── m5-train-day-1913-horizon-14.ipynb
├── m5-train-day-1913-horizon-21.ipynb
├── m5-train-day-1913-horizon-28.ipynb
├── m5-train-day-1913-horizon-7.ipynb
├── m5-train-day-1941-horizon-14.ipynb
├── m5-train-day-1941-horizon-21.ipynb
├── m5-train-day-1941-horizon-28.ipynb
├── m5-train-day-1941-horizon-7.ipynb
└── m5-uncertainty-predict-quantile-with-gcp.ipynb
├── chapter_03
└── ch3-end-to-end-image-classification.ipynb
├── chapter_04
└── ch4-end-to-end-nlp.ipynb
└── cover.png
/KaggleWB.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/The-Kaggle-Workbook/f264cf5d1d6d4bf03b876e3f2aa667ebf42a36db/KaggleWB.png
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |

2 |
3 | ## Machine Learning Summit 2025
4 | **Bridging Theory and Practice: ML Solutions for Today’s Challenges**
5 |
6 | 3 days, 20+ experts, and 25+ tech sessions and talks covering critical aspects of:
7 | - **Agentic and Generative AI**
8 | - **Applied Machine Learning in the Real World**
9 | - **ML Engineering and Optimization**
10 |
11 | 👉 [Book your ticket now >>](https://packt.link/mlsumgh)
12 |
13 | ---
14 |
15 | ## Join Our Newsletters 📬
16 |
17 | ### DataPro
18 | *The future of AI is unfolding. Don’t fall behind.*
19 |
20 | 
21 |
22 | Stay ahead with [**DataPro**](https://landing.packtpub.com/subscribe-datapronewsletter/?link_from_packtlink=yes), the free weekly newsletter for data scientists, AI/ML researchers, and data engineers.
23 | From trending tools like **PyTorch**, **scikit-learn**, **XGBoost**, and **BentoML** to hands-on insights on **database optimization** and real-world **ML workflows**, you’ll get what matters, fast.
24 |
25 | > Stay sharp with [DataPro](https://landing.packtpub.com/subscribe-datapronewsletter/?link_from_packtlink=yes). Join **115K+ data professionals** who never miss a beat.
26 |
27 | ---
28 |
29 | ### BIPro
30 | *Business runs on data. Make sure yours tells the right story.*
31 |
32 | 
33 |
34 | [**BIPro**](https://landing.packtpub.com/subscribe-bipro-newsletter/?link_from_packtlink=yes) is your free weekly newsletter for BI professionals, analysts, and data leaders.
35 | Get practical tips on **dashboarding**, **data visualization**, and **analytics strategy** with tools like **Power BI**, **Tableau**, **Looker**, **SQL**, and **dbt**.
36 |
37 | > Get smarter with [BIPro](https://landing.packtpub.com/subscribe-bipro-newsletter/?link_from_packtlink=yes). Trusted by **35K+ BI professionals**, see what you’re missing.
38 |
39 |
40 | ### [Packt Conference : Put Generative AI to work on Oct 11-13 (Virtual)](https://packt.link/JGIEY)
41 |
42 | [](https://packt.link/JGIEY)
43 | 3 Days, 20+ AI Experts, 25+ Workshops and Power Talks
44 |
45 | Code: USD75OFF
46 |
47 | # The-Kaggle-Workbook
48 | Code Repository for The Kaggle Workbook, Published by Packt
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | |
57 |
58 | Key Features
59 |
60 | - Explore data science, original ideas, and winning solutions from past Kaggle competitions
61 | - Challenge yourself and start thinking like a Kaggle Grandmaster
62 | - Fill your portfolio with impressive case studies that will come in handy during interviews
63 |
64 | |
65 |
66 |
67 |
68 |
69 | ## Getting started
70 |
71 |
72 |
73 | You can run these notebooks on cloud platforms like [Kaggle](https://www.kaggle.com/) [Colab](https://colab.research.google.com/) or your local machine. Note that most chapters require a GPU even TPU sometimes to run in a reasonable amount of time, so we recommend one of the cloud platforms as they come pre-installed with CUDA.
74 |
75 |
76 |
77 | ### Running on a cloud platform
78 |
79 |
80 | To run these notebooks on a cloud platform, just click on one of the badges (Colab or Kaggle) in the table below. The code will be reproduced from Github directly onto the choosen platform (you may have to add the necessary data before running it). Alternatively, we also provide links to the fully working original notebook on Kaggle that you can copy and immediately run.
81 |
82 | |no| Chapter | Notebook | Colab | Kaggle |
83 | |:--| :-------- | :-------- | :-------: | :-------: |
84 | |01| The Most Renowned Tabular Competition – Porto Seguro’s Safe Driver Prediction | [workbook-blend](https://www.kaggle.com/code/lucamassaron/workbook-blend) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_01/workbook-blend.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_01/workbook-blend.ipynb)|
85 | ||| [workbook-dae](https://www.kaggle.com/code/lucamassaron/workbook-dae) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_01/workbook-dae.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_01/workbook-dae.ipynb)|
86 | ||| [workbook-lgb](https://www.kaggle.com/code/lucamassaron/workbook-lgb) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_01/workbook-lgb.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_01/workbook-lgb.ipynb)|
87 | |02| The Makridakis Competitions – M5 on Kaggle for Accuracy and Uncertainty | [m5-predict-private-leaderboard](https://www.kaggle.com/code/lucamassaron/m5-predict-private-leaderboard) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-predict-private-leaderboard.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-predict-private-leaderboard.ipynb)|
88 | || | [m5-predict-public-leaderboard](https://www.kaggle.com/lucamassaron/m5-predict-public-leaderboard) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-predict-public-leaderboard.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-predict-public-leaderboard.ipynb)
89 | || | [m5-train-day-1913-horizon-7](https://www.kaggle.com/lucamassaron/m5-train-day-1913-horizon-7) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1913-horizon-7.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1913-horizon-7.ipynb)
90 | || | [m5-train-day-1913-horizon-14](https://www.kaggle.com/lucamassaron/m5-train-day-1913-horizon-14) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1913-horizon-14.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1913-horizon-14.ipynb)
91 | || | [m5-train-day-1913-horizon-21](https://www.kaggle.com/lucamassaron/m5-train-day-1913-horizon-21) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1913-horizon-21.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1913-horizon-21.ipynb)
92 | || | [m5-train-day-1913-horizon-28](https://www.kaggle.com/lucamassaron/m5-train-day-1913-horizon-28) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1913-horizon-28.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1913-horizon-28.ipynb)
93 | || | [m5-train-day-1941-horizon-7](https://www.kaggle.com/lucamassaron/m5-train-day-1941-horizon-7) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1941-horizon-7.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1941-horizon-7.ipynb)
94 | || | [m5-train-day-1941-horizon-14](https://www.kaggle.com/lucamassaron/m5-train-day-1941-horizon-14) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1941-horizon-14.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1941-horizon-14.ipynb)
95 | || | [m5-train-day-1941-horizon-21](https://www.kaggle.com/lucamassaron/m5-train-day-1941-horizon-21) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1941-horizon-21.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1941-horizon-21.ipynb)
96 | || | [m5-train-day-1941-horizon-28](https://www.kaggle.com/lucamassaron/m5-train-day-1941-horizon-28) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1941-horizon-28.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-train-day-1941-horizon-28.ipynb)
97 | || | [m5-aggregations](https://www.kaggle.com/code/lucamassaron/m5-aggregations) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-aggregations.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-aggregations.ipynb)
98 | || | [m5-uncertainty-predict-quantile-with-gcp](https://www.kaggle.com/lucamassaron/m5-uncertainty-predict-quantile-with-gcp) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-uncertainty-predict-quantile-with-gcp.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_02/m5-uncertainty-predict-quantile-with-gcp.ipynb)
99 | |03| Vision Competition: Cassava Leaf Disease Competition | [ch3-end-to-end-image-classification](https://www.kaggle.com/code/konradb/ch3-end-to-end-image-classification)| [](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_03/ch3-end-to-end-image-classification.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_03/ch3-end-to-end-image-classification.ipynb)|
100 | |04| NLP Competition – Google Quest Q&A Labeling | [ch4-end-to-end-nlp](https://www.kaggle.com/code/konradb/ch4-end-to-end-nlp) |[](https://colab.research.google.com/github/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_04/ch4-end-to-end-nlp.ipynb)|[](https://kaggle.com/kernels/welcome?src=https://github.com/PacktPublishing/The-Kaggle-Workbook/blob/main/chapter_04/ch4-end-to-end-nlp.ipynb)|
101 |
102 | ## Join our Discord server
103 |
104 | Join our Discord community to meet like-minded people and learn alongside more than 3000 members at [Discord](https://packt.link/KaggleDiscord)
105 |
106 | ## Book description
107 | More than 80,000 Kaggle novices currently participate in Kaggle competitions. To help them navigate the often-overwhelming world of Kaggle, two Grandmasters put their heads together to write The Kaggle Book. The first guidebook on techniques for success has since made plenty of waves in the community. Now, they’ve come back with an even more practical approach based on hands-on exercises that can help you start thinking like an experienced data scientist.
108 |
109 | In this book, you’ll get up close and personal with four extensive case studies based on past Kaggle competitions. You’ll:
110 |
111 | * Learn how bright minds predicted which drivers would likely avoid filing insurance claims in Brazil
112 |
113 | * See how expert Kagglers estimated the uncertainty distribution of Walmart unit sales
114 |
115 | * Discover the different solutions on how to identify the type of disease present on cassava leaves that were discovered in 2021
116 |
117 | * Learn how the Kaggle community classified detected toxic content on Quora with NLP
118 |
119 | You can use this workbook as a supplement alongside the Kaggle Book or on its own alongside resources available on the Kaggle website and other online communities. Whatever path you choose, this workbook will help make you a formidable Kaggle competitor.
120 |
121 | ## What you will learn
122 | * Boost your data science skillset with a curated selection of exercises
123 | * Combine different methods to create better solutions
124 | * Case studies and exercises to take your data modeling skills further
125 | * Get a deeper insight into NLP and how it can help you solve unlikely challenges
126 | * Sharpen your knowledge of time-series forecasting
127 | * Challenge yourself to become a better data scientist
128 |
129 | ## Who this book is for
130 | If you’re new to Kaggle and want to sink your teeth into practical exercises, start with The Kaggle Book, first. A basic understanding of the Kaggle platform, along with knowledge of machine learning and data science is a prerequisite.
131 |
132 | This book is suitable for anyone starting their Kaggle journey or veterans trying to get better at it. Data analysts/scientists who want to do better in Kaggle competitions and secure jobs with tech giants will find this book helpful.
133 |
134 | ## Table of contents
135 |
136 | 1. The Most Renowned Tabular Competition – Porto Seguro’s Safe Driver Prediction
137 | 2. The Makridakis Competitions – M5 on Kaggle for Accuracy and Uncertainty
138 | 3. Vision Competition: Cassava Leaf Disease Competition
139 | 4. NLP Competition – Google Quest Q&A Labeling
140 |
141 |
142 |
143 |
144 |
145 | |
146 |
147 |
148 |
149 | ### Download a free PDF
150 |
151 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
152 | https://packt.link/free-ebook/9781804611210
--------------------------------------------------------------------------------
/chapter_01/workbook-blend.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "47960894",
7 | "metadata": {
8 | "execution": {
9 | "iopub.execute_input": "2022-07-30T20:57:38.950665Z",
10 | "iopub.status.busy": "2022-07-30T20:57:38.949942Z",
11 | "iopub.status.idle": "2022-07-30T20:57:38.966850Z",
12 | "shell.execute_reply": "2022-07-30T20:57:38.965478Z"
13 | },
14 | "papermill": {
15 | "duration": 0.027111,
16 | "end_time": "2022-07-30T20:57:38.969575",
17 | "exception": false,
18 | "start_time": "2022-07-30T20:57:38.942464",
19 | "status": "completed"
20 | },
21 | "tags": []
22 | },
23 | "outputs": [],
24 | "source": [
25 | "import pandas as pd\n",
26 | "import numpy as np"
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": 2,
32 | "id": "4c4b4e7f",
33 | "metadata": {
34 | "execution": {
35 | "iopub.execute_input": "2022-07-30T20:57:38.978285Z",
36 | "iopub.status.busy": "2022-07-30T20:57:38.977943Z",
37 | "iopub.status.idle": "2022-07-30T20:57:38.985266Z",
38 | "shell.execute_reply": "2022-07-30T20:57:38.984276Z"
39 | },
40 | "papermill": {
41 | "duration": 0.01452,
42 | "end_time": "2022-07-30T20:57:38.987551",
43 | "exception": false,
44 | "start_time": "2022-07-30T20:57:38.973031",
45 | "status": "completed"
46 | },
47 | "tags": []
48 | },
49 | "outputs": [],
50 | "source": [
51 | "def eval_gini(y_true, y_pred):\n",
52 | " n_samples = y_true.shape[0]\n",
53 | " L_mid = np.linspace(1 / n_samples, 1, n_samples)\n",
54 | "\n",
55 | " pred_order = y_true[y_pred.argsort()]\n",
56 | " L_pred = np.cumsum(pred_order) / np.sum(pred_order)\n",
57 | " G_pred = np.sum(L_mid - L_pred)\n",
58 | "\n",
59 | " true_order = y_true[y_true.argsort()]\n",
60 | " L_true = np.cumsum(true_order) / np.sum(true_order)\n",
61 | " G_true = np.sum(L_mid - L_true)\n",
62 | "\n",
63 | " eval_result = G_pred / G_true\n",
64 | " return eval_result"
65 | ]
66 | },
67 | {
68 | "cell_type": "code",
69 | "execution_count": 3,
70 | "id": "10310872",
71 | "metadata": {
72 | "execution": {
73 | "iopub.execute_input": "2022-07-30T20:57:38.996216Z",
74 | "iopub.status.busy": "2022-07-30T20:57:38.995482Z",
75 | "iopub.status.idle": "2022-07-30T20:57:42.184084Z",
76 | "shell.execute_reply": "2022-07-30T20:57:42.182728Z"
77 | },
78 | "papermill": {
79 | "duration": 3.196225,
80 | "end_time": "2022-07-30T20:57:42.187015",
81 | "exception": false,
82 | "start_time": "2022-07-30T20:57:38.990790",
83 | "status": "completed"
84 | },
85 | "tags": []
86 | },
87 | "outputs": [],
88 | "source": [
89 | "lgb_oof = pd.read_csv(\"../input/workbook-lgb/lgb_oof.csv\")\n",
90 | "dnn_oof = pd.read_csv(\"../input/workbook-dae/dnn_oof.csv\")\n",
91 | "\n",
92 | "target = pd.read_csv(\"../input/porto-seguro-safe-driver-prediction/train.csv\", usecols=['id','target']) "
93 | ]
94 | },
95 | {
96 | "cell_type": "code",
97 | "execution_count": 4,
98 | "id": "35e7658b",
99 | "metadata": {
100 | "execution": {
101 | "iopub.execute_input": "2022-07-30T20:57:42.196136Z",
102 | "iopub.status.busy": "2022-07-30T20:57:42.194995Z",
103 | "iopub.status.idle": "2022-07-30T20:57:42.503888Z",
104 | "shell.execute_reply": "2022-07-30T20:57:42.502682Z"
105 | },
106 | "papermill": {
107 | "duration": 0.316622,
108 | "end_time": "2022-07-30T20:57:42.507150",
109 | "exception": false,
110 | "start_time": "2022-07-30T20:57:42.190528",
111 | "status": "completed"
112 | },
113 | "tags": []
114 | },
115 | "outputs": [],
116 | "source": [
117 | "lgb_oof_ranks = (lgb_oof.target.rank() / len(lgb_oof))\n",
118 | "dnn_oof_ranks = (dnn_oof.target.rank() / len(dnn_oof))"
119 | ]
120 | },
121 | {
122 | "cell_type": "code",
123 | "execution_count": 5,
124 | "id": "ac06b151",
125 | "metadata": {
126 | "execution": {
127 | "iopub.execute_input": "2022-07-30T20:57:42.515771Z",
128 | "iopub.status.busy": "2022-07-30T20:57:42.515369Z",
129 | "iopub.status.idle": "2022-07-30T20:57:44.584257Z",
130 | "shell.execute_reply": "2022-07-30T20:57:44.583019Z"
131 | },
132 | "papermill": {
133 | "duration": 2.076634,
134 | "end_time": "2022-07-30T20:57:44.587253",
135 | "exception": false,
136 | "start_time": "2022-07-30T20:57:42.510619",
137 | "status": "completed"
138 | },
139 | "tags": []
140 | },
141 | "outputs": [
142 | {
143 | "name": "stdout",
144 | "output_type": "stream",
145 | "text": [
146 | "starting from a oof lgb baseline 0.28850\n",
147 | "\n",
148 | "lgd=0.1 dnn=0.9 -> 0.26632\n",
149 | "lgd=0.2 dnn=0.8 -> 0.27188\n",
150 | "lgd=0.3 dnn=0.7 -> 0.27682\n",
151 | "lgd=0.4 dnn=0.6 -> 0.28102\n",
152 | "lgd=0.5 dnn=0.5 -> 0.28440\n",
153 | "lgd=0.6 dnn=0.4 -> 0.28692\n",
154 | "lgd=0.7 dnn=0.3 -> 0.28857\n",
155 | "lgd=0.8 dnn=0.2 -> 0.28938\n",
156 | "lgd=0.9 dnn=0.1 -> 0.28935\n",
157 | "\n",
158 | "Best alpha is 0.8\n"
159 | ]
160 | }
161 | ],
162 | "source": [
163 | "baseline = eval_gini(y_true=target.target, y_pred=lgb_oof_ranks)\n",
164 | "\n",
165 | "print(f\"starting from a oof lgb baseline {baseline:0.5f}\\n\")\n",
166 | "\n",
167 | "best_alpha = 1.0\n",
168 | "\n",
169 | "for alpha in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]:\n",
170 | " ensemble = alpha * lgb_oof_ranks + (1.0 - alpha) * dnn_oof_ranks\n",
171 | " score = eval_gini(y_true=target.target, y_pred=ensemble)\n",
172 | " print(f\"lgd={alpha:0.1f} dnn={(1.0 - alpha):0.1f} -> {score:0.5f}\")\n",
173 | " \n",
174 | " if score > baseline:\n",
175 | " baseline = score\n",
176 | " best_alpha = alpha\n",
177 | " \n",
178 | "print(f\"\\nBest alpha is {best_alpha:0.1f}\")"
179 | ]
180 | },
181 | {
182 | "cell_type": "code",
183 | "execution_count": 6,
184 | "id": "ae3704e9",
185 | "metadata": {
186 | "execution": {
187 | "iopub.execute_input": "2022-07-30T20:57:44.597141Z",
188 | "iopub.status.busy": "2022-07-30T20:57:44.596557Z",
189 | "iopub.status.idle": "2022-07-30T20:57:45.925726Z",
190 | "shell.execute_reply": "2022-07-30T20:57:45.924165Z"
191 | },
192 | "papermill": {
193 | "duration": 1.337879,
194 | "end_time": "2022-07-30T20:57:45.929049",
195 | "exception": false,
196 | "start_time": "2022-07-30T20:57:44.591170",
197 | "status": "completed"
198 | },
199 | "tags": []
200 | },
201 | "outputs": [],
202 | "source": [
203 | "lgb_submission = pd.read_csv(\"../input/workbook-lgb/lgb_submission.csv\")\n",
204 | "dnn_submission = pd.read_csv(\"../input/workbook-dae/dnn_submission.csv\")\n",
205 | "\n",
206 | "submission = pd.read_csv(\"../input/porto-seguro-safe-driver-prediction/sample_submission.csv\")"
207 | ]
208 | },
209 | {
210 | "cell_type": "code",
211 | "execution_count": 7,
212 | "id": "10fd2b5b",
213 | "metadata": {
214 | "execution": {
215 | "iopub.execute_input": "2022-07-30T20:57:45.938885Z",
216 | "iopub.status.busy": "2022-07-30T20:57:45.937993Z",
217 | "iopub.status.idle": "2022-07-30T20:57:49.459454Z",
218 | "shell.execute_reply": "2022-07-30T20:57:49.458267Z"
219 | },
220 | "papermill": {
221 | "duration": 3.529131,
222 | "end_time": "2022-07-30T20:57:49.462068",
223 | "exception": false,
224 | "start_time": "2022-07-30T20:57:45.932937",
225 | "status": "completed"
226 | },
227 | "tags": []
228 | },
229 | "outputs": [],
230 | "source": [
231 | "lgb_ranks = (lgb_submission.target.rank() / len(lgb_submission))\n",
232 | "dnn_ranks = (dnn_submission.target.rank() / len(dnn_submission))\n",
233 | "\n",
234 | "submission.target = lgb_ranks * 0.5 + dnn_ranks * 0.5\n",
235 | "\n",
236 | "submission.to_csv(\"equal_blend_rank.csv\", index=False)"
237 | ]
238 | },
239 | {
240 | "cell_type": "code",
241 | "execution_count": 8,
242 | "id": "41637edb",
243 | "metadata": {
244 | "execution": {
245 | "iopub.execute_input": "2022-07-30T20:57:49.471917Z",
246 | "iopub.status.busy": "2022-07-30T20:57:49.471089Z",
247 | "iopub.status.idle": "2022-07-30T20:57:52.879101Z",
248 | "shell.execute_reply": "2022-07-30T20:57:52.877867Z"
249 | },
250 | "papermill": {
251 | "duration": 3.415968,
252 | "end_time": "2022-07-30T20:57:52.881998",
253 | "exception": false,
254 | "start_time": "2022-07-30T20:57:49.466030",
255 | "status": "completed"
256 | },
257 | "tags": []
258 | },
259 | "outputs": [],
260 | "source": [
261 | "best_alpha= 0.8\n",
262 | "\n",
263 | "lgb_ranks = (lgb_submission.target.rank() / len(lgb_submission))\n",
264 | "dnn_ranks = (dnn_submission.target.rank() / len(dnn_submission))\n",
265 | "\n",
266 | "submission.target = lgb_ranks * best_alpha + dnn_ranks * (1.0 - best_alpha)\n",
267 | "\n",
268 | "submission.to_csv(\"blend_rank.csv\", index=False)"
269 | ]
270 | }
271 | ],
272 | "metadata": {
273 | "kernelspec": {
274 | "display_name": "Python 3",
275 | "language": "python",
276 | "name": "python3"
277 | },
278 | "language_info": {
279 | "codemirror_mode": {
280 | "name": "ipython",
281 | "version": 3
282 | },
283 | "file_extension": ".py",
284 | "mimetype": "text/x-python",
285 | "name": "python",
286 | "nbconvert_exporter": "python",
287 | "pygments_lexer": "ipython3",
288 | "version": "3.7.12"
289 | },
290 | "papermill": {
291 | "default_parameters": {},
292 | "duration": 24.415119,
293 | "end_time": "2022-07-30T20:57:53.506735",
294 | "environment_variables": {},
295 | "exception": null,
296 | "input_path": "__notebook__.ipynb",
297 | "output_path": "__notebook__.ipynb",
298 | "parameters": {},
299 | "start_time": "2022-07-30T20:57:29.091616",
300 | "version": "2.3.4"
301 | }
302 | },
303 | "nbformat": 4,
304 | "nbformat_minor": 5
305 | }
306 |
--------------------------------------------------------------------------------
/chapter_01/workbook-lgb.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "46fd6b07",
7 | "metadata": {
8 | "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
9 | "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
10 | "execution": {
11 | "iopub.execute_input": "2022-07-30T08:39:49.714860Z",
12 | "iopub.status.busy": "2022-07-30T08:39:49.713757Z",
13 | "iopub.status.idle": "2022-07-30T08:39:52.680913Z",
14 | "shell.execute_reply": "2022-07-30T08:39:52.679670Z"
15 | },
16 | "papermill": {
17 | "duration": 2.978557,
18 | "end_time": "2022-07-30T08:39:52.684125",
19 | "exception": false,
20 | "start_time": "2022-07-30T08:39:49.705568",
21 | "status": "completed"
22 | },
23 | "tags": []
24 | },
25 | "outputs": [
26 | {
27 | "data": {
28 | "text/html": [
29 | "\n"
50 | ],
51 | "text/plain": [
52 | ""
53 | ]
54 | },
55 | "metadata": {},
56 | "output_type": "display_data"
57 | }
58 | ],
59 | "source": [
60 | "import numpy as np\n",
61 | "import pandas as pd\n",
62 | "import optuna\n",
63 | "import lightgbm as lgb\n",
64 | "from path import Path\n",
65 | "from sklearn.model_selection import StratifiedKFold"
66 | ]
67 | },
68 | {
69 | "cell_type": "code",
70 | "execution_count": 2,
71 | "id": "b890f156",
72 | "metadata": {
73 | "execution": {
74 | "iopub.execute_input": "2022-07-30T08:39:52.696260Z",
75 | "iopub.status.busy": "2022-07-30T08:39:52.695810Z",
76 | "iopub.status.idle": "2022-07-30T08:39:52.705476Z",
77 | "shell.execute_reply": "2022-07-30T08:39:52.704393Z"
78 | },
79 | "papermill": {
80 | "duration": 0.018545,
81 | "end_time": "2022-07-30T08:39:52.707977",
82 | "exception": false,
83 | "start_time": "2022-07-30T08:39:52.689432",
84 | "status": "completed"
85 | },
86 | "tags": []
87 | },
88 | "outputs": [],
89 | "source": [
90 | "class Config:\n",
91 | " input_path = Path('../input/porto-seguro-safe-driver-prediction')\n",
92 | " optuna_lgb = False\n",
93 | " n_estimators = 1500\n",
94 | " early_stopping_round = 150\n",
95 | " cv_folds = 5\n",
96 | " random_state = 0\n",
97 | " params = {'objective': 'binary',\n",
98 | " 'boosting_type': 'gbdt',\n",
99 | " 'learning_rate': 0.01,\n",
100 | " 'max_bin': 25,\n",
101 | " 'num_leaves': 31,\n",
102 | " 'min_child_samples': 1500,\n",
103 | " 'colsample_bytree': 0.7,\n",
104 | " 'subsample_freq': 1,\n",
105 | " 'subsample': 0.7,\n",
106 | " 'reg_alpha': 1.0,\n",
107 | " 'reg_lambda': 1.0,\n",
108 | " 'verbosity': 0,\n",
109 | " 'random_state': 0}\n",
110 | " \n",
111 | "config = Config()"
112 | ]
113 | },
114 | {
115 | "cell_type": "code",
116 | "execution_count": 3,
117 | "id": "2bfc9fd4",
118 | "metadata": {
119 | "execution": {
120 | "iopub.execute_input": "2022-07-30T08:39:52.720316Z",
121 | "iopub.status.busy": "2022-07-30T08:39:52.719548Z",
122 | "iopub.status.idle": "2022-07-30T08:40:04.770302Z",
123 | "shell.execute_reply": "2022-07-30T08:40:04.769115Z"
124 | },
125 | "papermill": {
126 | "duration": 12.060232,
127 | "end_time": "2022-07-30T08:40:04.773236",
128 | "exception": false,
129 | "start_time": "2022-07-30T08:39:52.713004",
130 | "status": "completed"
131 | },
132 | "tags": []
133 | },
134 | "outputs": [],
135 | "source": [
136 | "train = pd.read_csv(config.input_path / 'train.csv', index_col='id')\n",
137 | "test = pd.read_csv(config.input_path / 'test.csv', index_col='id')\n",
138 | "submission = pd.read_csv(config.input_path / 'sample_submission.csv', index_col='id')"
139 | ]
140 | },
141 | {
142 | "cell_type": "code",
143 | "execution_count": 4,
144 | "id": "3946b9c4",
145 | "metadata": {
146 | "execution": {
147 | "iopub.execute_input": "2022-07-30T08:40:04.785713Z",
148 | "iopub.status.busy": "2022-07-30T08:40:04.785026Z",
149 | "iopub.status.idle": "2022-07-30T08:40:04.790040Z",
150 | "shell.execute_reply": "2022-07-30T08:40:04.789216Z"
151 | },
152 | "papermill": {
153 | "duration": 0.013557,
154 | "end_time": "2022-07-30T08:40:04.792155",
155 | "exception": false,
156 | "start_time": "2022-07-30T08:40:04.778598",
157 | "status": "completed"
158 | },
159 | "tags": []
160 | },
161 | "outputs": [],
162 | "source": [
163 | "calc_features = [feat for feat in train.columns if \"_calc\" in feat]\n",
164 | "cat_features = [feat for feat in train.columns if \"_cat\" in feat]"
165 | ]
166 | },
167 | {
168 | "cell_type": "code",
169 | "execution_count": 5,
170 | "id": "8dd8d23c",
171 | "metadata": {
172 | "execution": {
173 | "iopub.execute_input": "2022-07-30T08:40:04.804118Z",
174 | "iopub.status.busy": "2022-07-30T08:40:04.803493Z",
175 | "iopub.status.idle": "2022-07-30T08:40:04.950739Z",
176 | "shell.execute_reply": "2022-07-30T08:40:04.949246Z"
177 | },
178 | "papermill": {
179 | "duration": 0.156931,
180 | "end_time": "2022-07-30T08:40:04.954042",
181 | "exception": false,
182 | "start_time": "2022-07-30T08:40:04.797111",
183 | "status": "completed"
184 | },
185 | "tags": []
186 | },
187 | "outputs": [],
188 | "source": [
189 | "# Extracting target\n",
190 | "target = train[\"target\"]\n",
191 | "train = train.drop(\"target\", axis=\"columns\")"
192 | ]
193 | },
194 | {
195 | "cell_type": "code",
196 | "execution_count": 6,
197 | "id": "88a3cf95",
198 | "metadata": {
199 | "execution": {
200 | "iopub.execute_input": "2022-07-30T08:40:04.966232Z",
201 | "iopub.status.busy": "2022-07-30T08:40:04.965767Z",
202 | "iopub.status.idle": "2022-07-30T08:40:05.230309Z",
203 | "shell.execute_reply": "2022-07-30T08:40:05.228443Z"
204 | },
205 | "papermill": {
206 | "duration": 0.274069,
207 | "end_time": "2022-07-30T08:40:05.233251",
208 | "exception": false,
209 | "start_time": "2022-07-30T08:40:04.959182",
210 | "status": "completed"
211 | },
212 | "tags": []
213 | },
214 | "outputs": [],
215 | "source": [
216 | "# Removing calc features\n",
217 | "train = train.drop(calc_features, axis=\"columns\")\n",
218 | "test = test.drop(calc_features, axis=\"columns\")"
219 | ]
220 | },
221 | {
222 | "cell_type": "code",
223 | "execution_count": 7,
224 | "id": "35f7321a",
225 | "metadata": {
226 | "execution": {
227 | "iopub.execute_input": "2022-07-30T08:40:05.245503Z",
228 | "iopub.status.busy": "2022-07-30T08:40:05.245010Z",
229 | "iopub.status.idle": "2022-07-30T08:40:08.264195Z",
230 | "shell.execute_reply": "2022-07-30T08:40:08.262614Z"
231 | },
232 | "papermill": {
233 | "duration": 3.033004,
234 | "end_time": "2022-07-30T08:40:08.271536",
235 | "exception": false,
236 | "start_time": "2022-07-30T08:40:05.238532",
237 | "status": "completed"
238 | },
239 | "tags": []
240 | },
241 | "outputs": [],
242 | "source": [
243 | "# Adding one-hot encoding of cat features\n",
244 | "train = pd.get_dummies(train, columns=cat_features)\n",
245 | "test = pd.get_dummies(test, columns=cat_features)"
246 | ]
247 | },
248 | {
249 | "cell_type": "code",
250 | "execution_count": 8,
251 | "id": "45634b52",
252 | "metadata": {
253 | "execution": {
254 | "iopub.execute_input": "2022-07-30T08:40:08.285541Z",
255 | "iopub.status.busy": "2022-07-30T08:40:08.284770Z",
256 | "iopub.status.idle": "2022-07-30T08:40:08.291098Z",
257 | "shell.execute_reply": "2022-07-30T08:40:08.289764Z"
258 | },
259 | "papermill": {
260 | "duration": 0.01597,
261 | "end_time": "2022-07-30T08:40:08.294034",
262 | "exception": false,
263 | "start_time": "2022-07-30T08:40:08.278064",
264 | "status": "completed"
265 | },
266 | "tags": []
267 | },
268 | "outputs": [],
269 | "source": [
270 | "assert((train.columns==test.columns).all())"
271 | ]
272 | },
273 | {
274 | "cell_type": "code",
275 | "execution_count": 9,
276 | "id": "6d4e4f1b",
277 | "metadata": {
278 | "execution": {
279 | "iopub.execute_input": "2022-07-30T08:40:08.306291Z",
280 | "iopub.status.busy": "2022-07-30T08:40:08.305802Z",
281 | "iopub.status.idle": "2022-07-30T08:40:09.530960Z",
282 | "shell.execute_reply": "2022-07-30T08:40:09.529395Z"
283 | },
284 | "papermill": {
285 | "duration": 1.234753,
286 | "end_time": "2022-07-30T08:40:09.533778",
287 | "exception": false,
288 | "start_time": "2022-07-30T08:40:08.299025",
289 | "status": "completed"
290 | },
291 | "tags": []
292 | },
293 | "outputs": [],
294 | "source": [
295 | "from numba import jit\n",
296 | "\n",
297 | "@jit\n",
298 | "def eval_gini(y_true, y_pred):\n",
299 | " y_true = np.asarray(y_true)\n",
300 | " y_true = y_true[np.argsort(y_pred)]\n",
301 | " ntrue = 0\n",
302 | " gini = 0\n",
303 | " delta = 0\n",
304 | " n = len(y_true)\n",
305 | " for i in range(n-1, -1, -1):\n",
306 | " y_i = y_true[i]\n",
307 | " ntrue += y_i\n",
308 | " gini += y_i * delta\n",
309 | " delta += 1 - y_i\n",
310 | " gini = 1 - 2 * gini / (ntrue * (n - ntrue))\n",
311 | " return gini\n",
312 | "\n",
313 | "def gini_lgb(y_true, y_pred):\n",
314 | " eval_name = 'normalized_gini_coef'\n",
315 | " eval_result = eval_gini(y_true, y_pred)\n",
316 | " is_higher_better = True\n",
317 | " return eval_name, eval_result, is_higher_better"
318 | ]
319 | },
320 | {
321 | "cell_type": "code",
322 | "execution_count": 10,
323 | "id": "febad662",
324 | "metadata": {
325 | "execution": {
326 | "iopub.execute_input": "2022-07-30T08:40:09.546621Z",
327 | "iopub.status.busy": "2022-07-30T08:40:09.546088Z",
328 | "iopub.status.idle": "2022-07-30T08:40:09.564393Z",
329 | "shell.execute_reply": "2022-07-30T08:40:09.563050Z"
330 | },
331 | "papermill": {
332 | "duration": 0.028159,
333 | "end_time": "2022-07-30T08:40:09.566967",
334 | "exception": false,
335 | "start_time": "2022-07-30T08:40:09.538808",
336 | "status": "completed"
337 | },
338 | "tags": []
339 | },
340 | "outputs": [],
341 | "source": [
342 | " if config.optuna_lgb:\n",
343 | " \n",
344 | " def objective(trial):\n",
345 | " params = {\n",
346 | " 'learning_rate': trial.suggest_float(\"learning_rate\", 0.01, 1.0),\n",
347 | " 'num_leaves': trial.suggest_int(\"num_leaves\", 3, 255),\n",
348 | " 'min_child_samples': trial.suggest_int(\"min_child_samples\", 3, 3000),\n",
349 | " 'colsample_bytree': trial.suggest_float(\"colsample_bytree\", 0.1, 1.0),\n",
350 | " 'subsample_freq': trial.suggest_int(\"subsample_freq\", 0, 10),\n",
351 | " 'subsample': trial.suggest_float(\"subsample\", 0.1, 1.0),\n",
352 | " 'reg_alpha': trial.suggest_loguniform(\"reg_alpha\", 1e-9, 10.0),\n",
353 | " 'reg_lambda': trial.suggest_loguniform(\"reg_lambda\", 1e-9, 10.0),\n",
354 | " }\n",
355 | " \n",
356 | " score = list()\n",
357 | " skf = StratifiedKFold(n_splits=config.cv_folds, shuffle=True, random_state=config.random_state)\n",
358 | "\n",
359 | " for train_idx, valid_idx in skf.split(train, target):\n",
360 | " X_train, y_train = train.iloc[train_idx], target.iloc[train_idx]\n",
361 | " X_valid, y_valid = train.iloc[valid_idx], target.iloc[valid_idx]\n",
362 | "\n",
363 | " model = lgb.LGBMClassifier(**params,\n",
364 | " n_estimators=1500,\n",
365 | " early_stopping_round=150,\n",
366 | " force_row_wise=True)\n",
367 | "\n",
368 | " callbacks=[lgb.early_stopping(stopping_rounds=150, verbose=False)]\n",
369 | " model.fit(X_train, y_train, eval_set=[(X_valid, y_valid)], eval_metric=gini_lgb, callbacks=callbacks)\n",
370 | " score.append(model.best_score_['valid_0']['normalized_gini_coef'])\n",
371 | "\n",
372 | " return np.mean(score)\n",
373 | "\n",
374 | " study = optuna.create_study(direction=\"maximize\")\n",
375 | " study.optimize(objective, n_trials=300)\n",
376 | "\n",
377 | " print(\"Best Gini Normalized Score\", study.best_value)\n",
378 | " print(\"Best parameters\", study.best_params)\n",
379 | " \n",
380 | " params = {'objective': 'binary',\n",
381 | " 'boosting_type': 'gbdt',\n",
382 | " 'verbosity': 0,\n",
383 | " 'random_state': 0}\n",
384 | " \n",
385 | " params.update(study.best_params)\n",
386 | " \n",
387 | "else:\n",
388 | " params = config.params"
389 | ]
390 | },
391 | {
392 | "cell_type": "code",
393 | "execution_count": 11,
394 | "id": "3fdf52dd",
395 | "metadata": {
396 | "execution": {
397 | "iopub.execute_input": "2022-07-30T08:40:09.580832Z",
398 | "iopub.status.busy": "2022-07-30T08:40:09.579546Z",
399 | "iopub.status.idle": "2022-07-30T08:50:28.667637Z",
400 | "shell.execute_reply": "2022-07-30T08:50:28.666080Z"
401 | },
402 | "papermill": {
403 | "duration": 619.098793,
404 | "end_time": "2022-07-30T08:50:28.671349",
405 | "exception": false,
406 | "start_time": "2022-07-30T08:40:09.572556",
407 | "status": "completed"
408 | },
409 | "tags": []
410 | },
411 | "outputs": [
412 | {
413 | "name": "stdout",
414 | "output_type": "stream",
415 | "text": [
416 | "CV fold 0\n",
417 | "Training until validation scores don't improve for 150 rounds\n",
418 | "[100]\tvalid_0's binary_logloss: 0.153243\tvalid_0's normalized_gini_coef: 0.271457\n",
419 | "[200]\tvalid_0's binary_logloss: 0.15228\tvalid_0's normalized_gini_coef: 0.280599\n",
420 | "[300]\tvalid_0's binary_logloss: 0.15185\tvalid_0's normalized_gini_coef: 0.286829\n",
421 | "[400]\tvalid_0's binary_logloss: 0.151651\tvalid_0's normalized_gini_coef: 0.289906\n",
422 | "[500]\tvalid_0's binary_logloss: 0.151543\tvalid_0's normalized_gini_coef: 0.291906\n",
423 | "[600]\tvalid_0's binary_logloss: 0.151473\tvalid_0's normalized_gini_coef: 0.293377\n",
424 | "[700]\tvalid_0's binary_logloss: 0.151437\tvalid_0's normalized_gini_coef: 0.293827\n",
425 | "[800]\tvalid_0's binary_logloss: 0.151417\tvalid_0's normalized_gini_coef: 0.294276\n",
426 | "[900]\tvalid_0's binary_logloss: 0.15142\tvalid_0's normalized_gini_coef: 0.294119\n",
427 | "CV fold 1\n",
428 | "Training until validation scores don't improve for 150 rounds\n",
429 | "[100]\tvalid_0's binary_logloss: 0.153553\tvalid_0's normalized_gini_coef: 0.255568\n",
430 | "[200]\tvalid_0's binary_logloss: 0.152779\tvalid_0's normalized_gini_coef: 0.261176\n",
431 | "[300]\tvalid_0's binary_logloss: 0.152509\tvalid_0's normalized_gini_coef: 0.264598\n",
432 | "[400]\tvalid_0's binary_logloss: 0.152392\tvalid_0's normalized_gini_coef: 0.266942\n",
433 | "[500]\tvalid_0's binary_logloss: 0.152334\tvalid_0's normalized_gini_coef: 0.268508\n",
434 | "[600]\tvalid_0's binary_logloss: 0.15231\tvalid_0's normalized_gini_coef: 0.269259\n",
435 | "[700]\tvalid_0's binary_logloss: 0.152308\tvalid_0's normalized_gini_coef: 0.269299\n",
436 | "[800]\tvalid_0's binary_logloss: 0.1523\tvalid_0's normalized_gini_coef: 0.269814\n",
437 | "[900]\tvalid_0's binary_logloss: 0.152298\tvalid_0's normalized_gini_coef: 0.270119\n",
438 | "CV fold 2\n",
439 | "Training until validation scores don't improve for 150 rounds\n",
440 | "[100]\tvalid_0's binary_logloss: 0.15349\tvalid_0's normalized_gini_coef: 0.250438\n",
441 | "[200]\tvalid_0's binary_logloss: 0.152638\tvalid_0's normalized_gini_coef: 0.261463\n",
442 | "[300]\tvalid_0's binary_logloss: 0.152286\tvalid_0's normalized_gini_coef: 0.267762\n",
443 | "[400]\tvalid_0's binary_logloss: 0.15211\tvalid_0's normalized_gini_coef: 0.271644\n",
444 | "[500]\tvalid_0's binary_logloss: 0.152015\tvalid_0's normalized_gini_coef: 0.274152\n",
445 | "[600]\tvalid_0's binary_logloss: 0.151963\tvalid_0's normalized_gini_coef: 0.275609\n",
446 | "[700]\tvalid_0's binary_logloss: 0.151933\tvalid_0's normalized_gini_coef: 0.276576\n",
447 | "[800]\tvalid_0's binary_logloss: 0.151919\tvalid_0's normalized_gini_coef: 0.276946\n",
448 | "[900]\tvalid_0's binary_logloss: 0.151906\tvalid_0's normalized_gini_coef: 0.277448\n",
449 | "[1000]\tvalid_0's binary_logloss: 0.151911\tvalid_0's normalized_gini_coef: 0.277363\n",
450 | "CV fold 3\n",
451 | "Training until validation scores don't improve for 150 rounds\n",
452 | "[100]\tvalid_0's binary_logloss: 0.153151\tvalid_0's normalized_gini_coef: 0.28492\n",
453 | "[200]\tvalid_0's binary_logloss: 0.152081\tvalid_0's normalized_gini_coef: 0.294826\n",
454 | "[300]\tvalid_0's binary_logloss: 0.151594\tvalid_0's normalized_gini_coef: 0.301155\n",
455 | "[400]\tvalid_0's binary_logloss: 0.151332\tvalid_0's normalized_gini_coef: 0.305416\n",
456 | "[500]\tvalid_0's binary_logloss: 0.151173\tvalid_0's normalized_gini_coef: 0.308713\n",
457 | "[600]\tvalid_0's binary_logloss: 0.151074\tvalid_0's normalized_gini_coef: 0.310518\n",
458 | "[700]\tvalid_0's binary_logloss: 0.151014\tvalid_0's normalized_gini_coef: 0.311803\n",
459 | "[800]\tvalid_0's binary_logloss: 0.150976\tvalid_0's normalized_gini_coef: 0.312533\n",
460 | "[900]\tvalid_0's binary_logloss: 0.150947\tvalid_0's normalized_gini_coef: 0.31291\n",
461 | "[1000]\tvalid_0's binary_logloss: 0.150928\tvalid_0's normalized_gini_coef: 0.313239\n",
462 | "[1100]\tvalid_0's binary_logloss: 0.15092\tvalid_0's normalized_gini_coef: 0.313284\n",
463 | "[1200]\tvalid_0's binary_logloss: 0.150921\tvalid_0's normalized_gini_coef: 0.313124\n",
464 | "CV fold 4\n",
465 | "Training until validation scores don't improve for 150 rounds\n",
466 | "[100]\tvalid_0's binary_logloss: 0.153417\tvalid_0's normalized_gini_coef: 0.259211\n",
467 | "[200]\tvalid_0's binary_logloss: 0.152528\tvalid_0's normalized_gini_coef: 0.268649\n",
468 | "[300]\tvalid_0's binary_logloss: 0.152123\tvalid_0's normalized_gini_coef: 0.27534\n",
469 | "[400]\tvalid_0's binary_logloss: 0.15192\tvalid_0's normalized_gini_coef: 0.279392\n",
470 | "[500]\tvalid_0's binary_logloss: 0.151813\tvalid_0's normalized_gini_coef: 0.28184\n",
471 | "[600]\tvalid_0's binary_logloss: 0.151733\tvalid_0's normalized_gini_coef: 0.283741\n",
472 | "[700]\tvalid_0's binary_logloss: 0.151682\tvalid_0's normalized_gini_coef: 0.284936\n",
473 | "[800]\tvalid_0's binary_logloss: 0.151647\tvalid_0's normalized_gini_coef: 0.286006\n",
474 | "[900]\tvalid_0's binary_logloss: 0.151625\tvalid_0's normalized_gini_coef: 0.28652\n",
475 | "[1000]\tvalid_0's binary_logloss: 0.151608\tvalid_0's normalized_gini_coef: 0.286903\n",
476 | "[1100]\tvalid_0's binary_logloss: 0.151595\tvalid_0's normalized_gini_coef: 0.287265\n",
477 | "[1200]\tvalid_0's binary_logloss: 0.15159\tvalid_0's normalized_gini_coef: 0.287404\n",
478 | "[1300]\tvalid_0's binary_logloss: 0.151592\tvalid_0's normalized_gini_coef: 0.287313\n",
479 | "[1400]\tvalid_0's binary_logloss: 0.151593\tvalid_0's normalized_gini_coef: 0.287344\n",
480 | "Early stopping, best iteration is:\n",
481 | "[1264]\tvalid_0's binary_logloss: 0.151586\tvalid_0's normalized_gini_coef: 0.287481\n"
482 | ]
483 | }
484 | ],
485 | "source": [
486 | "preds = np.zeros(len(test))\n",
487 | "oof = np.zeros(len(train))\n",
488 | "metric_evaluations = list()\n",
489 | "\n",
490 | "skf = StratifiedKFold(n_splits=config.cv_folds, shuffle=True, random_state=config.random_state)\n",
491 | "\n",
492 | "for idx, (train_idx, valid_idx) in enumerate(skf.split(train, target)):\n",
493 | " print(f\"CV fold {idx}\")\n",
494 | " X_train, y_train = train.iloc[train_idx], target.iloc[train_idx]\n",
495 | " X_valid, y_valid = train.iloc[valid_idx], target.iloc[valid_idx]\n",
496 | " \n",
497 | " model = lgb.LGBMClassifier(**params,\n",
498 | " n_estimators=config.n_estimators,\n",
499 | " early_stopping_round=config.early_stopping_round,\n",
500 | " force_row_wise=True)\n",
501 | " \n",
502 | " callbacks=[lgb.early_stopping(stopping_rounds=150), \n",
503 | " lgb.log_evaluation(period=100, show_stdv=False)]\n",
504 | " \n",
505 | " model.fit(X_train, y_train, eval_set=[(X_valid, y_valid)], eval_metric=gini_lgb, callbacks=callbacks)\n",
506 | " metric_evaluations.append(model.best_score_['valid_0']['normalized_gini_coef'])\n",
507 | " preds += model.predict_proba(test, num_iteration=model.best_iteration_)[:,1] / skf.n_splits\n",
508 | " oof[valid_idx] = model.predict_proba(X_valid, num_iteration=model.best_iteration_)[:,1]"
509 | ]
510 | },
511 | {
512 | "cell_type": "code",
513 | "execution_count": 12,
514 | "id": "95200173",
515 | "metadata": {
516 | "execution": {
517 | "iopub.execute_input": "2022-07-30T08:50:28.693817Z",
518 | "iopub.status.busy": "2022-07-30T08:50:28.693294Z",
519 | "iopub.status.idle": "2022-07-30T08:50:28.700032Z",
520 | "shell.execute_reply": "2022-07-30T08:50:28.699239Z"
521 | },
522 | "papermill": {
523 | "duration": 0.021486,
524 | "end_time": "2022-07-30T08:50:28.703357",
525 | "exception": false,
526 | "start_time": "2022-07-30T08:50:28.681871",
527 | "status": "completed"
528 | },
529 | "tags": []
530 | },
531 | "outputs": [
532 | {
533 | "name": "stdout",
534 | "output_type": "stream",
535 | "text": [
536 | "LightGBM CV Gini Normalized Score: 0.289 (0.015)\n"
537 | ]
538 | }
539 | ],
540 | "source": [
541 | "print(f\"LightGBM CV Gini Normalized Score: {np.mean(metric_evaluations):0.3f} ({np.std(metric_evaluations):0.3f})\")"
542 | ]
543 | },
544 | {
545 | "cell_type": "code",
546 | "execution_count": 13,
547 | "id": "1b2c8569",
548 | "metadata": {
549 | "execution": {
550 | "iopub.execute_input": "2022-07-30T08:50:28.725183Z",
551 | "iopub.status.busy": "2022-07-30T08:50:28.723826Z",
552 | "iopub.status.idle": "2022-07-30T08:50:32.297656Z",
553 | "shell.execute_reply": "2022-07-30T08:50:32.296560Z"
554 | },
555 | "papermill": {
556 | "duration": 3.587616,
557 | "end_time": "2022-07-30T08:50:32.300579",
558 | "exception": false,
559 | "start_time": "2022-07-30T08:50:28.712963",
560 | "status": "completed"
561 | },
562 | "tags": []
563 | },
564 | "outputs": [],
565 | "source": [
566 | "submission['target'] = preds\n",
567 | "submission.to_csv('lgb_submission.csv')"
568 | ]
569 | },
570 | {
571 | "cell_type": "code",
572 | "execution_count": 14,
573 | "id": "c62c62c5",
574 | "metadata": {
575 | "execution": {
576 | "iopub.execute_input": "2022-07-30T08:50:32.321371Z",
577 | "iopub.status.busy": "2022-07-30T08:50:32.320897Z",
578 | "iopub.status.idle": "2022-07-30T08:50:34.679613Z",
579 | "shell.execute_reply": "2022-07-30T08:50:34.678444Z"
580 | },
581 | "papermill": {
582 | "duration": 2.37259,
583 | "end_time": "2022-07-30T08:50:34.682689",
584 | "exception": false,
585 | "start_time": "2022-07-30T08:50:32.310099",
586 | "status": "completed"
587 | },
588 | "tags": []
589 | },
590 | "outputs": [],
591 | "source": [
592 | "oofs = target.to_frame()\n",
593 | "oofs['target'] = oof\n",
594 | "oofs.to_csv('lgb_oof.csv')"
595 | ]
596 | }
597 | ],
598 | "metadata": {
599 | "kernelspec": {
600 | "display_name": "Python 3",
601 | "language": "python",
602 | "name": "python3"
603 | },
604 | "language_info": {
605 | "codemirror_mode": {
606 | "name": "ipython",
607 | "version": 3
608 | },
609 | "file_extension": ".py",
610 | "mimetype": "text/x-python",
611 | "name": "python",
612 | "nbconvert_exporter": "python",
613 | "pygments_lexer": "ipython3",
614 | "version": "3.7.12"
615 | },
616 | "papermill": {
617 | "default_parameters": {},
618 | "duration": 657.129388,
619 | "end_time": "2022-07-30T08:50:36.423479",
620 | "environment_variables": {},
621 | "exception": null,
622 | "input_path": "__notebook__.ipynb",
623 | "output_path": "__notebook__.ipynb",
624 | "parameters": {},
625 | "start_time": "2022-07-30T08:39:39.294091",
626 | "version": "2.3.4"
627 | }
628 | },
629 | "nbformat": 4,
630 | "nbformat_minor": 5
631 | }
632 |
--------------------------------------------------------------------------------
/chapter_02/m5-predict-private-leaderboard.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "6aec719b",
7 | "metadata": {
8 | "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
9 | "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
10 | "execution": {
11 | "iopub.execute_input": "2022-08-10T06:50:59.206312Z",
12 | "iopub.status.busy": "2022-08-10T06:50:59.205529Z",
13 | "iopub.status.idle": "2022-08-10T06:51:01.166649Z",
14 | "shell.execute_reply": "2022-08-10T06:51:01.165361Z"
15 | },
16 | "papermill": {
17 | "duration": 1.96917,
18 | "end_time": "2022-08-10T06:51:01.169619",
19 | "exception": false,
20 | "start_time": "2022-08-10T06:50:59.200449",
21 | "status": "completed"
22 | },
23 | "tags": []
24 | },
25 | "outputs": [
26 | {
27 | "data": {
28 | "text/html": [
29 | "\n"
50 | ],
51 | "text/plain": [
52 | ""
53 | ]
54 | },
55 | "metadata": {},
56 | "output_type": "display_data"
57 | }
58 | ],
59 | "source": [
60 | "import numpy as np\n",
61 | "import pandas as pd\n",
62 | "import os\n",
63 | "import random\n",
64 | "import math\n",
65 | "from decimal import Decimal as dec\n",
66 | "import datetime\n",
67 | "import time\n",
68 | "import gc\n",
69 | "import lightgbm as lgb\n",
70 | "import pickle\n",
71 | "\n",
72 | "import warnings\n",
73 | "warnings.filterwarnings(\"ignore\", category=UserWarning)"
74 | ]
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": 2,
79 | "id": "48679298",
80 | "metadata": {
81 | "execution": {
82 | "iopub.execute_input": "2022-08-10T06:51:01.177116Z",
83 | "iopub.status.busy": "2022-08-10T06:51:01.176382Z",
84 | "iopub.status.idle": "2022-08-10T06:55:04.186957Z",
85 | "shell.execute_reply": "2022-08-10T06:55:04.186066Z"
86 | },
87 | "papermill": {
88 | "duration": 243.017162,
89 | "end_time": "2022-08-10T06:55:04.189631",
90 | "exception": false,
91 | "start_time": "2022-08-10T06:51:01.172469",
92 | "status": "completed"
93 | },
94 | "tags": []
95 | },
96 | "outputs": [
97 | {
98 | "name": "stdout",
99 | "output_type": "stream",
100 | "text": [
101 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_CA_1_7.bin\n",
102 | "[1 -> 7] predict 1/10 CA_1 day 1\n",
103 | "[1 -> 7] predict 1/10 CA_1 day 2\n",
104 | "[1 -> 7] predict 1/10 CA_1 day 3\n",
105 | "[1 -> 7] predict 1/10 CA_1 day 4\n",
106 | "[1 -> 7] predict 1/10 CA_1 day 5\n",
107 | "[1 -> 7] predict 1/10 CA_1 day 6\n",
108 | "[1 -> 7] predict 1/10 CA_1 day 7\n",
109 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_CA_2_7.bin\n",
110 | "[1 -> 7] predict 2/10 CA_2 day 1\n",
111 | "[1 -> 7] predict 2/10 CA_2 day 2\n",
112 | "[1 -> 7] predict 2/10 CA_2 day 3\n",
113 | "[1 -> 7] predict 2/10 CA_2 day 4\n",
114 | "[1 -> 7] predict 2/10 CA_2 day 5\n",
115 | "[1 -> 7] predict 2/10 CA_2 day 6\n",
116 | "[1 -> 7] predict 2/10 CA_2 day 7\n",
117 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_CA_3_7.bin\n",
118 | "[1 -> 7] predict 3/10 CA_3 day 1\n",
119 | "[1 -> 7] predict 3/10 CA_3 day 2\n",
120 | "[1 -> 7] predict 3/10 CA_3 day 3\n",
121 | "[1 -> 7] predict 3/10 CA_3 day 4\n",
122 | "[1 -> 7] predict 3/10 CA_3 day 5\n",
123 | "[1 -> 7] predict 3/10 CA_3 day 6\n",
124 | "[1 -> 7] predict 3/10 CA_3 day 7\n",
125 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_CA_4_7.bin\n",
126 | "[1 -> 7] predict 4/10 CA_4 day 1\n",
127 | "[1 -> 7] predict 4/10 CA_4 day 2\n",
128 | "[1 -> 7] predict 4/10 CA_4 day 3\n",
129 | "[1 -> 7] predict 4/10 CA_4 day 4\n",
130 | "[1 -> 7] predict 4/10 CA_4 day 5\n",
131 | "[1 -> 7] predict 4/10 CA_4 day 6\n",
132 | "[1 -> 7] predict 4/10 CA_4 day 7\n",
133 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_TX_1_7.bin\n",
134 | "[1 -> 7] predict 5/10 TX_1 day 1\n",
135 | "[1 -> 7] predict 5/10 TX_1 day 2\n",
136 | "[1 -> 7] predict 5/10 TX_1 day 3\n",
137 | "[1 -> 7] predict 5/10 TX_1 day 4\n",
138 | "[1 -> 7] predict 5/10 TX_1 day 5\n",
139 | "[1 -> 7] predict 5/10 TX_1 day 6\n",
140 | "[1 -> 7] predict 5/10 TX_1 day 7\n",
141 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_TX_2_7.bin\n",
142 | "[1 -> 7] predict 6/10 TX_2 day 1\n",
143 | "[1 -> 7] predict 6/10 TX_2 day 2\n",
144 | "[1 -> 7] predict 6/10 TX_2 day 3\n",
145 | "[1 -> 7] predict 6/10 TX_2 day 4\n",
146 | "[1 -> 7] predict 6/10 TX_2 day 5\n",
147 | "[1 -> 7] predict 6/10 TX_2 day 6\n",
148 | "[1 -> 7] predict 6/10 TX_2 day 7\n",
149 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_TX_3_7.bin\n",
150 | "[1 -> 7] predict 7/10 TX_3 day 1\n",
151 | "[1 -> 7] predict 7/10 TX_3 day 2\n",
152 | "[1 -> 7] predict 7/10 TX_3 day 3\n",
153 | "[1 -> 7] predict 7/10 TX_3 day 4\n",
154 | "[1 -> 7] predict 7/10 TX_3 day 5\n",
155 | "[1 -> 7] predict 7/10 TX_3 day 6\n",
156 | "[1 -> 7] predict 7/10 TX_3 day 7\n",
157 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_WI_1_7.bin\n",
158 | "[1 -> 7] predict 8/10 WI_1 day 1\n",
159 | "[1 -> 7] predict 8/10 WI_1 day 2\n",
160 | "[1 -> 7] predict 8/10 WI_1 day 3\n",
161 | "[1 -> 7] predict 8/10 WI_1 day 4\n",
162 | "[1 -> 7] predict 8/10 WI_1 day 5\n",
163 | "[1 -> 7] predict 8/10 WI_1 day 6\n",
164 | "[1 -> 7] predict 8/10 WI_1 day 7\n",
165 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_WI_2_7.bin\n",
166 | "[1 -> 7] predict 9/10 WI_2 day 1\n",
167 | "[1 -> 7] predict 9/10 WI_2 day 2\n",
168 | "[1 -> 7] predict 9/10 WI_2 day 3\n",
169 | "[1 -> 7] predict 9/10 WI_2 day 4\n",
170 | "[1 -> 7] predict 9/10 WI_2 day 5\n",
171 | "[1 -> 7] predict 9/10 WI_2 day 6\n",
172 | "[1 -> 7] predict 9/10 WI_2 day 7\n",
173 | "loading ../input/m5-train-day-1941-horizon-7/lgb_model_WI_3_7.bin\n",
174 | "[1 -> 7] predict 10/10 WI_3 day 1\n",
175 | "[1 -> 7] predict 10/10 WI_3 day 2\n",
176 | "[1 -> 7] predict 10/10 WI_3 day 3\n",
177 | "[1 -> 7] predict 10/10 WI_3 day 4\n",
178 | "[1 -> 7] predict 10/10 WI_3 day 5\n",
179 | "[1 -> 7] predict 10/10 WI_3 day 6\n",
180 | "[1 -> 7] predict 10/10 WI_3 day 7\n",
181 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_CA_1_14.bin\n",
182 | "[8 -> 14] predict 1/10 CA_1 day 8\n",
183 | "[8 -> 14] predict 1/10 CA_1 day 9\n",
184 | "[8 -> 14] predict 1/10 CA_1 day 10\n",
185 | "[8 -> 14] predict 1/10 CA_1 day 11\n",
186 | "[8 -> 14] predict 1/10 CA_1 day 12\n",
187 | "[8 -> 14] predict 1/10 CA_1 day 13\n",
188 | "[8 -> 14] predict 1/10 CA_1 day 14\n",
189 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_CA_2_14.bin\n",
190 | "[8 -> 14] predict 2/10 CA_2 day 8\n",
191 | "[8 -> 14] predict 2/10 CA_2 day 9\n",
192 | "[8 -> 14] predict 2/10 CA_2 day 10\n",
193 | "[8 -> 14] predict 2/10 CA_2 day 11\n",
194 | "[8 -> 14] predict 2/10 CA_2 day 12\n",
195 | "[8 -> 14] predict 2/10 CA_2 day 13\n",
196 | "[8 -> 14] predict 2/10 CA_2 day 14\n",
197 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_CA_3_14.bin\n",
198 | "[8 -> 14] predict 3/10 CA_3 day 8\n",
199 | "[8 -> 14] predict 3/10 CA_3 day 9\n",
200 | "[8 -> 14] predict 3/10 CA_3 day 10\n",
201 | "[8 -> 14] predict 3/10 CA_3 day 11\n",
202 | "[8 -> 14] predict 3/10 CA_3 day 12\n",
203 | "[8 -> 14] predict 3/10 CA_3 day 13\n",
204 | "[8 -> 14] predict 3/10 CA_3 day 14\n",
205 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_CA_4_14.bin\n",
206 | "[8 -> 14] predict 4/10 CA_4 day 8\n",
207 | "[8 -> 14] predict 4/10 CA_4 day 9\n",
208 | "[8 -> 14] predict 4/10 CA_4 day 10\n",
209 | "[8 -> 14] predict 4/10 CA_4 day 11\n",
210 | "[8 -> 14] predict 4/10 CA_4 day 12\n",
211 | "[8 -> 14] predict 4/10 CA_4 day 13\n",
212 | "[8 -> 14] predict 4/10 CA_4 day 14\n",
213 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_TX_1_14.bin\n",
214 | "[8 -> 14] predict 5/10 TX_1 day 8\n",
215 | "[8 -> 14] predict 5/10 TX_1 day 9\n",
216 | "[8 -> 14] predict 5/10 TX_1 day 10\n",
217 | "[8 -> 14] predict 5/10 TX_1 day 11\n",
218 | "[8 -> 14] predict 5/10 TX_1 day 12\n",
219 | "[8 -> 14] predict 5/10 TX_1 day 13\n",
220 | "[8 -> 14] predict 5/10 TX_1 day 14\n",
221 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_TX_2_14.bin\n",
222 | "[8 -> 14] predict 6/10 TX_2 day 8\n",
223 | "[8 -> 14] predict 6/10 TX_2 day 9\n",
224 | "[8 -> 14] predict 6/10 TX_2 day 10\n",
225 | "[8 -> 14] predict 6/10 TX_2 day 11\n",
226 | "[8 -> 14] predict 6/10 TX_2 day 12\n",
227 | "[8 -> 14] predict 6/10 TX_2 day 13\n",
228 | "[8 -> 14] predict 6/10 TX_2 day 14\n",
229 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_TX_3_14.bin\n",
230 | "[8 -> 14] predict 7/10 TX_3 day 8\n",
231 | "[8 -> 14] predict 7/10 TX_3 day 9\n",
232 | "[8 -> 14] predict 7/10 TX_3 day 10\n",
233 | "[8 -> 14] predict 7/10 TX_3 day 11\n",
234 | "[8 -> 14] predict 7/10 TX_3 day 12\n",
235 | "[8 -> 14] predict 7/10 TX_3 day 13\n",
236 | "[8 -> 14] predict 7/10 TX_3 day 14\n",
237 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_WI_1_14.bin\n",
238 | "[8 -> 14] predict 8/10 WI_1 day 8\n",
239 | "[8 -> 14] predict 8/10 WI_1 day 9\n",
240 | "[8 -> 14] predict 8/10 WI_1 day 10\n",
241 | "[8 -> 14] predict 8/10 WI_1 day 11\n",
242 | "[8 -> 14] predict 8/10 WI_1 day 12\n",
243 | "[8 -> 14] predict 8/10 WI_1 day 13\n",
244 | "[8 -> 14] predict 8/10 WI_1 day 14\n",
245 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_WI_2_14.bin\n",
246 | "[8 -> 14] predict 9/10 WI_2 day 8\n",
247 | "[8 -> 14] predict 9/10 WI_2 day 9\n",
248 | "[8 -> 14] predict 9/10 WI_2 day 10\n",
249 | "[8 -> 14] predict 9/10 WI_2 day 11\n",
250 | "[8 -> 14] predict 9/10 WI_2 day 12\n",
251 | "[8 -> 14] predict 9/10 WI_2 day 13\n",
252 | "[8 -> 14] predict 9/10 WI_2 day 14\n",
253 | "loading ../input/m5-train-day-1941-horizon-14/lgb_model_WI_3_14.bin\n",
254 | "[8 -> 14] predict 10/10 WI_3 day 8\n",
255 | "[8 -> 14] predict 10/10 WI_3 day 9\n",
256 | "[8 -> 14] predict 10/10 WI_3 day 10\n",
257 | "[8 -> 14] predict 10/10 WI_3 day 11\n",
258 | "[8 -> 14] predict 10/10 WI_3 day 12\n",
259 | "[8 -> 14] predict 10/10 WI_3 day 13\n",
260 | "[8 -> 14] predict 10/10 WI_3 day 14\n",
261 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_CA_1_21.bin\n",
262 | "[15 -> 21] predict 1/10 CA_1 day 15\n",
263 | "[15 -> 21] predict 1/10 CA_1 day 16\n",
264 | "[15 -> 21] predict 1/10 CA_1 day 17\n",
265 | "[15 -> 21] predict 1/10 CA_1 day 18\n",
266 | "[15 -> 21] predict 1/10 CA_1 day 19\n",
267 | "[15 -> 21] predict 1/10 CA_1 day 20\n",
268 | "[15 -> 21] predict 1/10 CA_1 day 21\n",
269 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_CA_2_21.bin\n",
270 | "[15 -> 21] predict 2/10 CA_2 day 15\n",
271 | "[15 -> 21] predict 2/10 CA_2 day 16\n",
272 | "[15 -> 21] predict 2/10 CA_2 day 17\n",
273 | "[15 -> 21] predict 2/10 CA_2 day 18\n",
274 | "[15 -> 21] predict 2/10 CA_2 day 19\n",
275 | "[15 -> 21] predict 2/10 CA_2 day 20\n",
276 | "[15 -> 21] predict 2/10 CA_2 day 21\n",
277 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_CA_3_21.bin\n",
278 | "[15 -> 21] predict 3/10 CA_3 day 15\n",
279 | "[15 -> 21] predict 3/10 CA_3 day 16\n",
280 | "[15 -> 21] predict 3/10 CA_3 day 17\n",
281 | "[15 -> 21] predict 3/10 CA_3 day 18\n",
282 | "[15 -> 21] predict 3/10 CA_3 day 19\n",
283 | "[15 -> 21] predict 3/10 CA_3 day 20\n",
284 | "[15 -> 21] predict 3/10 CA_3 day 21\n",
285 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_CA_4_21.bin\n",
286 | "[15 -> 21] predict 4/10 CA_4 day 15\n",
287 | "[15 -> 21] predict 4/10 CA_4 day 16\n",
288 | "[15 -> 21] predict 4/10 CA_4 day 17\n",
289 | "[15 -> 21] predict 4/10 CA_4 day 18\n",
290 | "[15 -> 21] predict 4/10 CA_4 day 19\n",
291 | "[15 -> 21] predict 4/10 CA_4 day 20\n",
292 | "[15 -> 21] predict 4/10 CA_4 day 21\n",
293 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_TX_1_21.bin\n",
294 | "[15 -> 21] predict 5/10 TX_1 day 15\n",
295 | "[15 -> 21] predict 5/10 TX_1 day 16\n",
296 | "[15 -> 21] predict 5/10 TX_1 day 17\n",
297 | "[15 -> 21] predict 5/10 TX_1 day 18\n",
298 | "[15 -> 21] predict 5/10 TX_1 day 19\n",
299 | "[15 -> 21] predict 5/10 TX_1 day 20\n",
300 | "[15 -> 21] predict 5/10 TX_1 day 21\n",
301 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_TX_2_21.bin\n",
302 | "[15 -> 21] predict 6/10 TX_2 day 15\n",
303 | "[15 -> 21] predict 6/10 TX_2 day 16\n",
304 | "[15 -> 21] predict 6/10 TX_2 day 17\n",
305 | "[15 -> 21] predict 6/10 TX_2 day 18\n",
306 | "[15 -> 21] predict 6/10 TX_2 day 19\n",
307 | "[15 -> 21] predict 6/10 TX_2 day 20\n",
308 | "[15 -> 21] predict 6/10 TX_2 day 21\n",
309 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_TX_3_21.bin\n",
310 | "[15 -> 21] predict 7/10 TX_3 day 15\n",
311 | "[15 -> 21] predict 7/10 TX_3 day 16\n",
312 | "[15 -> 21] predict 7/10 TX_3 day 17\n",
313 | "[15 -> 21] predict 7/10 TX_3 day 18\n",
314 | "[15 -> 21] predict 7/10 TX_3 day 19\n",
315 | "[15 -> 21] predict 7/10 TX_3 day 20\n",
316 | "[15 -> 21] predict 7/10 TX_3 day 21\n",
317 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_WI_1_21.bin\n",
318 | "[15 -> 21] predict 8/10 WI_1 day 15\n",
319 | "[15 -> 21] predict 8/10 WI_1 day 16\n",
320 | "[15 -> 21] predict 8/10 WI_1 day 17\n",
321 | "[15 -> 21] predict 8/10 WI_1 day 18\n",
322 | "[15 -> 21] predict 8/10 WI_1 day 19\n",
323 | "[15 -> 21] predict 8/10 WI_1 day 20\n",
324 | "[15 -> 21] predict 8/10 WI_1 day 21\n",
325 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_WI_2_21.bin\n",
326 | "[15 -> 21] predict 9/10 WI_2 day 15\n",
327 | "[15 -> 21] predict 9/10 WI_2 day 16\n",
328 | "[15 -> 21] predict 9/10 WI_2 day 17\n",
329 | "[15 -> 21] predict 9/10 WI_2 day 18\n",
330 | "[15 -> 21] predict 9/10 WI_2 day 19\n",
331 | "[15 -> 21] predict 9/10 WI_2 day 20\n",
332 | "[15 -> 21] predict 9/10 WI_2 day 21\n",
333 | "loading ../input/m5-train-day-1941-horizon-21/lgb_model_WI_3_21.bin\n",
334 | "[15 -> 21] predict 10/10 WI_3 day 15\n",
335 | "[15 -> 21] predict 10/10 WI_3 day 16\n",
336 | "[15 -> 21] predict 10/10 WI_3 day 17\n",
337 | "[15 -> 21] predict 10/10 WI_3 day 18\n",
338 | "[15 -> 21] predict 10/10 WI_3 day 19\n",
339 | "[15 -> 21] predict 10/10 WI_3 day 20\n",
340 | "[15 -> 21] predict 10/10 WI_3 day 21\n",
341 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_CA_1_28.bin\n",
342 | "[22 -> 28] predict 1/10 CA_1 day 22\n",
343 | "[22 -> 28] predict 1/10 CA_1 day 23\n",
344 | "[22 -> 28] predict 1/10 CA_1 day 24\n",
345 | "[22 -> 28] predict 1/10 CA_1 day 25\n",
346 | "[22 -> 28] predict 1/10 CA_1 day 26\n",
347 | "[22 -> 28] predict 1/10 CA_1 day 27\n",
348 | "[22 -> 28] predict 1/10 CA_1 day 28\n",
349 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_CA_2_28.bin\n",
350 | "[22 -> 28] predict 2/10 CA_2 day 22\n",
351 | "[22 -> 28] predict 2/10 CA_2 day 23\n",
352 | "[22 -> 28] predict 2/10 CA_2 day 24\n",
353 | "[22 -> 28] predict 2/10 CA_2 day 25\n",
354 | "[22 -> 28] predict 2/10 CA_2 day 26\n",
355 | "[22 -> 28] predict 2/10 CA_2 day 27\n",
356 | "[22 -> 28] predict 2/10 CA_2 day 28\n",
357 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_CA_3_28.bin\n",
358 | "[22 -> 28] predict 3/10 CA_3 day 22\n",
359 | "[22 -> 28] predict 3/10 CA_3 day 23\n",
360 | "[22 -> 28] predict 3/10 CA_3 day 24\n",
361 | "[22 -> 28] predict 3/10 CA_3 day 25\n",
362 | "[22 -> 28] predict 3/10 CA_3 day 26\n",
363 | "[22 -> 28] predict 3/10 CA_3 day 27\n",
364 | "[22 -> 28] predict 3/10 CA_3 day 28\n",
365 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_CA_4_28.bin\n",
366 | "[22 -> 28] predict 4/10 CA_4 day 22\n",
367 | "[22 -> 28] predict 4/10 CA_4 day 23\n",
368 | "[22 -> 28] predict 4/10 CA_4 day 24\n",
369 | "[22 -> 28] predict 4/10 CA_4 day 25\n",
370 | "[22 -> 28] predict 4/10 CA_4 day 26\n",
371 | "[22 -> 28] predict 4/10 CA_4 day 27\n",
372 | "[22 -> 28] predict 4/10 CA_4 day 28\n",
373 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_TX_1_28.bin\n",
374 | "[22 -> 28] predict 5/10 TX_1 day 22\n",
375 | "[22 -> 28] predict 5/10 TX_1 day 23\n",
376 | "[22 -> 28] predict 5/10 TX_1 day 24\n",
377 | "[22 -> 28] predict 5/10 TX_1 day 25\n",
378 | "[22 -> 28] predict 5/10 TX_1 day 26\n",
379 | "[22 -> 28] predict 5/10 TX_1 day 27\n",
380 | "[22 -> 28] predict 5/10 TX_1 day 28\n",
381 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_TX_2_28.bin\n",
382 | "[22 -> 28] predict 6/10 TX_2 day 22\n",
383 | "[22 -> 28] predict 6/10 TX_2 day 23\n",
384 | "[22 -> 28] predict 6/10 TX_2 day 24\n",
385 | "[22 -> 28] predict 6/10 TX_2 day 25\n",
386 | "[22 -> 28] predict 6/10 TX_2 day 26\n",
387 | "[22 -> 28] predict 6/10 TX_2 day 27\n",
388 | "[22 -> 28] predict 6/10 TX_2 day 28\n",
389 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_TX_3_28.bin\n",
390 | "[22 -> 28] predict 7/10 TX_3 day 22\n",
391 | "[22 -> 28] predict 7/10 TX_3 day 23\n",
392 | "[22 -> 28] predict 7/10 TX_3 day 24\n",
393 | "[22 -> 28] predict 7/10 TX_3 day 25\n",
394 | "[22 -> 28] predict 7/10 TX_3 day 26\n",
395 | "[22 -> 28] predict 7/10 TX_3 day 27\n",
396 | "[22 -> 28] predict 7/10 TX_3 day 28\n",
397 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_WI_1_28.bin\n",
398 | "[22 -> 28] predict 8/10 WI_1 day 22\n",
399 | "[22 -> 28] predict 8/10 WI_1 day 23\n",
400 | "[22 -> 28] predict 8/10 WI_1 day 24\n",
401 | "[22 -> 28] predict 8/10 WI_1 day 25\n",
402 | "[22 -> 28] predict 8/10 WI_1 day 26\n",
403 | "[22 -> 28] predict 8/10 WI_1 day 27\n",
404 | "[22 -> 28] predict 8/10 WI_1 day 28\n",
405 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_WI_2_28.bin\n",
406 | "[22 -> 28] predict 9/10 WI_2 day 22\n",
407 | "[22 -> 28] predict 9/10 WI_2 day 23\n",
408 | "[22 -> 28] predict 9/10 WI_2 day 24\n",
409 | "[22 -> 28] predict 9/10 WI_2 day 25\n",
410 | "[22 -> 28] predict 9/10 WI_2 day 26\n",
411 | "[22 -> 28] predict 9/10 WI_2 day 27\n",
412 | "[22 -> 28] predict 9/10 WI_2 day 28\n",
413 | "loading ../input/m5-train-day-1941-horizon-28/lgb_model_WI_3_28.bin\n",
414 | "[22 -> 28] predict 10/10 WI_3 day 22\n",
415 | "[22 -> 28] predict 10/10 WI_3 day 23\n",
416 | "[22 -> 28] predict 10/10 WI_3 day 24\n",
417 | "[22 -> 28] predict 10/10 WI_3 day 25\n",
418 | "[22 -> 28] predict 10/10 WI_3 day 26\n",
419 | "[22 -> 28] predict 10/10 WI_3 day 27\n",
420 | "[22 -> 28] predict 10/10 WI_3 day 28\n"
421 | ]
422 | }
423 | ],
424 | "source": [
425 | "store_id_set_list = ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n",
426 | "end_train_day_x_list = [1941]\n",
427 | "prediction_horizon_list = [7, 14, 21, 28]\n",
428 | "\n",
429 | "pred_v_all_df = list()\n",
430 | "\n",
431 | "for end_train_day_x in end_train_day_x_list:\n",
432 | " previous_prediction_horizon = 0\n",
433 | " for prediction_horizon in prediction_horizon_list:\n",
434 | " notebook_name = f\"../input/m5-train-day-{end_train_day_x}-horizon-{prediction_horizon}\"\n",
435 | "\n",
436 | " pred_v_df = pd.DataFrame()\n",
437 | " \n",
438 | " for store_index, store_id in enumerate(store_id_set_list):\n",
439 | " \n",
440 | " model_path = str(f'{notebook_name}/lgb_model_{store_id}_{prediction_horizon}.bin')\n",
441 | " print(f'loading {model_path}')\n",
442 | " estimator = pickle.load(open(model_path, 'rb'))\n",
443 | " base_test = pd.read_feather(f\"{notebook_name}/test_{store_id}_{prediction_horizon}.feather\")\n",
444 | " enable_features = [col for col in base_test.columns if col not in ['id', 'd', 'sales']]\n",
445 | " \n",
446 | " for predict_day in range(previous_prediction_horizon + 1, prediction_horizon + 1):\n",
447 | " print('[{3} -> {4}] predict {0}/{1} {2} day {5}'.format(\n",
448 | " store_index + 1, len(store_id_set_list), store_id,\n",
449 | " previous_prediction_horizon + 1, prediction_horizon, predict_day))\n",
450 | " mask = base_test['d'] == (end_train_day_x + predict_day)\n",
451 | " base_test.loc[mask, 'sales'] = estimator.predict(base_test[mask][enable_features])\n",
452 | " \n",
453 | " temp_v_df = base_test[\n",
454 | " (base_test['d'] >= end_train_day_x + previous_prediction_horizon + 1) &\n",
455 | " (base_test['d'] < end_train_day_x + prediction_horizon + 1)\n",
456 | " ][['id', 'd', 'sales']]\n",
457 | " \n",
458 | " if len(pred_v_df)!=0:\n",
459 | " pred_v_df = pd.concat([pred_v_df, temp_v_df])\n",
460 | " else:\n",
461 | " pred_v_df = temp_v_df.copy()\n",
462 | " \n",
463 | " del(temp_v_df)\n",
464 | " gc.collect()\n",
465 | " \n",
466 | " previous_prediction_horizon = prediction_horizon\n",
467 | " pred_v_all_df.append(pred_v_df)\n",
468 | " \n",
469 | "pred_v_all_df = pd.concat(pred_v_all_df)"
470 | ]
471 | },
472 | {
473 | "cell_type": "code",
474 | "execution_count": 3,
475 | "id": "a8419e0a",
476 | "metadata": {
477 | "execution": {
478 | "iopub.execute_input": "2022-08-10T06:55:04.233734Z",
479 | "iopub.status.busy": "2022-08-10T06:55:04.232986Z",
480 | "iopub.status.idle": "2022-08-10T06:55:04.426430Z",
481 | "shell.execute_reply": "2022-08-10T06:55:04.424949Z"
482 | },
483 | "papermill": {
484 | "duration": 0.218894,
485 | "end_time": "2022-08-10T06:55:04.429671",
486 | "exception": false,
487 | "start_time": "2022-08-10T06:55:04.210777",
488 | "status": "completed"
489 | },
490 | "tags": []
491 | },
492 | "outputs": [],
493 | "source": [
494 | "submission = pd.read_csv(\"../input/m5-forecasting-accuracy/sample_submission.csv\")"
495 | ]
496 | },
497 | {
498 | "cell_type": "code",
499 | "execution_count": 4,
500 | "id": "166369dd",
501 | "metadata": {
502 | "execution": {
503 | "iopub.execute_input": "2022-08-10T06:55:04.474091Z",
504 | "iopub.status.busy": "2022-08-10T06:55:04.473366Z",
505 | "iopub.status.idle": "2022-08-10T06:55:04.855454Z",
506 | "shell.execute_reply": "2022-08-10T06:55:04.854243Z"
507 | },
508 | "papermill": {
509 | "duration": 0.407073,
510 | "end_time": "2022-08-10T06:55:04.858388",
511 | "exception": false,
512 | "start_time": "2022-08-10T06:55:04.451315",
513 | "status": "completed"
514 | },
515 | "tags": []
516 | },
517 | "outputs": [],
518 | "source": [
519 | "pred_v_all_df.d = pred_v_all_df.d - end_train_day_x_list\n",
520 | "pred_h_all_df = pred_v_all_df.pivot(index='id', columns='d', values='sales')\n",
521 | "pred_h_all_df = pred_h_all_df.reset_index()\n",
522 | "pred_h_all_df.columns = submission.columns"
523 | ]
524 | },
525 | {
526 | "cell_type": "code",
527 | "execution_count": 5,
528 | "id": "afd01d75",
529 | "metadata": {
530 | "execution": {
531 | "iopub.execute_input": "2022-08-10T06:55:04.904846Z",
532 | "iopub.status.busy": "2022-08-10T06:55:04.903588Z",
533 | "iopub.status.idle": "2022-08-10T06:55:06.254339Z",
534 | "shell.execute_reply": "2022-08-10T06:55:06.253404Z"
535 | },
536 | "papermill": {
537 | "duration": 1.376611,
538 | "end_time": "2022-08-10T06:55:06.256963",
539 | "exception": false,
540 | "start_time": "2022-08-10T06:55:04.880352",
541 | "status": "completed"
542 | },
543 | "tags": []
544 | },
545 | "outputs": [],
546 | "source": [
547 | "submission = submission[['id']].merge(pred_h_all_df, on=['id'], how='left').fillna(0)\n",
548 | "submission.to_csv(\"m5_predictions.csv\", index=False)"
549 | ]
550 | }
551 | ],
552 | "metadata": {
553 | "kernelspec": {
554 | "display_name": "Python 3",
555 | "language": "python",
556 | "name": "python3"
557 | },
558 | "language_info": {
559 | "codemirror_mode": {
560 | "name": "ipython",
561 | "version": 3
562 | },
563 | "file_extension": ".py",
564 | "mimetype": "text/x-python",
565 | "name": "python",
566 | "nbconvert_exporter": "python",
567 | "pygments_lexer": "ipython3",
568 | "version": "3.7.12"
569 | },
570 | "papermill": {
571 | "default_parameters": {},
572 | "duration": 257.863222,
573 | "end_time": "2022-08-10T06:55:07.102588",
574 | "environment_variables": {},
575 | "exception": null,
576 | "input_path": "__notebook__.ipynb",
577 | "output_path": "__notebook__.ipynb",
578 | "parameters": {},
579 | "start_time": "2022-08-10T06:50:49.239366",
580 | "version": "2.3.4"
581 | }
582 | },
583 | "nbformat": 4,
584 | "nbformat_minor": 5
585 | }
586 |
--------------------------------------------------------------------------------
/chapter_02/m5-predict-public-leaderboard.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "eaaa021d",
7 | "metadata": {
8 | "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
9 | "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
10 | "execution": {
11 | "iopub.execute_input": "2022-10-03T10:55:39.373904Z",
12 | "iopub.status.busy": "2022-10-03T10:55:39.373362Z",
13 | "iopub.status.idle": "2022-10-03T10:55:41.440128Z",
14 | "shell.execute_reply": "2022-10-03T10:55:41.438903Z"
15 | },
16 | "papermill": {
17 | "duration": 2.074766,
18 | "end_time": "2022-10-03T10:55:41.443069",
19 | "exception": false,
20 | "start_time": "2022-10-03T10:55:39.368303",
21 | "status": "completed"
22 | },
23 | "tags": []
24 | },
25 | "outputs": [
26 | {
27 | "data": {
28 | "text/html": [
29 | "\n"
50 | ],
51 | "text/plain": [
52 | ""
53 | ]
54 | },
55 | "metadata": {},
56 | "output_type": "display_data"
57 | }
58 | ],
59 | "source": [
60 | "import numpy as np\n",
61 | "import pandas as pd\n",
62 | "import os\n",
63 | "import random\n",
64 | "import math\n",
65 | "from decimal import Decimal as dec\n",
66 | "import datetime\n",
67 | "import time\n",
68 | "import gc\n",
69 | "import lightgbm as lgb\n",
70 | "import pickle\n",
71 | "\n",
72 | "import warnings\n",
73 | "warnings.filterwarnings(\"ignore\", category=UserWarning)"
74 | ]
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": 2,
79 | "id": "b1a087a6",
80 | "metadata": {
81 | "execution": {
82 | "iopub.execute_input": "2022-10-03T10:55:41.450185Z",
83 | "iopub.status.busy": "2022-10-03T10:55:41.449812Z",
84 | "iopub.status.idle": "2022-10-03T10:59:56.162634Z",
85 | "shell.execute_reply": "2022-10-03T10:59:56.161295Z"
86 | },
87 | "papermill": {
88 | "duration": 254.719984,
89 | "end_time": "2022-10-03T10:59:56.165886",
90 | "exception": false,
91 | "start_time": "2022-10-03T10:55:41.445902",
92 | "status": "completed"
93 | },
94 | "tags": []
95 | },
96 | "outputs": [
97 | {
98 | "name": "stdout",
99 | "output_type": "stream",
100 | "text": [
101 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_CA_1_7.bin\n",
102 | "[1 -> 7] predict 1/10 CA_1 day 1\n",
103 | "[1 -> 7] predict 1/10 CA_1 day 2\n",
104 | "[1 -> 7] predict 1/10 CA_1 day 3\n",
105 | "[1 -> 7] predict 1/10 CA_1 day 4\n",
106 | "[1 -> 7] predict 1/10 CA_1 day 5\n",
107 | "[1 -> 7] predict 1/10 CA_1 day 6\n",
108 | "[1 -> 7] predict 1/10 CA_1 day 7\n",
109 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_CA_2_7.bin\n",
110 | "[1 -> 7] predict 2/10 CA_2 day 1\n",
111 | "[1 -> 7] predict 2/10 CA_2 day 2\n",
112 | "[1 -> 7] predict 2/10 CA_2 day 3\n",
113 | "[1 -> 7] predict 2/10 CA_2 day 4\n",
114 | "[1 -> 7] predict 2/10 CA_2 day 5\n",
115 | "[1 -> 7] predict 2/10 CA_2 day 6\n",
116 | "[1 -> 7] predict 2/10 CA_2 day 7\n",
117 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_CA_3_7.bin\n",
118 | "[1 -> 7] predict 3/10 CA_3 day 1\n",
119 | "[1 -> 7] predict 3/10 CA_3 day 2\n",
120 | "[1 -> 7] predict 3/10 CA_3 day 3\n",
121 | "[1 -> 7] predict 3/10 CA_3 day 4\n",
122 | "[1 -> 7] predict 3/10 CA_3 day 5\n",
123 | "[1 -> 7] predict 3/10 CA_3 day 6\n",
124 | "[1 -> 7] predict 3/10 CA_3 day 7\n",
125 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_CA_4_7.bin\n",
126 | "[1 -> 7] predict 4/10 CA_4 day 1\n",
127 | "[1 -> 7] predict 4/10 CA_4 day 2\n",
128 | "[1 -> 7] predict 4/10 CA_4 day 3\n",
129 | "[1 -> 7] predict 4/10 CA_4 day 4\n",
130 | "[1 -> 7] predict 4/10 CA_4 day 5\n",
131 | "[1 -> 7] predict 4/10 CA_4 day 6\n",
132 | "[1 -> 7] predict 4/10 CA_4 day 7\n",
133 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_TX_1_7.bin\n",
134 | "[1 -> 7] predict 5/10 TX_1 day 1\n",
135 | "[1 -> 7] predict 5/10 TX_1 day 2\n",
136 | "[1 -> 7] predict 5/10 TX_1 day 3\n",
137 | "[1 -> 7] predict 5/10 TX_1 day 4\n",
138 | "[1 -> 7] predict 5/10 TX_1 day 5\n",
139 | "[1 -> 7] predict 5/10 TX_1 day 6\n",
140 | "[1 -> 7] predict 5/10 TX_1 day 7\n",
141 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_TX_2_7.bin\n",
142 | "[1 -> 7] predict 6/10 TX_2 day 1\n",
143 | "[1 -> 7] predict 6/10 TX_2 day 2\n",
144 | "[1 -> 7] predict 6/10 TX_2 day 3\n",
145 | "[1 -> 7] predict 6/10 TX_2 day 4\n",
146 | "[1 -> 7] predict 6/10 TX_2 day 5\n",
147 | "[1 -> 7] predict 6/10 TX_2 day 6\n",
148 | "[1 -> 7] predict 6/10 TX_2 day 7\n",
149 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_TX_3_7.bin\n",
150 | "[1 -> 7] predict 7/10 TX_3 day 1\n",
151 | "[1 -> 7] predict 7/10 TX_3 day 2\n",
152 | "[1 -> 7] predict 7/10 TX_3 day 3\n",
153 | "[1 -> 7] predict 7/10 TX_3 day 4\n",
154 | "[1 -> 7] predict 7/10 TX_3 day 5\n",
155 | "[1 -> 7] predict 7/10 TX_3 day 6\n",
156 | "[1 -> 7] predict 7/10 TX_3 day 7\n",
157 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_WI_1_7.bin\n",
158 | "[1 -> 7] predict 8/10 WI_1 day 1\n",
159 | "[1 -> 7] predict 8/10 WI_1 day 2\n",
160 | "[1 -> 7] predict 8/10 WI_1 day 3\n",
161 | "[1 -> 7] predict 8/10 WI_1 day 4\n",
162 | "[1 -> 7] predict 8/10 WI_1 day 5\n",
163 | "[1 -> 7] predict 8/10 WI_1 day 6\n",
164 | "[1 -> 7] predict 8/10 WI_1 day 7\n",
165 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_WI_2_7.bin\n",
166 | "[1 -> 7] predict 9/10 WI_2 day 1\n",
167 | "[1 -> 7] predict 9/10 WI_2 day 2\n",
168 | "[1 -> 7] predict 9/10 WI_2 day 3\n",
169 | "[1 -> 7] predict 9/10 WI_2 day 4\n",
170 | "[1 -> 7] predict 9/10 WI_2 day 5\n",
171 | "[1 -> 7] predict 9/10 WI_2 day 6\n",
172 | "[1 -> 7] predict 9/10 WI_2 day 7\n",
173 | "loading ../input/m5-train-day-1913-horizon-7/lgb_model_WI_3_7.bin\n",
174 | "[1 -> 7] predict 10/10 WI_3 day 1\n",
175 | "[1 -> 7] predict 10/10 WI_3 day 2\n",
176 | "[1 -> 7] predict 10/10 WI_3 day 3\n",
177 | "[1 -> 7] predict 10/10 WI_3 day 4\n",
178 | "[1 -> 7] predict 10/10 WI_3 day 5\n",
179 | "[1 -> 7] predict 10/10 WI_3 day 6\n",
180 | "[1 -> 7] predict 10/10 WI_3 day 7\n",
181 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_CA_1_14.bin\n",
182 | "[8 -> 14] predict 1/10 CA_1 day 8\n",
183 | "[8 -> 14] predict 1/10 CA_1 day 9\n",
184 | "[8 -> 14] predict 1/10 CA_1 day 10\n",
185 | "[8 -> 14] predict 1/10 CA_1 day 11\n",
186 | "[8 -> 14] predict 1/10 CA_1 day 12\n",
187 | "[8 -> 14] predict 1/10 CA_1 day 13\n",
188 | "[8 -> 14] predict 1/10 CA_1 day 14\n",
189 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_CA_2_14.bin\n",
190 | "[8 -> 14] predict 2/10 CA_2 day 8\n",
191 | "[8 -> 14] predict 2/10 CA_2 day 9\n",
192 | "[8 -> 14] predict 2/10 CA_2 day 10\n",
193 | "[8 -> 14] predict 2/10 CA_2 day 11\n",
194 | "[8 -> 14] predict 2/10 CA_2 day 12\n",
195 | "[8 -> 14] predict 2/10 CA_2 day 13\n",
196 | "[8 -> 14] predict 2/10 CA_2 day 14\n",
197 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_CA_3_14.bin\n",
198 | "[8 -> 14] predict 3/10 CA_3 day 8\n",
199 | "[8 -> 14] predict 3/10 CA_3 day 9\n",
200 | "[8 -> 14] predict 3/10 CA_3 day 10\n",
201 | "[8 -> 14] predict 3/10 CA_3 day 11\n",
202 | "[8 -> 14] predict 3/10 CA_3 day 12\n",
203 | "[8 -> 14] predict 3/10 CA_3 day 13\n",
204 | "[8 -> 14] predict 3/10 CA_3 day 14\n",
205 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_CA_4_14.bin\n",
206 | "[8 -> 14] predict 4/10 CA_4 day 8\n",
207 | "[8 -> 14] predict 4/10 CA_4 day 9\n",
208 | "[8 -> 14] predict 4/10 CA_4 day 10\n",
209 | "[8 -> 14] predict 4/10 CA_4 day 11\n",
210 | "[8 -> 14] predict 4/10 CA_4 day 12\n",
211 | "[8 -> 14] predict 4/10 CA_4 day 13\n",
212 | "[8 -> 14] predict 4/10 CA_4 day 14\n",
213 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_TX_1_14.bin\n",
214 | "[8 -> 14] predict 5/10 TX_1 day 8\n",
215 | "[8 -> 14] predict 5/10 TX_1 day 9\n",
216 | "[8 -> 14] predict 5/10 TX_1 day 10\n",
217 | "[8 -> 14] predict 5/10 TX_1 day 11\n",
218 | "[8 -> 14] predict 5/10 TX_1 day 12\n",
219 | "[8 -> 14] predict 5/10 TX_1 day 13\n",
220 | "[8 -> 14] predict 5/10 TX_1 day 14\n",
221 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_TX_2_14.bin\n",
222 | "[8 -> 14] predict 6/10 TX_2 day 8\n",
223 | "[8 -> 14] predict 6/10 TX_2 day 9\n",
224 | "[8 -> 14] predict 6/10 TX_2 day 10\n",
225 | "[8 -> 14] predict 6/10 TX_2 day 11\n",
226 | "[8 -> 14] predict 6/10 TX_2 day 12\n",
227 | "[8 -> 14] predict 6/10 TX_2 day 13\n",
228 | "[8 -> 14] predict 6/10 TX_2 day 14\n",
229 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_TX_3_14.bin\n",
230 | "[8 -> 14] predict 7/10 TX_3 day 8\n",
231 | "[8 -> 14] predict 7/10 TX_3 day 9\n",
232 | "[8 -> 14] predict 7/10 TX_3 day 10\n",
233 | "[8 -> 14] predict 7/10 TX_3 day 11\n",
234 | "[8 -> 14] predict 7/10 TX_3 day 12\n",
235 | "[8 -> 14] predict 7/10 TX_3 day 13\n",
236 | "[8 -> 14] predict 7/10 TX_3 day 14\n",
237 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_WI_1_14.bin\n",
238 | "[8 -> 14] predict 8/10 WI_1 day 8\n",
239 | "[8 -> 14] predict 8/10 WI_1 day 9\n",
240 | "[8 -> 14] predict 8/10 WI_1 day 10\n",
241 | "[8 -> 14] predict 8/10 WI_1 day 11\n",
242 | "[8 -> 14] predict 8/10 WI_1 day 12\n",
243 | "[8 -> 14] predict 8/10 WI_1 day 13\n",
244 | "[8 -> 14] predict 8/10 WI_1 day 14\n",
245 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_WI_2_14.bin\n",
246 | "[8 -> 14] predict 9/10 WI_2 day 8\n",
247 | "[8 -> 14] predict 9/10 WI_2 day 9\n",
248 | "[8 -> 14] predict 9/10 WI_2 day 10\n",
249 | "[8 -> 14] predict 9/10 WI_2 day 11\n",
250 | "[8 -> 14] predict 9/10 WI_2 day 12\n",
251 | "[8 -> 14] predict 9/10 WI_2 day 13\n",
252 | "[8 -> 14] predict 9/10 WI_2 day 14\n",
253 | "loading ../input/m5-train-day-1913-horizon-14/lgb_model_WI_3_14.bin\n",
254 | "[8 -> 14] predict 10/10 WI_3 day 8\n",
255 | "[8 -> 14] predict 10/10 WI_3 day 9\n",
256 | "[8 -> 14] predict 10/10 WI_3 day 10\n",
257 | "[8 -> 14] predict 10/10 WI_3 day 11\n",
258 | "[8 -> 14] predict 10/10 WI_3 day 12\n",
259 | "[8 -> 14] predict 10/10 WI_3 day 13\n",
260 | "[8 -> 14] predict 10/10 WI_3 day 14\n",
261 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_CA_1_21.bin\n",
262 | "[15 -> 21] predict 1/10 CA_1 day 15\n",
263 | "[15 -> 21] predict 1/10 CA_1 day 16\n",
264 | "[15 -> 21] predict 1/10 CA_1 day 17\n",
265 | "[15 -> 21] predict 1/10 CA_1 day 18\n",
266 | "[15 -> 21] predict 1/10 CA_1 day 19\n",
267 | "[15 -> 21] predict 1/10 CA_1 day 20\n",
268 | "[15 -> 21] predict 1/10 CA_1 day 21\n",
269 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_CA_2_21.bin\n",
270 | "[15 -> 21] predict 2/10 CA_2 day 15\n",
271 | "[15 -> 21] predict 2/10 CA_2 day 16\n",
272 | "[15 -> 21] predict 2/10 CA_2 day 17\n",
273 | "[15 -> 21] predict 2/10 CA_2 day 18\n",
274 | "[15 -> 21] predict 2/10 CA_2 day 19\n",
275 | "[15 -> 21] predict 2/10 CA_2 day 20\n",
276 | "[15 -> 21] predict 2/10 CA_2 day 21\n",
277 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_CA_3_21.bin\n",
278 | "[15 -> 21] predict 3/10 CA_3 day 15\n",
279 | "[15 -> 21] predict 3/10 CA_3 day 16\n",
280 | "[15 -> 21] predict 3/10 CA_3 day 17\n",
281 | "[15 -> 21] predict 3/10 CA_3 day 18\n",
282 | "[15 -> 21] predict 3/10 CA_3 day 19\n",
283 | "[15 -> 21] predict 3/10 CA_3 day 20\n",
284 | "[15 -> 21] predict 3/10 CA_3 day 21\n",
285 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_CA_4_21.bin\n",
286 | "[15 -> 21] predict 4/10 CA_4 day 15\n",
287 | "[15 -> 21] predict 4/10 CA_4 day 16\n",
288 | "[15 -> 21] predict 4/10 CA_4 day 17\n",
289 | "[15 -> 21] predict 4/10 CA_4 day 18\n",
290 | "[15 -> 21] predict 4/10 CA_4 day 19\n",
291 | "[15 -> 21] predict 4/10 CA_4 day 20\n",
292 | "[15 -> 21] predict 4/10 CA_4 day 21\n",
293 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_TX_1_21.bin\n",
294 | "[15 -> 21] predict 5/10 TX_1 day 15\n",
295 | "[15 -> 21] predict 5/10 TX_1 day 16\n",
296 | "[15 -> 21] predict 5/10 TX_1 day 17\n",
297 | "[15 -> 21] predict 5/10 TX_1 day 18\n",
298 | "[15 -> 21] predict 5/10 TX_1 day 19\n",
299 | "[15 -> 21] predict 5/10 TX_1 day 20\n",
300 | "[15 -> 21] predict 5/10 TX_1 day 21\n",
301 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_TX_2_21.bin\n",
302 | "[15 -> 21] predict 6/10 TX_2 day 15\n",
303 | "[15 -> 21] predict 6/10 TX_2 day 16\n",
304 | "[15 -> 21] predict 6/10 TX_2 day 17\n",
305 | "[15 -> 21] predict 6/10 TX_2 day 18\n",
306 | "[15 -> 21] predict 6/10 TX_2 day 19\n",
307 | "[15 -> 21] predict 6/10 TX_2 day 20\n",
308 | "[15 -> 21] predict 6/10 TX_2 day 21\n",
309 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_TX_3_21.bin\n",
310 | "[15 -> 21] predict 7/10 TX_3 day 15\n",
311 | "[15 -> 21] predict 7/10 TX_3 day 16\n",
312 | "[15 -> 21] predict 7/10 TX_3 day 17\n",
313 | "[15 -> 21] predict 7/10 TX_3 day 18\n",
314 | "[15 -> 21] predict 7/10 TX_3 day 19\n",
315 | "[15 -> 21] predict 7/10 TX_3 day 20\n",
316 | "[15 -> 21] predict 7/10 TX_3 day 21\n",
317 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_WI_1_21.bin\n",
318 | "[15 -> 21] predict 8/10 WI_1 day 15\n",
319 | "[15 -> 21] predict 8/10 WI_1 day 16\n",
320 | "[15 -> 21] predict 8/10 WI_1 day 17\n",
321 | "[15 -> 21] predict 8/10 WI_1 day 18\n",
322 | "[15 -> 21] predict 8/10 WI_1 day 19\n",
323 | "[15 -> 21] predict 8/10 WI_1 day 20\n",
324 | "[15 -> 21] predict 8/10 WI_1 day 21\n",
325 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_WI_2_21.bin\n",
326 | "[15 -> 21] predict 9/10 WI_2 day 15\n",
327 | "[15 -> 21] predict 9/10 WI_2 day 16\n",
328 | "[15 -> 21] predict 9/10 WI_2 day 17\n",
329 | "[15 -> 21] predict 9/10 WI_2 day 18\n",
330 | "[15 -> 21] predict 9/10 WI_2 day 19\n",
331 | "[15 -> 21] predict 9/10 WI_2 day 20\n",
332 | "[15 -> 21] predict 9/10 WI_2 day 21\n",
333 | "loading ../input/m5-train-day-1913-horizon-21/lgb_model_WI_3_21.bin\n",
334 | "[15 -> 21] predict 10/10 WI_3 day 15\n",
335 | "[15 -> 21] predict 10/10 WI_3 day 16\n",
336 | "[15 -> 21] predict 10/10 WI_3 day 17\n",
337 | "[15 -> 21] predict 10/10 WI_3 day 18\n",
338 | "[15 -> 21] predict 10/10 WI_3 day 19\n",
339 | "[15 -> 21] predict 10/10 WI_3 day 20\n",
340 | "[15 -> 21] predict 10/10 WI_3 day 21\n",
341 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_CA_1_28.bin\n",
342 | "[22 -> 28] predict 1/10 CA_1 day 22\n",
343 | "[22 -> 28] predict 1/10 CA_1 day 23\n",
344 | "[22 -> 28] predict 1/10 CA_1 day 24\n",
345 | "[22 -> 28] predict 1/10 CA_1 day 25\n",
346 | "[22 -> 28] predict 1/10 CA_1 day 26\n",
347 | "[22 -> 28] predict 1/10 CA_1 day 27\n",
348 | "[22 -> 28] predict 1/10 CA_1 day 28\n",
349 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_CA_2_28.bin\n",
350 | "[22 -> 28] predict 2/10 CA_2 day 22\n",
351 | "[22 -> 28] predict 2/10 CA_2 day 23\n",
352 | "[22 -> 28] predict 2/10 CA_2 day 24\n",
353 | "[22 -> 28] predict 2/10 CA_2 day 25\n",
354 | "[22 -> 28] predict 2/10 CA_2 day 26\n",
355 | "[22 -> 28] predict 2/10 CA_2 day 27\n",
356 | "[22 -> 28] predict 2/10 CA_2 day 28\n",
357 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_CA_3_28.bin\n",
358 | "[22 -> 28] predict 3/10 CA_3 day 22\n",
359 | "[22 -> 28] predict 3/10 CA_3 day 23\n",
360 | "[22 -> 28] predict 3/10 CA_3 day 24\n",
361 | "[22 -> 28] predict 3/10 CA_3 day 25\n",
362 | "[22 -> 28] predict 3/10 CA_3 day 26\n",
363 | "[22 -> 28] predict 3/10 CA_3 day 27\n",
364 | "[22 -> 28] predict 3/10 CA_3 day 28\n",
365 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_CA_4_28.bin\n",
366 | "[22 -> 28] predict 4/10 CA_4 day 22\n",
367 | "[22 -> 28] predict 4/10 CA_4 day 23\n",
368 | "[22 -> 28] predict 4/10 CA_4 day 24\n",
369 | "[22 -> 28] predict 4/10 CA_4 day 25\n",
370 | "[22 -> 28] predict 4/10 CA_4 day 26\n",
371 | "[22 -> 28] predict 4/10 CA_4 day 27\n",
372 | "[22 -> 28] predict 4/10 CA_4 day 28\n",
373 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_TX_1_28.bin\n",
374 | "[22 -> 28] predict 5/10 TX_1 day 22\n",
375 | "[22 -> 28] predict 5/10 TX_1 day 23\n",
376 | "[22 -> 28] predict 5/10 TX_1 day 24\n",
377 | "[22 -> 28] predict 5/10 TX_1 day 25\n",
378 | "[22 -> 28] predict 5/10 TX_1 day 26\n",
379 | "[22 -> 28] predict 5/10 TX_1 day 27\n",
380 | "[22 -> 28] predict 5/10 TX_1 day 28\n",
381 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_TX_2_28.bin\n",
382 | "[22 -> 28] predict 6/10 TX_2 day 22\n",
383 | "[22 -> 28] predict 6/10 TX_2 day 23\n",
384 | "[22 -> 28] predict 6/10 TX_2 day 24\n",
385 | "[22 -> 28] predict 6/10 TX_2 day 25\n",
386 | "[22 -> 28] predict 6/10 TX_2 day 26\n",
387 | "[22 -> 28] predict 6/10 TX_2 day 27\n",
388 | "[22 -> 28] predict 6/10 TX_2 day 28\n",
389 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_TX_3_28.bin\n",
390 | "[22 -> 28] predict 7/10 TX_3 day 22\n",
391 | "[22 -> 28] predict 7/10 TX_3 day 23\n",
392 | "[22 -> 28] predict 7/10 TX_3 day 24\n",
393 | "[22 -> 28] predict 7/10 TX_3 day 25\n",
394 | "[22 -> 28] predict 7/10 TX_3 day 26\n",
395 | "[22 -> 28] predict 7/10 TX_3 day 27\n",
396 | "[22 -> 28] predict 7/10 TX_3 day 28\n",
397 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_WI_1_28.bin\n",
398 | "[22 -> 28] predict 8/10 WI_1 day 22\n",
399 | "[22 -> 28] predict 8/10 WI_1 day 23\n",
400 | "[22 -> 28] predict 8/10 WI_1 day 24\n",
401 | "[22 -> 28] predict 8/10 WI_1 day 25\n",
402 | "[22 -> 28] predict 8/10 WI_1 day 26\n",
403 | "[22 -> 28] predict 8/10 WI_1 day 27\n",
404 | "[22 -> 28] predict 8/10 WI_1 day 28\n",
405 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_WI_2_28.bin\n",
406 | "[22 -> 28] predict 9/10 WI_2 day 22\n",
407 | "[22 -> 28] predict 9/10 WI_2 day 23\n",
408 | "[22 -> 28] predict 9/10 WI_2 day 24\n",
409 | "[22 -> 28] predict 9/10 WI_2 day 25\n",
410 | "[22 -> 28] predict 9/10 WI_2 day 26\n",
411 | "[22 -> 28] predict 9/10 WI_2 day 27\n",
412 | "[22 -> 28] predict 9/10 WI_2 day 28\n",
413 | "loading ../input/m5-train-day-1913-horizon-28/lgb_model_WI_3_28.bin\n",
414 | "[22 -> 28] predict 10/10 WI_3 day 22\n",
415 | "[22 -> 28] predict 10/10 WI_3 day 23\n",
416 | "[22 -> 28] predict 10/10 WI_3 day 24\n",
417 | "[22 -> 28] predict 10/10 WI_3 day 25\n",
418 | "[22 -> 28] predict 10/10 WI_3 day 26\n",
419 | "[22 -> 28] predict 10/10 WI_3 day 27\n",
420 | "[22 -> 28] predict 10/10 WI_3 day 28\n"
421 | ]
422 | }
423 | ],
424 | "source": [
425 | "store_id_set_list = ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n",
426 | "end_train_day_x_list = [1913]\n",
427 | "prediction_horizon_list = [7, 14, 21, 28]\n",
428 | "\n",
429 | "pred_v_all_df = list()\n",
430 | "\n",
431 | "for end_train_day_x in end_train_day_x_list:\n",
432 | " previous_prediction_horizon = 0\n",
433 | " for prediction_horizon in prediction_horizon_list:\n",
434 | " notebook_name = f\"../input/m5-train-day-{end_train_day_x}-horizon-{prediction_horizon}\"\n",
435 | "\n",
436 | " pred_v_df = pd.DataFrame()\n",
437 | " \n",
438 | " for store_index, store_id in enumerate(store_id_set_list):\n",
439 | " \n",
440 | " model_path = str(f'{notebook_name}/lgb_model_{store_id}_{prediction_horizon}.bin')\n",
441 | " print(f'loading {model_path}')\n",
442 | " estimator = pickle.load(open(model_path, 'rb'))\n",
443 | " base_test = pd.read_feather(f\"{notebook_name}/test_{store_id}_{prediction_horizon}.feather\")\n",
444 | " enable_features = [col for col in base_test.columns if col not in ['id', 'd', 'sales']]\n",
445 | " \n",
446 | " for predict_day in range(previous_prediction_horizon + 1, prediction_horizon + 1):\n",
447 | " print('[{3} -> {4}] predict {0}/{1} {2} day {5}'.format(\n",
448 | " store_index + 1, len(store_id_set_list), store_id,\n",
449 | " previous_prediction_horizon + 1, prediction_horizon, predict_day))\n",
450 | " mask = base_test['d'] == (end_train_day_x + predict_day)\n",
451 | " base_test.loc[mask, 'sales'] = estimator.predict(base_test[mask][enable_features])\n",
452 | " \n",
453 | " temp_v_df = base_test[\n",
454 | " (base_test['d'] >= end_train_day_x + previous_prediction_horizon + 1) &\n",
455 | " (base_test['d'] < end_train_day_x + prediction_horizon + 1)\n",
456 | " ][['id', 'd', 'sales']]\n",
457 | " \n",
458 | " if len(pred_v_df)!=0:\n",
459 | " pred_v_df = pd.concat([pred_v_df, temp_v_df])\n",
460 | " else:\n",
461 | " pred_v_df = temp_v_df.copy()\n",
462 | " \n",
463 | " del(temp_v_df)\n",
464 | " gc.collect()\n",
465 | " \n",
466 | " previous_prediction_horizon = prediction_horizon\n",
467 | " \n",
468 | " if end_train_day_x == 1913:\n",
469 | " pred_v_df.id = pred_v_df.id.str.replace(\"evaluation\", \"validation\")\n",
470 | " \n",
471 | " pred_v_all_df.append(pred_v_df)\n",
472 | " \n",
473 | "pred_v_all_df = pd.concat(pred_v_all_df)"
474 | ]
475 | },
476 | {
477 | "cell_type": "code",
478 | "execution_count": 3,
479 | "id": "8a1fc42e",
480 | "metadata": {
481 | "execution": {
482 | "iopub.execute_input": "2022-10-03T10:59:56.235402Z",
483 | "iopub.status.busy": "2022-10-03T10:59:56.234355Z",
484 | "iopub.status.idle": "2022-10-03T10:59:56.466651Z",
485 | "shell.execute_reply": "2022-10-03T10:59:56.465456Z"
486 | },
487 | "papermill": {
488 | "duration": 0.267259,
489 | "end_time": "2022-10-03T10:59:56.469607",
490 | "exception": false,
491 | "start_time": "2022-10-03T10:59:56.202348",
492 | "status": "completed"
493 | },
494 | "tags": []
495 | },
496 | "outputs": [],
497 | "source": [
498 | "submission = pd.read_csv(\"../input/m5-forecasting-accuracy/sample_submission.csv\")"
499 | ]
500 | },
501 | {
502 | "cell_type": "code",
503 | "execution_count": 4,
504 | "id": "fe67c873",
505 | "metadata": {
506 | "execution": {
507 | "iopub.execute_input": "2022-10-03T10:59:56.516881Z",
508 | "iopub.status.busy": "2022-10-03T10:59:56.516466Z",
509 | "iopub.status.idle": "2022-10-03T10:59:57.171264Z",
510 | "shell.execute_reply": "2022-10-03T10:59:57.170288Z"
511 | },
512 | "papermill": {
513 | "duration": 0.680921,
514 | "end_time": "2022-10-03T10:59:57.173772",
515 | "exception": false,
516 | "start_time": "2022-10-03T10:59:56.492851",
517 | "status": "completed"
518 | },
519 | "tags": []
520 | },
521 | "outputs": [],
522 | "source": [
523 | "pred_v_all_df.d = pred_v_all_df.d - end_train_day_x_list\n",
524 | "pred_h_all_df = pred_v_all_df.pivot(index='id', columns='d', values='sales')\n",
525 | "pred_h_all_df = pred_h_all_df.reset_index()\n",
526 | "pred_h_all_df.columns = submission.columns"
527 | ]
528 | },
529 | {
530 | "cell_type": "code",
531 | "execution_count": 5,
532 | "id": "c41f3ca1",
533 | "metadata": {
534 | "execution": {
535 | "iopub.execute_input": "2022-10-03T10:59:57.217736Z",
536 | "iopub.status.busy": "2022-10-03T10:59:57.216861Z",
537 | "iopub.status.idle": "2022-10-03T10:59:58.580153Z",
538 | "shell.execute_reply": "2022-10-03T10:59:58.579075Z"
539 | },
540 | "papermill": {
541 | "duration": 1.388389,
542 | "end_time": "2022-10-03T10:59:58.583117",
543 | "exception": false,
544 | "start_time": "2022-10-03T10:59:57.194728",
545 | "status": "completed"
546 | },
547 | "tags": []
548 | },
549 | "outputs": [],
550 | "source": [
551 | "submission = submission[['id']].merge(pred_h_all_df, on=['id'], how='left').fillna(0)\n",
552 | "submission.to_csv(\"m5_predictions.csv\", index=False)"
553 | ]
554 | }
555 | ],
556 | "metadata": {
557 | "kernelspec": {
558 | "display_name": "Python 3",
559 | "language": "python",
560 | "name": "python3"
561 | },
562 | "language_info": {
563 | "codemirror_mode": {
564 | "name": "ipython",
565 | "version": 3
566 | },
567 | "file_extension": ".py",
568 | "mimetype": "text/x-python",
569 | "name": "python",
570 | "nbconvert_exporter": "python",
571 | "pygments_lexer": "ipython3",
572 | "version": "3.7.12"
573 | },
574 | "papermill": {
575 | "default_parameters": {},
576 | "duration": 269.581051,
577 | "end_time": "2022-10-03T10:59:59.532195",
578 | "environment_variables": {},
579 | "exception": null,
580 | "input_path": "__notebook__.ipynb",
581 | "output_path": "__notebook__.ipynb",
582 | "parameters": {},
583 | "start_time": "2022-10-03T10:55:29.951144",
584 | "version": "2.3.4"
585 | }
586 | },
587 | "nbformat": 4,
588 | "nbformat_minor": 5
589 | }
590 |
--------------------------------------------------------------------------------
/chapter_02/m5-train-day-1913-horizon-14.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "42ff92d0",
7 | "metadata": {
8 | "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
9 | "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
10 | "execution": {
11 | "iopub.execute_input": "2022-08-10T08:00:53.578549Z",
12 | "iopub.status.busy": "2022-08-10T08:00:53.577944Z",
13 | "iopub.status.idle": "2022-08-10T08:00:55.869333Z",
14 | "shell.execute_reply": "2022-08-10T08:00:55.868083Z"
15 | },
16 | "papermill": {
17 | "duration": 2.302835,
18 | "end_time": "2022-08-10T08:00:55.872607",
19 | "exception": false,
20 | "start_time": "2022-08-10T08:00:53.569772",
21 | "status": "completed"
22 | },
23 | "tags": []
24 | },
25 | "outputs": [
26 | {
27 | "data": {
28 | "text/html": [
29 | "\n"
50 | ],
51 | "text/plain": [
52 | ""
53 | ]
54 | },
55 | "metadata": {},
56 | "output_type": "display_data"
57 | }
58 | ],
59 | "source": [
60 | "import numpy as np\n",
61 | "import pandas as pd\n",
62 | "import os\n",
63 | "import random\n",
64 | "import math\n",
65 | "from decimal import Decimal as dec\n",
66 | "import datetime\n",
67 | "import time\n",
68 | "import gc\n",
69 | "import lightgbm as lgb\n",
70 | "import pickle\n",
71 | "\n",
72 | "import warnings\n",
73 | "warnings.filterwarnings(\"ignore\", category=UserWarning)"
74 | ]
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": 2,
79 | "id": "49991518",
80 | "metadata": {
81 | "execution": {
82 | "iopub.execute_input": "2022-08-10T08:00:55.884808Z",
83 | "iopub.status.busy": "2022-08-10T08:00:55.884370Z",
84 | "iopub.status.idle": "2022-08-10T08:03:36.285412Z",
85 | "shell.execute_reply": "2022-08-10T08:03:36.283263Z"
86 | },
87 | "papermill": {
88 | "duration": 160.410067,
89 | "end_time": "2022-08-10T08:03:36.288151",
90 | "exception": false,
91 | "start_time": "2022-08-10T08:00:55.878084",
92 | "status": "completed"
93 | },
94 | "tags": []
95 | },
96 | "outputs": [
97 | {
98 | "name": "stdout",
99 | "output_type": "stream",
100 | "text": [
101 | "Mem. usage decreased to 96.13 Mb (78.8% reduction)\n",
102 | "Mem. usage decreased to 143.53 Mb (31.2% reduction)\n",
103 | "Mem. usage decreased to 0.12 Mb (41.9% reduction)\n",
104 | "Mem. usage decreased to 2.09 Mb (84.5% reduction)\n"
105 | ]
106 | }
107 | ],
108 | "source": [
109 | "def reduce_mem_usage(df, verbose=True):\n",
110 | " numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n",
111 | " start_mem = df.memory_usage().sum() / 1024**2 \n",
112 | " for col in df.columns:\n",
113 | " col_type = df[col].dtypes\n",
114 | " if col_type in numerics:\n",
115 | " c_min = df[col].min()\n",
116 | " c_max = df[col].max()\n",
117 | " if str(col_type)[:3] == 'int':\n",
118 | " if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n",
119 | " df[col] = df[col].astype(np.int8)\n",
120 | " elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n",
121 | " df[col] = df[col].astype(np.int16)\n",
122 | " elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n",
123 | " df[col] = df[col].astype(np.int32)\n",
124 | " elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n",
125 | " df[col] = df[col].astype(np.int64) \n",
126 | " else:\n",
127 | " if c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n",
128 | " df[col] = df[col].astype(np.float32)\n",
129 | " else:\n",
130 | " df[col] = df[col].astype(np.float64) \n",
131 | " end_mem = df.memory_usage().sum() / 1024**2\n",
132 | " if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n",
133 | " return df\n",
134 | "\n",
135 | "def load_data():\n",
136 | " train_df = reduce_mem_usage(pd.read_csv(\"../input/m5-forecasting-accuracy/sales_train_evaluation.csv\"))\n",
137 | " prices_df = reduce_mem_usage(pd.read_csv(\"../input/m5-forecasting-accuracy/sell_prices.csv\"))\n",
138 | " calendar_df = reduce_mem_usage(pd.read_csv(\"../input/m5-forecasting-accuracy/calendar.csv\"))\n",
139 | " submission_df = reduce_mem_usage(pd.read_csv(\"../input/m5-forecasting-accuracy/sample_submission.csv\"))\n",
140 | " return train_df, prices_df, calendar_df, submission_df\n",
141 | "\n",
142 | "train_df, prices_df, calendar_df, submission_df = load_data()"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": 3,
148 | "id": "f8586e46",
149 | "metadata": {
150 | "execution": {
151 | "iopub.execute_input": "2022-08-10T08:03:36.300235Z",
152 | "iopub.status.busy": "2022-08-10T08:03:36.299817Z",
153 | "iopub.status.idle": "2022-08-10T08:03:36.312801Z",
154 | "shell.execute_reply": "2022-08-10T08:03:36.311527Z"
155 | },
156 | "papermill": {
157 | "duration": 0.02195,
158 | "end_time": "2022-08-10T08:03:36.315222",
159 | "exception": false,
160 | "start_time": "2022-08-10T08:03:36.293272",
161 | "status": "completed"
162 | },
163 | "tags": []
164 | },
165 | "outputs": [],
166 | "source": [
167 | "def generate_base_grid(train_df, end_train_day_x, predict_horizon):\n",
168 | " index_columns = ['id', 'item_id', 'dept_id', 'cat_id', 'store_id', 'state_id']\n",
169 | "\n",
170 | " grid_df = pd.melt(train_df, id_vars=index_columns, var_name='d', value_name='sales')\n",
171 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
172 | "\n",
173 | " grid_df['d_org'] = grid_df['d']\n",
174 | " grid_df['d'] = grid_df['d'].apply(lambda x: x[2:]).astype(np.int16)\n",
175 | "\n",
176 | " time_mask = (grid_df['d'] > end_train_day_x) & (grid_df['d'] <= end_train_day_x + predict_horizon)\n",
177 | " holdout_df = grid_df.loc[time_mask, [\"id\", \"d\", \"sales\"]].reset_index(drop=True)\n",
178 | " holdout_df.to_feather(f\"holdout_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
179 | " del(holdout_df)\n",
180 | " gc.collect()\n",
181 | "\n",
182 | " grid_df = grid_df[grid_df['d'] <= end_train_day_x]\n",
183 | " grid_df['d'] = grid_df['d_org']\n",
184 | " grid_df = grid_df.drop('d_org', axis=1)\n",
185 | "\n",
186 | " add_grid = pd.DataFrame()\n",
187 | " for i in range(predict_horizon):\n",
188 | " temp_df = train_df[index_columns]\n",
189 | " temp_df = temp_df.drop_duplicates()\n",
190 | " temp_df['d'] = 'd_' + str(end_train_day_x + i + 1)\n",
191 | " temp_df['sales'] = np.nan\n",
192 | " add_grid = pd.concat([add_grid, temp_df])\n",
193 | " \n",
194 | " grid_df = pd.concat([grid_df, add_grid])\n",
195 | " grid_df = grid_df.reset_index(drop=True)\n",
196 | " \n",
197 | " for col in index_columns:\n",
198 | " grid_df[col] = grid_df[col].astype('category')\n",
199 | " \n",
200 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
201 | " grid_df.to_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
202 | " del(grid_df)\n",
203 | " gc.collect()"
204 | ]
205 | },
206 | {
207 | "cell_type": "code",
208 | "execution_count": 4,
209 | "id": "6229053d",
210 | "metadata": {
211 | "execution": {
212 | "iopub.execute_input": "2022-08-10T08:03:36.327663Z",
213 | "iopub.status.busy": "2022-08-10T08:03:36.327263Z",
214 | "iopub.status.idle": "2022-08-10T08:03:36.338243Z",
215 | "shell.execute_reply": "2022-08-10T08:03:36.337305Z"
216 | },
217 | "papermill": {
218 | "duration": 0.020108,
219 | "end_time": "2022-08-10T08:03:36.340438",
220 | "exception": false,
221 | "start_time": "2022-08-10T08:03:36.320330",
222 | "status": "completed"
223 | },
224 | "tags": []
225 | },
226 | "outputs": [],
227 | "source": [
228 | "def merge_by_concat(df1, df2, merge_on):\n",
229 | " merged_gf = df1[merge_on]\n",
230 | " merged_gf = merged_gf.merge(df2, on=merge_on, how='left')\n",
231 | " new_columns = [col for col in list(merged_gf) if col not in merge_on]\n",
232 | " df1 = pd.concat([df1, merged_gf[new_columns]], axis=1)\n",
233 | " return df1\n",
234 | " \n",
235 | "def calc_release_week(prices_df, end_train_day_x, predict_horizon):\n",
236 | " index_columns = ['id', 'item_id', 'dept_id', 'cat_id', 'store_id', 'state_id']\n",
237 | " \n",
238 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
239 | " \n",
240 | " release_df = prices_df.groupby(['store_id', 'item_id'])['wm_yr_wk'].agg(['min']).reset_index()\n",
241 | " release_df.columns = ['store_id', 'item_id', 'release']\n",
242 | " \n",
243 | " grid_df = merge_by_concat(grid_df, release_df, ['store_id', 'item_id'])\n",
244 | " \n",
245 | " del release_df\n",
246 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
247 | " gc.collect()\n",
248 | " \n",
249 | " grid_df = merge_by_concat(grid_df, calendar_df[['wm_yr_wk', 'd']], ['d'])\n",
250 | " grid_df = grid_df.reset_index(drop=True)\n",
251 | "\n",
252 | " grid_df['release'] = grid_df['release'] - grid_df['release'].min()\n",
253 | " grid_df['release'] = grid_df['release'].astype(np.int16)\n",
254 | " \n",
255 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
256 | " grid_df.to_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
257 | " del(grid_df)\n",
258 | " gc.collect()"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": 5,
264 | "id": "d1d4adf1",
265 | "metadata": {
266 | "execution": {
267 | "iopub.execute_input": "2022-08-10T08:03:36.352982Z",
268 | "iopub.status.busy": "2022-08-10T08:03:36.352069Z",
269 | "iopub.status.idle": "2022-08-10T08:03:36.368598Z",
270 | "shell.execute_reply": "2022-08-10T08:03:36.367456Z"
271 | },
272 | "papermill": {
273 | "duration": 0.026341,
274 | "end_time": "2022-08-10T08:03:36.371898",
275 | "exception": false,
276 | "start_time": "2022-08-10T08:03:36.345557",
277 | "status": "completed"
278 | },
279 | "tags": []
280 | },
281 | "outputs": [],
282 | "source": [
283 | "def generate_grid_price(prices_df, calendar_df, end_train_day_x, predict_horizon):\n",
284 | "\n",
285 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
286 | "\n",
287 | " prices_df['price_max'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('max')\n",
288 | " prices_df['price_min'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('min')\n",
289 | " prices_df['price_std'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('std')\n",
290 | " prices_df['price_mean'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('mean')\n",
291 | " prices_df['price_norm'] = prices_df['sell_price'] / prices_df['price_max']\n",
292 | " prices_df['price_nunique'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('nunique')\n",
293 | " prices_df['item_nunique'] = prices_df.groupby(['store_id', 'sell_price'])['item_id'].transform('nunique')\n",
294 | "\n",
295 | " calendar_prices = calendar_df[['wm_yr_wk', 'month', 'year']]\n",
296 | " calendar_prices = calendar_prices.drop_duplicates(subset=['wm_yr_wk'])\n",
297 | " prices_df = prices_df.merge(calendar_prices[['wm_yr_wk', 'month', 'year']], on=['wm_yr_wk'], how='left')\n",
298 | " \n",
299 | " del calendar_prices\n",
300 | " gc.collect()\n",
301 | " \n",
302 | " prices_df['price_momentum'] = prices_df['sell_price'] / prices_df.groupby(['store_id', 'item_id'])[\n",
303 | " 'sell_price'].transform(lambda x: x.shift(1))\n",
304 | " prices_df['price_momentum_m'] = prices_df['sell_price'] / prices_df.groupby(['store_id', 'item_id', 'month'])[\n",
305 | " 'sell_price'].transform('mean')\n",
306 | " prices_df['price_momentum_y'] = prices_df['sell_price'] / prices_df.groupby(['store_id', 'item_id', 'year'])[\n",
307 | " 'sell_price'].transform('mean')\n",
308 | "\n",
309 | " prices_df['sell_price_cent'] = [math.modf(p)[0] for p in prices_df['sell_price']]\n",
310 | " prices_df['price_max_cent'] = [math.modf(p)[0] for p in prices_df['price_max']]\n",
311 | " prices_df['price_min_cent'] = [math.modf(p)[0] for p in prices_df['price_min']]\n",
312 | "\n",
313 | " del prices_df['month'], prices_df['year']\n",
314 | " prices_df = reduce_mem_usage(prices_df, verbose=False)\n",
315 | " gc.collect()\n",
316 | " \n",
317 | " original_columns = list(grid_df)\n",
318 | " grid_df = grid_df.merge(prices_df, on=['store_id', 'item_id', 'wm_yr_wk'], how='left')\n",
319 | " del(prices_df)\n",
320 | " gc.collect()\n",
321 | " \n",
322 | " keep_columns = [col for col in list(grid_df) if col not in original_columns]\n",
323 | " grid_df = grid_df[['id', 'd'] + keep_columns]\n",
324 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
325 | "\n",
326 | " grid_df.to_feather(f\"grid_price_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
327 | " del(grid_df)\n",
328 | " gc.collect()"
329 | ]
330 | },
331 | {
332 | "cell_type": "code",
333 | "execution_count": 6,
334 | "id": "1b521f42",
335 | "metadata": {
336 | "execution": {
337 | "iopub.execute_input": "2022-08-10T08:03:36.384960Z",
338 | "iopub.status.busy": "2022-08-10T08:03:36.384524Z",
339 | "iopub.status.idle": "2022-08-10T08:03:36.402050Z",
340 | "shell.execute_reply": "2022-08-10T08:03:36.400670Z"
341 | },
342 | "papermill": {
343 | "duration": 0.028013,
344 | "end_time": "2022-08-10T08:03:36.405829",
345 | "exception": false,
346 | "start_time": "2022-08-10T08:03:36.377816",
347 | "status": "completed"
348 | },
349 | "tags": []
350 | },
351 | "outputs": [],
352 | "source": [
353 | "def get_moon_phase(d): # 0=new, 4=full; 4 days/phase\n",
354 | " diff = datetime.datetime.strptime(d, '%Y-%m-%d') - datetime.datetime(2001, 1, 1)\n",
355 | " days = dec(diff.days) + (dec(diff.seconds) / dec(86400))\n",
356 | " lunations = dec(\"0.20439731\") + (days * dec(\"0.03386319269\"))\n",
357 | " phase_index = math.floor((lunations % dec(1) * dec(8)) + dec('0.5'))\n",
358 | " return int(phase_index) & 7\n",
359 | " \n",
360 | "def generate_grid_calendar(calendar_df, end_train_day_x, predict_horizon):\n",
361 | " \n",
362 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
363 | " grid_df = grid_df[['id', 'd']]\n",
364 | " gc.collect()\n",
365 | "\n",
366 | " calendar_df['moon'] = calendar_df.date.apply(get_moon_phase)\n",
367 | "\n",
368 | " # Merge calendar partly\n",
369 | " icols = ['date',\n",
370 | " 'd',\n",
371 | " 'event_name_1',\n",
372 | " 'event_type_1',\n",
373 | " 'event_name_2',\n",
374 | " 'event_type_2',\n",
375 | " 'snap_CA',\n",
376 | " 'snap_TX',\n",
377 | " 'snap_WI',\n",
378 | " 'moon',\n",
379 | " ]\n",
380 | "\n",
381 | " grid_df = grid_df.merge(calendar_df[icols], on=['d'], how='left')\n",
382 | "\n",
383 | " icols = ['event_name_1',\n",
384 | " 'event_type_1',\n",
385 | " 'event_name_2',\n",
386 | " 'event_type_2',\n",
387 | " 'snap_CA',\n",
388 | " 'snap_TX',\n",
389 | " 'snap_WI']\n",
390 | " \n",
391 | " for col in icols:\n",
392 | " grid_df[col] = grid_df[col].astype('category')\n",
393 | "\n",
394 | " grid_df['date'] = pd.to_datetime(grid_df['date'])\n",
395 | "\n",
396 | " grid_df['tm_d'] = grid_df['date'].dt.day.astype(np.int8)\n",
397 | " grid_df['tm_w'] = grid_df['date'].dt.isocalendar().week.astype(np.int8)\n",
398 | " grid_df['tm_m'] = grid_df['date'].dt.month.astype(np.int8)\n",
399 | " grid_df['tm_y'] = grid_df['date'].dt.year\n",
400 | " grid_df['tm_y'] = (grid_df['tm_y'] - grid_df['tm_y'].min()).astype(np.int8)\n",
401 | " grid_df['tm_wm'] = grid_df['tm_d'].apply(lambda x: math.ceil(x / 7)).astype(np.int8)\n",
402 | "\n",
403 | " grid_df['tm_dw'] = grid_df['date'].dt.dayofweek.astype(np.int8)\n",
404 | " grid_df['tm_w_end'] = (grid_df['tm_dw'] >= 5).astype(np.int8)\n",
405 | " \n",
406 | " del(grid_df['date'])\n",
407 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
408 | " grid_df.to_feather(f\"grid_calendar_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
409 | " \n",
410 | " del(grid_df)\n",
411 | " del(calendar_df)\n",
412 | " gc.collect()"
413 | ]
414 | },
415 | {
416 | "cell_type": "code",
417 | "execution_count": 7,
418 | "id": "8d21ae9b",
419 | "metadata": {
420 | "execution": {
421 | "iopub.execute_input": "2022-08-10T08:03:36.418118Z",
422 | "iopub.status.busy": "2022-08-10T08:03:36.417675Z",
423 | "iopub.status.idle": "2022-08-10T08:03:36.425109Z",
424 | "shell.execute_reply": "2022-08-10T08:03:36.423661Z"
425 | },
426 | "papermill": {
427 | "duration": 0.017284,
428 | "end_time": "2022-08-10T08:03:36.428337",
429 | "exception": false,
430 | "start_time": "2022-08-10T08:03:36.411053",
431 | "status": "completed"
432 | },
433 | "tags": []
434 | },
435 | "outputs": [],
436 | "source": [
437 | "def modify_grid_base(end_train_day_x, predict_horizon):\n",
438 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
439 | " grid_df['d'] = grid_df['d'].apply(lambda x: x[2:]).astype(np.int16)\n",
440 | " del grid_df['wm_yr_wk']\n",
441 | " \n",
442 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
443 | " grid_df.to_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
444 | " \n",
445 | " del(grid_df)\n",
446 | " gc.collect()"
447 | ]
448 | },
449 | {
450 | "cell_type": "code",
451 | "execution_count": 8,
452 | "id": "41f22821",
453 | "metadata": {
454 | "execution": {
455 | "iopub.execute_input": "2022-08-10T08:03:36.441104Z",
456 | "iopub.status.busy": "2022-08-10T08:03:36.440324Z",
457 | "iopub.status.idle": "2022-08-10T08:03:36.451914Z",
458 | "shell.execute_reply": "2022-08-10T08:03:36.450919Z"
459 | },
460 | "papermill": {
461 | "duration": 0.021041,
462 | "end_time": "2022-08-10T08:03:36.454525",
463 | "exception": false,
464 | "start_time": "2022-08-10T08:03:36.433484",
465 | "status": "completed"
466 | },
467 | "tags": []
468 | },
469 | "outputs": [],
470 | "source": [
471 | "def generate_lag_feature(end_train_day_x, predict_horizon):\n",
472 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
473 | " grid_df = grid_df[['id', 'd', 'sales']]\n",
474 | " \n",
475 | " num_lag_day_list = []\n",
476 | " num_lag_day = 15\n",
477 | " for col in range(predict_horizon, predict_horizon + num_lag_day):\n",
478 | " num_lag_day_list.append(col)\n",
479 | " \n",
480 | " num_rolling_day_list = [7, 14, 30, 60, 180]\n",
481 | " num_shift_rolling_day_list = []\n",
482 | " for num_shift_day in [1, 7, 14]:\n",
483 | " for num_rolling_day in [7, 14, 30, 60]:\n",
484 | " num_shift_rolling_day_list.append([num_shift_day, num_rolling_day])\n",
485 | " \n",
486 | " grid_df = grid_df.assign(**{\n",
487 | " '{}_lag_{}'.format(col, l): grid_df.groupby(['id'])['sales'].transform(lambda x: x.shift(l))\n",
488 | " for l in num_lag_day_list\n",
489 | " })\n",
490 | "\n",
491 | " for col in list(grid_df):\n",
492 | " if 'lag' in col:\n",
493 | " grid_df[col] = grid_df[col].astype(np.float16)\n",
494 | "\n",
495 | " for num_rolling_day in num_rolling_day_list:\n",
496 | " grid_df['rolling_mean_' + str(num_rolling_day)] = grid_df.groupby(['id'])['sales'].transform(\n",
497 | " lambda x: x.shift(predict_horizon).rolling(num_rolling_day).mean()).astype(np.float16)\n",
498 | " grid_df['rolling_std_' + str(num_rolling_day)] = grid_df.groupby(['id'])['sales'].transform(\n",
499 | " lambda x: x.shift(predict_horizon).rolling(num_rolling_day).std()).astype(np.float16)\n",
500 | "\n",
501 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
502 | " grid_df.to_feather(f\"lag_feature_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
503 | " \n",
504 | " del(grid_df)\n",
505 | " gc.collect()\n"
506 | ]
507 | },
508 | {
509 | "cell_type": "code",
510 | "execution_count": 9,
511 | "id": "4a9d6859",
512 | "metadata": {
513 | "execution": {
514 | "iopub.execute_input": "2022-08-10T08:03:36.467638Z",
515 | "iopub.status.busy": "2022-08-10T08:03:36.466900Z",
516 | "iopub.status.idle": "2022-08-10T08:03:36.477030Z",
517 | "shell.execute_reply": "2022-08-10T08:03:36.475839Z"
518 | },
519 | "papermill": {
520 | "duration": 0.019823,
521 | "end_time": "2022-08-10T08:03:36.479619",
522 | "exception": false,
523 | "start_time": "2022-08-10T08:03:36.459796",
524 | "status": "completed"
525 | },
526 | "tags": []
527 | },
528 | "outputs": [],
529 | "source": [
530 | "def generate_target_encoding_feature(end_train_day_x, predict_horizon):\n",
531 | "\n",
532 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
533 | " \n",
534 | " grid_df.loc[grid_df['d'] > (end_train_day_x - predict_horizon), 'sales'] = np.nan\n",
535 | " base_cols = list(grid_df)\n",
536 | "\n",
537 | " icols = [\n",
538 | " ['state_id'],\n",
539 | " ['store_id'],\n",
540 | " ['cat_id'],\n",
541 | " ['dept_id'],\n",
542 | " ['state_id', 'cat_id'],\n",
543 | " ['state_id', 'dept_id'],\n",
544 | " ['store_id', 'cat_id'],\n",
545 | " ['store_id', 'dept_id'],\n",
546 | " ['item_id'],\n",
547 | " ['item_id', 'state_id'],\n",
548 | " ['item_id', 'store_id']\n",
549 | " ]\n",
550 | "\n",
551 | " for col in icols:\n",
552 | " col_name = '_' + '_'.join(col) + '_'\n",
553 | " grid_df['enc' + col_name + 'mean'] = grid_df.groupby(col)['sales'].transform('mean').astype(\n",
554 | " np.float16)\n",
555 | " grid_df['enc' + col_name + 'std'] = grid_df.groupby(col)['sales'].transform('std').astype(\n",
556 | " np.float16)\n",
557 | "\n",
558 | " keep_cols = [col for col in list(grid_df) if col not in base_cols]\n",
559 | " grid_df = grid_df[['id', 'd'] + keep_cols]\n",
560 | "\n",
561 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
562 | " grid_df.to_feather(f\"target_encoding_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
563 | " \n",
564 | " del(grid_df)\n",
565 | " gc.collect()"
566 | ]
567 | },
568 | {
569 | "cell_type": "code",
570 | "execution_count": 10,
571 | "id": "340cb424",
572 | "metadata": {
573 | "execution": {
574 | "iopub.execute_input": "2022-08-10T08:03:36.492763Z",
575 | "iopub.status.busy": "2022-08-10T08:03:36.491937Z",
576 | "iopub.status.idle": "2022-08-10T08:03:36.505344Z",
577 | "shell.execute_reply": "2022-08-10T08:03:36.504100Z"
578 | },
579 | "papermill": {
580 | "duration": 0.023044,
581 | "end_time": "2022-08-10T08:03:36.508148",
582 | "exception": false,
583 | "start_time": "2022-08-10T08:03:36.485104",
584 | "status": "completed"
585 | },
586 | "tags": []
587 | },
588 | "outputs": [],
589 | "source": [
590 | "def assemble_grid_by_store(train_df, end_train_day_x, predict_horizon):\n",
591 | " grid_df = pd.concat([pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\"),\n",
592 | " pd.read_feather(f\"grid_price_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\").iloc[:, 2:],\n",
593 | " pd.read_feather(f\"grid_calendar_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\").iloc[:, 2:]],\n",
594 | " axis=1)\n",
595 | " gc.collect()\n",
596 | " store_id_set_list = list(train_df['store_id'].unique())\n",
597 | "\n",
598 | " index_store = dict()\n",
599 | " for store_id in store_id_set_list:\n",
600 | " extract = grid_df[grid_df['store_id'] == store_id]\n",
601 | " index_store[store_id] = extract.index.to_numpy()\n",
602 | " extract = extract.reset_index(drop=True)\n",
603 | " extract.to_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
604 | "\n",
605 | " del(grid_df)\n",
606 | " gc.collect()\n",
607 | " \n",
608 | " mean_features = [\n",
609 | " 'enc_cat_id_mean', 'enc_cat_id_std',\n",
610 | " 'enc_dept_id_mean', 'enc_dept_id_std',\n",
611 | " 'enc_item_id_mean', 'enc_item_id_std'\n",
612 | " ]\n",
613 | " df2 = pd.read_feather(f\"target_encoding_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")[mean_features]\n",
614 | "\n",
615 | " for store_id in store_id_set_list:\n",
616 | " df = pd.read_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
617 | " df = pd.concat([df, df2[df2.index.isin(index_store[store_id])].reset_index(drop=True)], axis=1)\n",
618 | " df.to_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
619 | "\n",
620 | " del(df2)\n",
621 | " gc.collect()\n",
622 | " \n",
623 | " df3 = pd.read_feather(f\"lag_feature_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\").iloc[:, 3:]\n",
624 | "\n",
625 | " for store_id in store_id_set_list:\n",
626 | " df = pd.read_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
627 | " df = pd.concat([df, df3[df3.index.isin(index_store[store_id])].reset_index(drop=True)], axis=1)\n",
628 | " df.to_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
629 | "\n",
630 | " del(df3)\n",
631 | " del(store_id_set_list)\n",
632 | " gc.collect()\n"
633 | ]
634 | },
635 | {
636 | "cell_type": "code",
637 | "execution_count": 11,
638 | "id": "8636015c",
639 | "metadata": {
640 | "execution": {
641 | "iopub.execute_input": "2022-08-10T08:03:36.521446Z",
642 | "iopub.status.busy": "2022-08-10T08:03:36.520661Z",
643 | "iopub.status.idle": "2022-08-10T08:03:36.527226Z",
644 | "shell.execute_reply": "2022-08-10T08:03:36.526274Z"
645 | },
646 | "papermill": {
647 | "duration": 0.016431,
648 | "end_time": "2022-08-10T08:03:36.529754",
649 | "exception": false,
650 | "start_time": "2022-08-10T08:03:36.513323",
651 | "status": "completed"
652 | },
653 | "tags": []
654 | },
655 | "outputs": [],
656 | "source": [
657 | "def load_grid_by_store(end_train_day_x, predict_horizon, store_id):\n",
658 | " df = pd.read_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
659 | " \n",
660 | " remove_features = ['id', 'state_id', 'store_id', 'date', 'wm_yr_wk', 'd', 'sales']\n",
661 | " enable_features = [col for col in list(df) if col not in remove_features]\n",
662 | " df = df[['id', 'd', 'sales'] + enable_features]\n",
663 | " df = reduce_mem_usage(df, verbose=False)\n",
664 | " gc.collect()\n",
665 | " \n",
666 | " return df, enable_features"
667 | ]
668 | },
669 | {
670 | "cell_type": "code",
671 | "execution_count": 12,
672 | "id": "3c4f75f0",
673 | "metadata": {
674 | "execution": {
675 | "iopub.execute_input": "2022-08-10T08:03:36.542845Z",
676 | "iopub.status.busy": "2022-08-10T08:03:36.542048Z",
677 | "iopub.status.idle": "2022-08-10T08:03:36.558473Z",
678 | "shell.execute_reply": "2022-08-10T08:03:36.557134Z"
679 | },
680 | "papermill": {
681 | "duration": 0.025907,
682 | "end_time": "2022-08-10T08:03:36.561137",
683 | "exception": false,
684 | "start_time": "2022-08-10T08:03:36.535230",
685 | "status": "completed"
686 | },
687 | "tags": []
688 | },
689 | "outputs": [],
690 | "source": [
691 | "def train(train_df, seed, end_train_day_x, predict_horizon):\n",
692 | " \n",
693 | " lgb_params = {\n",
694 | " 'boosting_type': 'goss',\n",
695 | " 'objective': 'tweedie',\n",
696 | " 'tweedie_variance_power': 1.1,\n",
697 | " 'metric': 'rmse',\n",
698 | " #'subsample': 0.5,\n",
699 | " #'subsample_freq': 1,\n",
700 | " 'learning_rate': 0.03,\n",
701 | " 'num_leaves': 2 ** 11 - 1,\n",
702 | " 'min_data_in_leaf': 2 ** 12 - 1,\n",
703 | " 'feature_fraction': 0.5,\n",
704 | " 'max_bin': 100,\n",
705 | " 'boost_from_average': False,\n",
706 | " 'num_boost_round': 1400,\n",
707 | " 'verbose': -1,\n",
708 | " 'num_threads': os.cpu_count(),\n",
709 | " 'force_row_wise': True,\n",
710 | " }\n",
711 | "\n",
712 | " random.seed(seed)\n",
713 | " np.random.seed(seed)\n",
714 | " os.environ['PYTHONHASHSEED'] = str(seed)\n",
715 | " \n",
716 | " lgb_params['seed'] = seed\n",
717 | "\n",
718 | " store_id_set_list = list(train_df['store_id'].unique())\n",
719 | " print(f\"training stores: {store_id_set_list}\")\n",
720 | " \n",
721 | " feature_importance_all_df = pd.DataFrame()\n",
722 | " for store_index, store_id in enumerate(store_id_set_list):\n",
723 | " print(f'now training {store_id} store')\n",
724 | "\n",
725 | " grid_df, enable_features = load_grid_by_store(end_train_day_x, predict_horizon, store_id)\n",
726 | "\n",
727 | " train_mask = grid_df['d'] <= end_train_day_x\n",
728 | " valid_mask = train_mask & (grid_df['d'] > (end_train_day_x - predict_horizon))\n",
729 | " preds_mask = grid_df['d'] > (end_train_day_x - 100)\n",
730 | "\n",
731 | " train_data = lgb.Dataset(grid_df[train_mask][enable_features],\n",
732 | " label=grid_df[train_mask]['sales'])\n",
733 | "\n",
734 | " valid_data = lgb.Dataset(grid_df[valid_mask][enable_features],\n",
735 | " label=grid_df[valid_mask]['sales'])\n",
736 | "\n",
737 | "\n",
738 | " # Saving part of the dataset for later predictions\n",
739 | " # Removing features that we need to calculate recursively\n",
740 | " grid_df = grid_df[preds_mask].reset_index(drop=True)\n",
741 | " grid_df.to_feather(f'test_{store_id}_{predict_horizon}.feather')\n",
742 | " del(grid_df)\n",
743 | " gc.collect()\n",
744 | " \n",
745 | " estimator = lgb.train(lgb_params,\n",
746 | " train_data,\n",
747 | " valid_sets=[valid_data],\n",
748 | " callbacks=[lgb.log_evaluation(period=100, show_stdv=False)],\n",
749 | " )\n",
750 | "\n",
751 | " model_name = str(f'lgb_model_{store_id}_{predict_horizon}.bin')\n",
752 | " feature_importance_store_df = pd.DataFrame(sorted(zip(enable_features, estimator.feature_importance())),\n",
753 | " columns=['feature_name', 'importance'])\n",
754 | " feature_importance_store_df = feature_importance_store_df.sort_values('importance', ascending=False)\n",
755 | " feature_importance_store_df['store_id'] = store_id\n",
756 | " feature_importance_store_df.to_csv(f'feature_importance_{store_id}_{predict_horizon}.csv', index=False)\n",
757 | " feature_importance_all_df = pd.concat([feature_importance_all_df, feature_importance_store_df])\n",
758 | " pickle.dump(estimator, open(model_name, 'wb'))\n",
759 | "\n",
760 | " del([train_data, valid_data, estimator])\n",
761 | " gc.collect()\n",
762 | "\n",
763 | " feature_importance_all_df.to_csv(f'feature_importance_all_{predict_horizon}.csv', index=False)\n",
764 | " feature_importance_agg_df = feature_importance_all_df.groupby(\n",
765 | " 'feature_name')['importance'].agg(['mean', 'std']).reset_index()\n",
766 | " feature_importance_agg_df.columns = ['feature_name', 'importance_mean', 'importance_std']\n",
767 | " feature_importance_agg_df = feature_importance_agg_df.sort_values('importance_mean', ascending=False)\n",
768 | " feature_importance_agg_df.to_csv(f'feature_importance_agg_{predict_horizon}.csv', index=False)"
769 | ]
770 | },
771 | {
772 | "cell_type": "code",
773 | "execution_count": 13,
774 | "id": "5318004f",
775 | "metadata": {
776 | "execution": {
777 | "iopub.execute_input": "2022-08-10T08:03:36.573935Z",
778 | "iopub.status.busy": "2022-08-10T08:03:36.573133Z",
779 | "iopub.status.idle": "2022-08-10T08:03:36.581683Z",
780 | "shell.execute_reply": "2022-08-10T08:03:36.580609Z"
781 | },
782 | "papermill": {
783 | "duration": 0.017998,
784 | "end_time": "2022-08-10T08:03:36.584323",
785 | "exception": false,
786 | "start_time": "2022-08-10T08:03:36.566325",
787 | "status": "completed"
788 | },
789 | "tags": []
790 | },
791 | "outputs": [],
792 | "source": [
793 | "def train_pipeline(train_df, prices_df, calendar_df, end_train_day_x_list, prediction_horizon_list):\n",
794 | " \n",
795 | " for end_train_day_x in end_train_day_x_list:\n",
796 | " \n",
797 | " for predict_horizon in prediction_horizon_list:\n",
798 | " \n",
799 | " print(f\"end training point day: {end_train_day_x} - prediction horizon: {predict_horizon} days\")\n",
800 | "\n",
801 | " # Data preparation\n",
802 | " generate_base_grid(train_df, end_train_day_x, predict_horizon)\n",
803 | " calc_release_week(prices_df, end_train_day_x, predict_horizon)\n",
804 | " generate_grid_price(prices_df, calendar_df, end_train_day_x, predict_horizon)\n",
805 | " generate_grid_calendar(calendar_df, end_train_day_x, predict_horizon)\n",
806 | " modify_grid_base(end_train_day_x, predict_horizon)\n",
807 | " generate_lag_feature(end_train_day_x, predict_horizon)\n",
808 | " generate_target_encoding_feature(end_train_day_x, predict_horizon)\n",
809 | " assemble_grid_by_store(train_df, end_train_day_x, predict_horizon)\n",
810 | "\n",
811 | " # Modelling\n",
812 | " train(train_df, seed, end_train_day_x, predict_horizon)\n",
813 | " "
814 | ]
815 | },
816 | {
817 | "cell_type": "code",
818 | "execution_count": 14,
819 | "id": "76f519a4",
820 | "metadata": {
821 | "execution": {
822 | "iopub.execute_input": "2022-08-10T08:03:36.597132Z",
823 | "iopub.status.busy": "2022-08-10T08:03:36.596656Z",
824 | "iopub.status.idle": "2022-08-10T14:00:56.217703Z",
825 | "shell.execute_reply": "2022-08-10T14:00:56.216355Z"
826 | },
827 | "papermill": {
828 | "duration": 21439.632474,
829 | "end_time": "2022-08-10T14:00:56.221972",
830 | "exception": false,
831 | "start_time": "2022-08-10T08:03:36.589498",
832 | "status": "completed"
833 | },
834 | "tags": []
835 | },
836 | "outputs": [
837 | {
838 | "name": "stdout",
839 | "output_type": "stream",
840 | "text": [
841 | "end training point day: 1913 - prediction horizon: 14 days\n",
842 | "training stores: ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n",
843 | "now training CA_1 store\n",
844 | "[100]\tvalid_0's rmse: 1.98492\n",
845 | "[200]\tvalid_0's rmse: 1.98161\n",
846 | "[300]\tvalid_0's rmse: 1.97054\n",
847 | "[400]\tvalid_0's rmse: 1.95829\n",
848 | "[500]\tvalid_0's rmse: 1.94792\n",
849 | "[600]\tvalid_0's rmse: 1.93966\n",
850 | "[700]\tvalid_0's rmse: 1.93218\n",
851 | "[800]\tvalid_0's rmse: 1.92508\n",
852 | "[900]\tvalid_0's rmse: 1.91939\n",
853 | "[1000]\tvalid_0's rmse: 1.91346\n",
854 | "[1100]\tvalid_0's rmse: 1.90813\n",
855 | "[1200]\tvalid_0's rmse: 1.90283\n",
856 | "[1300]\tvalid_0's rmse: 1.8973\n",
857 | "[1400]\tvalid_0's rmse: 1.89283\n",
858 | "now training CA_2 store\n",
859 | "[100]\tvalid_0's rmse: 1.91117\n",
860 | "[200]\tvalid_0's rmse: 1.86986\n",
861 | "[300]\tvalid_0's rmse: 1.84889\n",
862 | "[400]\tvalid_0's rmse: 1.83344\n",
863 | "[500]\tvalid_0's rmse: 1.82144\n",
864 | "[600]\tvalid_0's rmse: 1.81059\n",
865 | "[700]\tvalid_0's rmse: 1.80194\n",
866 | "[800]\tvalid_0's rmse: 1.79452\n",
867 | "[900]\tvalid_0's rmse: 1.7881\n",
868 | "[1000]\tvalid_0's rmse: 1.7823\n",
869 | "[1100]\tvalid_0's rmse: 1.77661\n",
870 | "[1200]\tvalid_0's rmse: 1.77086\n",
871 | "[1300]\tvalid_0's rmse: 1.76593\n",
872 | "[1400]\tvalid_0's rmse: 1.76159\n",
873 | "now training CA_3 store\n",
874 | "[100]\tvalid_0's rmse: 2.53222\n",
875 | "[200]\tvalid_0's rmse: 2.47532\n",
876 | "[300]\tvalid_0's rmse: 2.4488\n",
877 | "[400]\tvalid_0's rmse: 2.43069\n",
878 | "[500]\tvalid_0's rmse: 2.41843\n",
879 | "[600]\tvalid_0's rmse: 2.40709\n",
880 | "[700]\tvalid_0's rmse: 2.3973\n",
881 | "[800]\tvalid_0's rmse: 2.38801\n",
882 | "[900]\tvalid_0's rmse: 2.38002\n",
883 | "[1000]\tvalid_0's rmse: 2.37329\n",
884 | "[1100]\tvalid_0's rmse: 2.36563\n",
885 | "[1200]\tvalid_0's rmse: 2.35844\n",
886 | "[1300]\tvalid_0's rmse: 2.35117\n",
887 | "[1400]\tvalid_0's rmse: 2.34429\n",
888 | "now training CA_4 store\n",
889 | "[100]\tvalid_0's rmse: 1.35882\n",
890 | "[200]\tvalid_0's rmse: 1.35035\n",
891 | "[300]\tvalid_0's rmse: 1.3444\n",
892 | "[400]\tvalid_0's rmse: 1.33928\n",
893 | "[500]\tvalid_0's rmse: 1.33456\n",
894 | "[600]\tvalid_0's rmse: 1.33113\n",
895 | "[700]\tvalid_0's rmse: 1.32778\n",
896 | "[800]\tvalid_0's rmse: 1.32449\n",
897 | "[900]\tvalid_0's rmse: 1.32143\n",
898 | "[1000]\tvalid_0's rmse: 1.31866\n",
899 | "[1100]\tvalid_0's rmse: 1.31563\n",
900 | "[1200]\tvalid_0's rmse: 1.31325\n",
901 | "[1300]\tvalid_0's rmse: 1.31065\n",
902 | "[1400]\tvalid_0's rmse: 1.30808\n",
903 | "now training TX_1 store\n",
904 | "[100]\tvalid_0's rmse: 1.6319\n",
905 | "[200]\tvalid_0's rmse: 1.62011\n",
906 | "[300]\tvalid_0's rmse: 1.61463\n",
907 | "[400]\tvalid_0's rmse: 1.6082\n",
908 | "[500]\tvalid_0's rmse: 1.60243\n",
909 | "[600]\tvalid_0's rmse: 1.59738\n",
910 | "[700]\tvalid_0's rmse: 1.59228\n",
911 | "[800]\tvalid_0's rmse: 1.58685\n",
912 | "[900]\tvalid_0's rmse: 1.58183\n",
913 | "[1000]\tvalid_0's rmse: 1.57853\n",
914 | "[1100]\tvalid_0's rmse: 1.57457\n",
915 | "[1200]\tvalid_0's rmse: 1.57167\n",
916 | "[1300]\tvalid_0's rmse: 1.56707\n",
917 | "[1400]\tvalid_0's rmse: 1.56351\n",
918 | "now training TX_2 store\n",
919 | "[100]\tvalid_0's rmse: 1.7827\n",
920 | "[200]\tvalid_0's rmse: 1.78291\n",
921 | "[300]\tvalid_0's rmse: 1.76916\n",
922 | "[400]\tvalid_0's rmse: 1.75764\n",
923 | "[500]\tvalid_0's rmse: 1.74986\n",
924 | "[600]\tvalid_0's rmse: 1.74015\n",
925 | "[700]\tvalid_0's rmse: 1.73274\n",
926 | "[800]\tvalid_0's rmse: 1.72597\n",
927 | "[900]\tvalid_0's rmse: 1.71936\n",
928 | "[1000]\tvalid_0's rmse: 1.71248\n",
929 | "[1100]\tvalid_0's rmse: 1.70518\n",
930 | "[1200]\tvalid_0's rmse: 1.69903\n",
931 | "[1300]\tvalid_0's rmse: 1.6947\n",
932 | "[1400]\tvalid_0's rmse: 1.68947\n",
933 | "now training TX_3 store\n",
934 | "[100]\tvalid_0's rmse: 1.78573\n",
935 | "[200]\tvalid_0's rmse: 1.77665\n",
936 | "[300]\tvalid_0's rmse: 1.76574\n",
937 | "[400]\tvalid_0's rmse: 1.75667\n",
938 | "[500]\tvalid_0's rmse: 1.74594\n",
939 | "[600]\tvalid_0's rmse: 1.73627\n",
940 | "[700]\tvalid_0's rmse: 1.72786\n",
941 | "[800]\tvalid_0's rmse: 1.72006\n",
942 | "[900]\tvalid_0's rmse: 1.71262\n",
943 | "[1000]\tvalid_0's rmse: 1.70555\n",
944 | "[1100]\tvalid_0's rmse: 1.69912\n",
945 | "[1200]\tvalid_0's rmse: 1.694\n",
946 | "[1300]\tvalid_0's rmse: 1.6876\n",
947 | "[1400]\tvalid_0's rmse: 1.68226\n",
948 | "now training WI_1 store\n",
949 | "[100]\tvalid_0's rmse: 1.62552\n",
950 | "[200]\tvalid_0's rmse: 1.60633\n",
951 | "[300]\tvalid_0's rmse: 1.59359\n",
952 | "[400]\tvalid_0's rmse: 1.58471\n",
953 | "[500]\tvalid_0's rmse: 1.57678\n",
954 | "[600]\tvalid_0's rmse: 1.5691\n",
955 | "[700]\tvalid_0's rmse: 1.5624\n",
956 | "[800]\tvalid_0's rmse: 1.55719\n",
957 | "[900]\tvalid_0's rmse: 1.55085\n",
958 | "[1000]\tvalid_0's rmse: 1.54566\n",
959 | "[1100]\tvalid_0's rmse: 1.54092\n",
960 | "[1200]\tvalid_0's rmse: 1.5353\n",
961 | "[1300]\tvalid_0's rmse: 1.53084\n",
962 | "[1400]\tvalid_0's rmse: 1.52649\n",
963 | "now training WI_2 store\n",
964 | "[100]\tvalid_0's rmse: 2.77893\n",
965 | "[200]\tvalid_0's rmse: 2.6597\n",
966 | "[300]\tvalid_0's rmse: 2.61266\n",
967 | "[400]\tvalid_0's rmse: 2.57752\n",
968 | "[500]\tvalid_0's rmse: 2.55148\n",
969 | "[600]\tvalid_0's rmse: 2.53119\n",
970 | "[700]\tvalid_0's rmse: 2.51245\n",
971 | "[800]\tvalid_0's rmse: 2.49806\n",
972 | "[900]\tvalid_0's rmse: 2.48206\n",
973 | "[1000]\tvalid_0's rmse: 2.46869\n",
974 | "[1100]\tvalid_0's rmse: 2.45617\n",
975 | "[1200]\tvalid_0's rmse: 2.44478\n",
976 | "[1300]\tvalid_0's rmse: 2.43257\n",
977 | "[1400]\tvalid_0's rmse: 2.41996\n",
978 | "now training WI_3 store\n",
979 | "[100]\tvalid_0's rmse: 2.01178\n",
980 | "[200]\tvalid_0's rmse: 1.92874\n",
981 | "[300]\tvalid_0's rmse: 1.9046\n",
982 | "[400]\tvalid_0's rmse: 1.88611\n",
983 | "[500]\tvalid_0's rmse: 1.86973\n",
984 | "[600]\tvalid_0's rmse: 1.85482\n",
985 | "[700]\tvalid_0's rmse: 1.84318\n",
986 | "[800]\tvalid_0's rmse: 1.83389\n",
987 | "[900]\tvalid_0's rmse: 1.82589\n",
988 | "[1000]\tvalid_0's rmse: 1.81567\n",
989 | "[1100]\tvalid_0's rmse: 1.8056\n",
990 | "[1200]\tvalid_0's rmse: 1.79759\n",
991 | "[1300]\tvalid_0's rmse: 1.78984\n",
992 | "[1400]\tvalid_0's rmse: 1.78209\n"
993 | ]
994 | }
995 | ],
996 | "source": [
997 | "end_train_day_x_list = [1913] # [1941, 1913, 1885, 1857, 1829, 1577]\n",
998 | "prediction_horizon_list = [14] # [7, 14, 21, 28]\n",
999 | "seed = 42\n",
1000 | "\n",
1001 | "train_pipeline(train_df, prices_df, calendar_df, end_train_day_x_list, prediction_horizon_list)"
1002 | ]
1003 | }
1004 | ],
1005 | "metadata": {
1006 | "kernelspec": {
1007 | "display_name": "Python 3",
1008 | "language": "python",
1009 | "name": "python3"
1010 | },
1011 | "language_info": {
1012 | "codemirror_mode": {
1013 | "name": "ipython",
1014 | "version": 3
1015 | },
1016 | "file_extension": ".py",
1017 | "mimetype": "text/x-python",
1018 | "name": "python",
1019 | "nbconvert_exporter": "python",
1020 | "pygments_lexer": "ipython3",
1021 | "version": "3.7.12"
1022 | },
1023 | "papermill": {
1024 | "default_parameters": {},
1025 | "duration": 21615.694999,
1026 | "end_time": "2022-08-10T14:00:58.438655",
1027 | "environment_variables": {},
1028 | "exception": null,
1029 | "input_path": "__notebook__.ipynb",
1030 | "output_path": "__notebook__.ipynb",
1031 | "parameters": {},
1032 | "start_time": "2022-08-10T08:00:42.743656",
1033 | "version": "2.3.4"
1034 | }
1035 | },
1036 | "nbformat": 4,
1037 | "nbformat_minor": 5
1038 | }
1039 |
--------------------------------------------------------------------------------
/chapter_02/m5-train-day-1941-horizon-7.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "id": "c49a577e",
7 | "metadata": {
8 | "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
9 | "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
10 | "execution": {
11 | "iopub.execute_input": "2022-08-10T08:03:47.310183Z",
12 | "iopub.status.busy": "2022-08-10T08:03:47.308987Z",
13 | "iopub.status.idle": "2022-08-10T08:03:49.566379Z",
14 | "shell.execute_reply": "2022-08-10T08:03:49.564792Z"
15 | },
16 | "papermill": {
17 | "duration": 2.270562,
18 | "end_time": "2022-08-10T08:03:49.570545",
19 | "exception": false,
20 | "start_time": "2022-08-10T08:03:47.299983",
21 | "status": "completed"
22 | },
23 | "tags": []
24 | },
25 | "outputs": [
26 | {
27 | "data": {
28 | "text/html": [
29 | "\n"
50 | ],
51 | "text/plain": [
52 | ""
53 | ]
54 | },
55 | "metadata": {},
56 | "output_type": "display_data"
57 | }
58 | ],
59 | "source": [
60 | "import numpy as np\n",
61 | "import pandas as pd\n",
62 | "import os\n",
63 | "import random\n",
64 | "import math\n",
65 | "from decimal import Decimal as dec\n",
66 | "import datetime\n",
67 | "import time\n",
68 | "import gc\n",
69 | "import lightgbm as lgb\n",
70 | "import pickle\n",
71 | "\n",
72 | "import warnings\n",
73 | "warnings.filterwarnings(\"ignore\", category=UserWarning)"
74 | ]
75 | },
76 | {
77 | "cell_type": "code",
78 | "execution_count": 2,
79 | "id": "09ec7e9a",
80 | "metadata": {
81 | "execution": {
82 | "iopub.execute_input": "2022-08-10T08:03:49.587067Z",
83 | "iopub.status.busy": "2022-08-10T08:03:49.586143Z",
84 | "iopub.status.idle": "2022-08-10T08:07:27.606617Z",
85 | "shell.execute_reply": "2022-08-10T08:07:27.605332Z"
86 | },
87 | "papermill": {
88 | "duration": 218.032212,
89 | "end_time": "2022-08-10T08:07:27.609247",
90 | "exception": false,
91 | "start_time": "2022-08-10T08:03:49.577035",
92 | "status": "completed"
93 | },
94 | "tags": []
95 | },
96 | "outputs": [
97 | {
98 | "name": "stdout",
99 | "output_type": "stream",
100 | "text": [
101 | "Mem. usage decreased to 96.13 Mb (78.8% reduction)\n",
102 | "Mem. usage decreased to 143.53 Mb (31.2% reduction)\n",
103 | "Mem. usage decreased to 0.12 Mb (41.9% reduction)\n",
104 | "Mem. usage decreased to 2.09 Mb (84.5% reduction)\n"
105 | ]
106 | }
107 | ],
108 | "source": [
109 | "def reduce_mem_usage(df, verbose=True):\n",
110 | " numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n",
111 | " start_mem = df.memory_usage().sum() / 1024**2 \n",
112 | " for col in df.columns:\n",
113 | " col_type = df[col].dtypes\n",
114 | " if col_type in numerics:\n",
115 | " c_min = df[col].min()\n",
116 | " c_max = df[col].max()\n",
117 | " if str(col_type)[:3] == 'int':\n",
118 | " if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n",
119 | " df[col] = df[col].astype(np.int8)\n",
120 | " elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n",
121 | " df[col] = df[col].astype(np.int16)\n",
122 | " elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n",
123 | " df[col] = df[col].astype(np.int32)\n",
124 | " elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n",
125 | " df[col] = df[col].astype(np.int64) \n",
126 | " else:\n",
127 | " if c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n",
128 | " df[col] = df[col].astype(np.float32)\n",
129 | " else:\n",
130 | " df[col] = df[col].astype(np.float64) \n",
131 | " end_mem = df.memory_usage().sum() / 1024**2\n",
132 | " if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n",
133 | " return df\n",
134 | "\n",
135 | "def load_data():\n",
136 | " train_df = reduce_mem_usage(pd.read_csv(\"../input/m5-forecasting-accuracy/sales_train_evaluation.csv\"))\n",
137 | " prices_df = reduce_mem_usage(pd.read_csv(\"../input/m5-forecasting-accuracy/sell_prices.csv\"))\n",
138 | " calendar_df = reduce_mem_usage(pd.read_csv(\"../input/m5-forecasting-accuracy/calendar.csv\"))\n",
139 | " submission_df = reduce_mem_usage(pd.read_csv(\"../input/m5-forecasting-accuracy/sample_submission.csv\"))\n",
140 | " return train_df, prices_df, calendar_df, submission_df\n",
141 | "\n",
142 | "train_df, prices_df, calendar_df, submission_df = load_data()"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": 3,
148 | "id": "b14350bf",
149 | "metadata": {
150 | "execution": {
151 | "iopub.execute_input": "2022-08-10T08:07:27.623464Z",
152 | "iopub.status.busy": "2022-08-10T08:07:27.622214Z",
153 | "iopub.status.idle": "2022-08-10T08:07:27.636349Z",
154 | "shell.execute_reply": "2022-08-10T08:07:27.635308Z"
155 | },
156 | "papermill": {
157 | "duration": 0.023904,
158 | "end_time": "2022-08-10T08:07:27.638737",
159 | "exception": false,
160 | "start_time": "2022-08-10T08:07:27.614833",
161 | "status": "completed"
162 | },
163 | "tags": []
164 | },
165 | "outputs": [],
166 | "source": [
167 | "def generate_base_grid(train_df, end_train_day_x, predict_horizon):\n",
168 | " index_columns = ['id', 'item_id', 'dept_id', 'cat_id', 'store_id', 'state_id']\n",
169 | "\n",
170 | " grid_df = pd.melt(train_df, id_vars=index_columns, var_name='d', value_name='sales')\n",
171 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
172 | "\n",
173 | " grid_df['d_org'] = grid_df['d']\n",
174 | " grid_df['d'] = grid_df['d'].apply(lambda x: x[2:]).astype(np.int16)\n",
175 | "\n",
176 | " time_mask = (grid_df['d'] > end_train_day_x) & (grid_df['d'] <= end_train_day_x + predict_horizon)\n",
177 | " holdout_df = grid_df.loc[time_mask, [\"id\", \"d\", \"sales\"]].reset_index(drop=True)\n",
178 | " holdout_df.to_feather(f\"holdout_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
179 | " del(holdout_df)\n",
180 | " gc.collect()\n",
181 | "\n",
182 | " grid_df = grid_df[grid_df['d'] <= end_train_day_x]\n",
183 | " grid_df['d'] = grid_df['d_org']\n",
184 | " grid_df = grid_df.drop('d_org', axis=1)\n",
185 | "\n",
186 | " add_grid = pd.DataFrame()\n",
187 | " for i in range(predict_horizon):\n",
188 | " temp_df = train_df[index_columns]\n",
189 | " temp_df = temp_df.drop_duplicates()\n",
190 | " temp_df['d'] = 'd_' + str(end_train_day_x + i + 1)\n",
191 | " temp_df['sales'] = np.nan\n",
192 | " add_grid = pd.concat([add_grid, temp_df])\n",
193 | " \n",
194 | " grid_df = pd.concat([grid_df, add_grid])\n",
195 | " grid_df = grid_df.reset_index(drop=True)\n",
196 | " \n",
197 | " for col in index_columns:\n",
198 | " grid_df[col] = grid_df[col].astype('category')\n",
199 | " \n",
200 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
201 | " grid_df.to_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
202 | " del(grid_df)\n",
203 | " gc.collect()"
204 | ]
205 | },
206 | {
207 | "cell_type": "code",
208 | "execution_count": 4,
209 | "id": "b8c9f3b1",
210 | "metadata": {
211 | "execution": {
212 | "iopub.execute_input": "2022-08-10T08:07:27.651270Z",
213 | "iopub.status.busy": "2022-08-10T08:07:27.650538Z",
214 | "iopub.status.idle": "2022-08-10T08:07:27.662451Z",
215 | "shell.execute_reply": "2022-08-10T08:07:27.661146Z"
216 | },
217 | "papermill": {
218 | "duration": 0.021155,
219 | "end_time": "2022-08-10T08:07:27.665260",
220 | "exception": false,
221 | "start_time": "2022-08-10T08:07:27.644105",
222 | "status": "completed"
223 | },
224 | "tags": []
225 | },
226 | "outputs": [],
227 | "source": [
228 | "def merge_by_concat(df1, df2, merge_on):\n",
229 | " merged_gf = df1[merge_on]\n",
230 | " merged_gf = merged_gf.merge(df2, on=merge_on, how='left')\n",
231 | " new_columns = [col for col in list(merged_gf) if col not in merge_on]\n",
232 | " df1 = pd.concat([df1, merged_gf[new_columns]], axis=1)\n",
233 | " return df1\n",
234 | " \n",
235 | "def calc_release_week(prices_df, end_train_day_x, predict_horizon):\n",
236 | " index_columns = ['id', 'item_id', 'dept_id', 'cat_id', 'store_id', 'state_id']\n",
237 | " \n",
238 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
239 | " \n",
240 | " release_df = prices_df.groupby(['store_id', 'item_id'])['wm_yr_wk'].agg(['min']).reset_index()\n",
241 | " release_df.columns = ['store_id', 'item_id', 'release']\n",
242 | " \n",
243 | " grid_df = merge_by_concat(grid_df, release_df, ['store_id', 'item_id'])\n",
244 | " \n",
245 | " del release_df\n",
246 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
247 | " gc.collect()\n",
248 | " \n",
249 | " grid_df = merge_by_concat(grid_df, calendar_df[['wm_yr_wk', 'd']], ['d'])\n",
250 | " grid_df = grid_df.reset_index(drop=True)\n",
251 | "\n",
252 | " grid_df['release'] = grid_df['release'] - grid_df['release'].min()\n",
253 | " grid_df['release'] = grid_df['release'].astype(np.int16)\n",
254 | " \n",
255 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
256 | " grid_df.to_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
257 | " del(grid_df)\n",
258 | " gc.collect()"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": 5,
264 | "id": "8533915c",
265 | "metadata": {
266 | "execution": {
267 | "iopub.execute_input": "2022-08-10T08:07:27.677683Z",
268 | "iopub.status.busy": "2022-08-10T08:07:27.677121Z",
269 | "iopub.status.idle": "2022-08-10T08:07:27.693956Z",
270 | "shell.execute_reply": "2022-08-10T08:07:27.692392Z"
271 | },
272 | "papermill": {
273 | "duration": 0.02634,
274 | "end_time": "2022-08-10T08:07:27.696927",
275 | "exception": false,
276 | "start_time": "2022-08-10T08:07:27.670587",
277 | "status": "completed"
278 | },
279 | "tags": []
280 | },
281 | "outputs": [],
282 | "source": [
283 | "def generate_grid_price(prices_df, calendar_df, end_train_day_x, predict_horizon):\n",
284 | "\n",
285 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
286 | "\n",
287 | " prices_df['price_max'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('max')\n",
288 | " prices_df['price_min'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('min')\n",
289 | " prices_df['price_std'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('std')\n",
290 | " prices_df['price_mean'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('mean')\n",
291 | " prices_df['price_norm'] = prices_df['sell_price'] / prices_df['price_max']\n",
292 | " prices_df['price_nunique'] = prices_df.groupby(['store_id', 'item_id'])['sell_price'].transform('nunique')\n",
293 | " prices_df['item_nunique'] = prices_df.groupby(['store_id', 'sell_price'])['item_id'].transform('nunique')\n",
294 | "\n",
295 | " calendar_prices = calendar_df[['wm_yr_wk', 'month', 'year']]\n",
296 | " calendar_prices = calendar_prices.drop_duplicates(subset=['wm_yr_wk'])\n",
297 | " prices_df = prices_df.merge(calendar_prices[['wm_yr_wk', 'month', 'year']], on=['wm_yr_wk'], how='left')\n",
298 | " \n",
299 | " del calendar_prices\n",
300 | " gc.collect()\n",
301 | " \n",
302 | " prices_df['price_momentum'] = prices_df['sell_price'] / prices_df.groupby(['store_id', 'item_id'])[\n",
303 | " 'sell_price'].transform(lambda x: x.shift(1))\n",
304 | " prices_df['price_momentum_m'] = prices_df['sell_price'] / prices_df.groupby(['store_id', 'item_id', 'month'])[\n",
305 | " 'sell_price'].transform('mean')\n",
306 | " prices_df['price_momentum_y'] = prices_df['sell_price'] / prices_df.groupby(['store_id', 'item_id', 'year'])[\n",
307 | " 'sell_price'].transform('mean')\n",
308 | "\n",
309 | " prices_df['sell_price_cent'] = [math.modf(p)[0] for p in prices_df['sell_price']]\n",
310 | " prices_df['price_max_cent'] = [math.modf(p)[0] for p in prices_df['price_max']]\n",
311 | " prices_df['price_min_cent'] = [math.modf(p)[0] for p in prices_df['price_min']]\n",
312 | "\n",
313 | " del prices_df['month'], prices_df['year']\n",
314 | " prices_df = reduce_mem_usage(prices_df, verbose=False)\n",
315 | " gc.collect()\n",
316 | " \n",
317 | " original_columns = list(grid_df)\n",
318 | " grid_df = grid_df.merge(prices_df, on=['store_id', 'item_id', 'wm_yr_wk'], how='left')\n",
319 | " del(prices_df)\n",
320 | " gc.collect()\n",
321 | " \n",
322 | " keep_columns = [col for col in list(grid_df) if col not in original_columns]\n",
323 | " grid_df = grid_df[['id', 'd'] + keep_columns]\n",
324 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
325 | "\n",
326 | " grid_df.to_feather(f\"grid_price_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
327 | " del(grid_df)\n",
328 | " gc.collect()"
329 | ]
330 | },
331 | {
332 | "cell_type": "code",
333 | "execution_count": 6,
334 | "id": "22983152",
335 | "metadata": {
336 | "execution": {
337 | "iopub.execute_input": "2022-08-10T08:07:27.709081Z",
338 | "iopub.status.busy": "2022-08-10T08:07:27.708258Z",
339 | "iopub.status.idle": "2022-08-10T08:07:27.724899Z",
340 | "shell.execute_reply": "2022-08-10T08:07:27.723789Z"
341 | },
342 | "papermill": {
343 | "duration": 0.025505,
344 | "end_time": "2022-08-10T08:07:27.727465",
345 | "exception": false,
346 | "start_time": "2022-08-10T08:07:27.701960",
347 | "status": "completed"
348 | },
349 | "tags": []
350 | },
351 | "outputs": [],
352 | "source": [
353 | "def get_moon_phase(d): # 0=new, 4=full; 4 days/phase\n",
354 | " diff = datetime.datetime.strptime(d, '%Y-%m-%d') - datetime.datetime(2001, 1, 1)\n",
355 | " days = dec(diff.days) + (dec(diff.seconds) / dec(86400))\n",
356 | " lunations = dec(\"0.20439731\") + (days * dec(\"0.03386319269\"))\n",
357 | " phase_index = math.floor((lunations % dec(1) * dec(8)) + dec('0.5'))\n",
358 | " return int(phase_index) & 7\n",
359 | " \n",
360 | "def generate_grid_calendar(calendar_df, end_train_day_x, predict_horizon):\n",
361 | " \n",
362 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
363 | " grid_df = grid_df[['id', 'd']]\n",
364 | " gc.collect()\n",
365 | "\n",
366 | " calendar_df['moon'] = calendar_df.date.apply(get_moon_phase)\n",
367 | "\n",
368 | " # Merge calendar partly\n",
369 | " icols = ['date',\n",
370 | " 'd',\n",
371 | " 'event_name_1',\n",
372 | " 'event_type_1',\n",
373 | " 'event_name_2',\n",
374 | " 'event_type_2',\n",
375 | " 'snap_CA',\n",
376 | " 'snap_TX',\n",
377 | " 'snap_WI',\n",
378 | " 'moon',\n",
379 | " ]\n",
380 | "\n",
381 | " grid_df = grid_df.merge(calendar_df[icols], on=['d'], how='left')\n",
382 | "\n",
383 | " icols = ['event_name_1',\n",
384 | " 'event_type_1',\n",
385 | " 'event_name_2',\n",
386 | " 'event_type_2',\n",
387 | " 'snap_CA',\n",
388 | " 'snap_TX',\n",
389 | " 'snap_WI']\n",
390 | " \n",
391 | " for col in icols:\n",
392 | " grid_df[col] = grid_df[col].astype('category')\n",
393 | "\n",
394 | " grid_df['date'] = pd.to_datetime(grid_df['date'])\n",
395 | "\n",
396 | " grid_df['tm_d'] = grid_df['date'].dt.day.astype(np.int8)\n",
397 | " grid_df['tm_w'] = grid_df['date'].dt.isocalendar().week.astype(np.int8)\n",
398 | " grid_df['tm_m'] = grid_df['date'].dt.month.astype(np.int8)\n",
399 | " grid_df['tm_y'] = grid_df['date'].dt.year\n",
400 | " grid_df['tm_y'] = (grid_df['tm_y'] - grid_df['tm_y'].min()).astype(np.int8)\n",
401 | " grid_df['tm_wm'] = grid_df['tm_d'].apply(lambda x: math.ceil(x / 7)).astype(np.int8)\n",
402 | "\n",
403 | " grid_df['tm_dw'] = grid_df['date'].dt.dayofweek.astype(np.int8)\n",
404 | " grid_df['tm_w_end'] = (grid_df['tm_dw'] >= 5).astype(np.int8)\n",
405 | " \n",
406 | " del(grid_df['date'])\n",
407 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
408 | " grid_df.to_feather(f\"grid_calendar_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
409 | " \n",
410 | " del(grid_df)\n",
411 | " del(calendar_df)\n",
412 | " gc.collect()"
413 | ]
414 | },
415 | {
416 | "cell_type": "code",
417 | "execution_count": 7,
418 | "id": "a97eff6c",
419 | "metadata": {
420 | "execution": {
421 | "iopub.execute_input": "2022-08-10T08:07:27.739635Z",
422 | "iopub.status.busy": "2022-08-10T08:07:27.738949Z",
423 | "iopub.status.idle": "2022-08-10T08:07:27.745189Z",
424 | "shell.execute_reply": "2022-08-10T08:07:27.744243Z"
425 | },
426 | "papermill": {
427 | "duration": 0.015095,
428 | "end_time": "2022-08-10T08:07:27.747505",
429 | "exception": false,
430 | "start_time": "2022-08-10T08:07:27.732410",
431 | "status": "completed"
432 | },
433 | "tags": []
434 | },
435 | "outputs": [],
436 | "source": [
437 | "def modify_grid_base(end_train_day_x, predict_horizon):\n",
438 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
439 | " grid_df['d'] = grid_df['d'].apply(lambda x: x[2:]).astype(np.int16)\n",
440 | " del grid_df['wm_yr_wk']\n",
441 | " \n",
442 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
443 | " grid_df.to_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
444 | " \n",
445 | " del(grid_df)\n",
446 | " gc.collect()"
447 | ]
448 | },
449 | {
450 | "cell_type": "code",
451 | "execution_count": 8,
452 | "id": "386e5140",
453 | "metadata": {
454 | "execution": {
455 | "iopub.execute_input": "2022-08-10T08:07:27.760213Z",
456 | "iopub.status.busy": "2022-08-10T08:07:27.759091Z",
457 | "iopub.status.idle": "2022-08-10T08:07:27.771666Z",
458 | "shell.execute_reply": "2022-08-10T08:07:27.770691Z"
459 | },
460 | "papermill": {
461 | "duration": 0.021476,
462 | "end_time": "2022-08-10T08:07:27.774074",
463 | "exception": false,
464 | "start_time": "2022-08-10T08:07:27.752598",
465 | "status": "completed"
466 | },
467 | "tags": []
468 | },
469 | "outputs": [],
470 | "source": [
471 | "def generate_lag_feature(end_train_day_x, predict_horizon):\n",
472 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
473 | " grid_df = grid_df[['id', 'd', 'sales']]\n",
474 | " \n",
475 | " num_lag_day_list = []\n",
476 | " num_lag_day = 15\n",
477 | " for col in range(predict_horizon, predict_horizon + num_lag_day):\n",
478 | " num_lag_day_list.append(col)\n",
479 | " \n",
480 | " num_rolling_day_list = [7, 14, 30, 60, 180]\n",
481 | " num_shift_rolling_day_list = []\n",
482 | " for num_shift_day in [1, 7, 14]:\n",
483 | " for num_rolling_day in [7, 14, 30, 60]:\n",
484 | " num_shift_rolling_day_list.append([num_shift_day, num_rolling_day])\n",
485 | " \n",
486 | " grid_df = grid_df.assign(**{\n",
487 | " '{}_lag_{}'.format(col, l): grid_df.groupby(['id'])['sales'].transform(lambda x: x.shift(l))\n",
488 | " for l in num_lag_day_list\n",
489 | " })\n",
490 | "\n",
491 | " for col in list(grid_df):\n",
492 | " if 'lag' in col:\n",
493 | " grid_df[col] = grid_df[col].astype(np.float16)\n",
494 | "\n",
495 | " for num_rolling_day in num_rolling_day_list:\n",
496 | " grid_df['rolling_mean_' + str(num_rolling_day)] = grid_df.groupby(['id'])['sales'].transform(\n",
497 | " lambda x: x.shift(predict_horizon).rolling(num_rolling_day).mean()).astype(np.float16)\n",
498 | " grid_df['rolling_std_' + str(num_rolling_day)] = grid_df.groupby(['id'])['sales'].transform(\n",
499 | " lambda x: x.shift(predict_horizon).rolling(num_rolling_day).std()).astype(np.float16)\n",
500 | "\n",
501 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
502 | " grid_df.to_feather(f\"lag_feature_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
503 | " \n",
504 | " del(grid_df)\n",
505 | " gc.collect()\n"
506 | ]
507 | },
508 | {
509 | "cell_type": "code",
510 | "execution_count": 9,
511 | "id": "6f51d175",
512 | "metadata": {
513 | "execution": {
514 | "iopub.execute_input": "2022-08-10T08:07:27.786352Z",
515 | "iopub.status.busy": "2022-08-10T08:07:27.785573Z",
516 | "iopub.status.idle": "2022-08-10T08:07:27.797676Z",
517 | "shell.execute_reply": "2022-08-10T08:07:27.796400Z"
518 | },
519 | "papermill": {
520 | "duration": 0.021819,
521 | "end_time": "2022-08-10T08:07:27.800831",
522 | "exception": false,
523 | "start_time": "2022-08-10T08:07:27.779012",
524 | "status": "completed"
525 | },
526 | "tags": []
527 | },
528 | "outputs": [],
529 | "source": [
530 | "def generate_target_encoding_feature(end_train_day_x, predict_horizon):\n",
531 | "\n",
532 | " grid_df = pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
533 | " \n",
534 | " grid_df.loc[grid_df['d'] > (end_train_day_x - predict_horizon), 'sales'] = np.nan\n",
535 | " base_cols = list(grid_df)\n",
536 | "\n",
537 | " icols = [\n",
538 | " ['state_id'],\n",
539 | " ['store_id'],\n",
540 | " ['cat_id'],\n",
541 | " ['dept_id'],\n",
542 | " ['state_id', 'cat_id'],\n",
543 | " ['state_id', 'dept_id'],\n",
544 | " ['store_id', 'cat_id'],\n",
545 | " ['store_id', 'dept_id'],\n",
546 | " ['item_id'],\n",
547 | " ['item_id', 'state_id'],\n",
548 | " ['item_id', 'store_id']\n",
549 | " ]\n",
550 | "\n",
551 | " for col in icols:\n",
552 | " col_name = '_' + '_'.join(col) + '_'\n",
553 | " grid_df['enc' + col_name + 'mean'] = grid_df.groupby(col)['sales'].transform('mean').astype(\n",
554 | " np.float16)\n",
555 | " grid_df['enc' + col_name + 'std'] = grid_df.groupby(col)['sales'].transform('std').astype(\n",
556 | " np.float16)\n",
557 | "\n",
558 | " keep_cols = [col for col in list(grid_df) if col not in base_cols]\n",
559 | " grid_df = grid_df[['id', 'd'] + keep_cols]\n",
560 | "\n",
561 | " grid_df = reduce_mem_usage(grid_df, verbose=False)\n",
562 | " grid_df.to_feather(f\"target_encoding_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
563 | " \n",
564 | " del(grid_df)\n",
565 | " gc.collect()"
566 | ]
567 | },
568 | {
569 | "cell_type": "code",
570 | "execution_count": 10,
571 | "id": "a97ebc47",
572 | "metadata": {
573 | "execution": {
574 | "iopub.execute_input": "2022-08-10T08:07:27.812980Z",
575 | "iopub.status.busy": "2022-08-10T08:07:27.812568Z",
576 | "iopub.status.idle": "2022-08-10T08:07:27.826638Z",
577 | "shell.execute_reply": "2022-08-10T08:07:27.825017Z"
578 | },
579 | "papermill": {
580 | "duration": 0.023284,
581 | "end_time": "2022-08-10T08:07:27.829248",
582 | "exception": false,
583 | "start_time": "2022-08-10T08:07:27.805964",
584 | "status": "completed"
585 | },
586 | "tags": []
587 | },
588 | "outputs": [],
589 | "source": [
590 | "def assemble_grid_by_store(train_df, end_train_day_x, predict_horizon):\n",
591 | " grid_df = pd.concat([pd.read_feather(f\"grid_df_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\"),\n",
592 | " pd.read_feather(f\"grid_price_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\").iloc[:, 2:],\n",
593 | " pd.read_feather(f\"grid_calendar_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\").iloc[:, 2:]],\n",
594 | " axis=1)\n",
595 | " gc.collect()\n",
596 | " store_id_set_list = list(train_df['store_id'].unique())\n",
597 | "\n",
598 | " index_store = dict()\n",
599 | " for store_id in store_id_set_list:\n",
600 | " extract = grid_df[grid_df['store_id'] == store_id]\n",
601 | " index_store[store_id] = extract.index.to_numpy()\n",
602 | " extract = extract.reset_index(drop=True)\n",
603 | " extract.to_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
604 | "\n",
605 | " del(grid_df)\n",
606 | " gc.collect()\n",
607 | " \n",
608 | " mean_features = [\n",
609 | " 'enc_cat_id_mean', 'enc_cat_id_std',\n",
610 | " 'enc_dept_id_mean', 'enc_dept_id_std',\n",
611 | " 'enc_item_id_mean', 'enc_item_id_std'\n",
612 | " ]\n",
613 | " df2 = pd.read_feather(f\"target_encoding_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")[mean_features]\n",
614 | "\n",
615 | " for store_id in store_id_set_list:\n",
616 | " df = pd.read_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
617 | " df = pd.concat([df, df2[df2.index.isin(index_store[store_id])].reset_index(drop=True)], axis=1)\n",
618 | " df.to_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
619 | "\n",
620 | " del(df2)\n",
621 | " gc.collect()\n",
622 | " \n",
623 | " df3 = pd.read_feather(f\"lag_feature_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\").iloc[:, 3:]\n",
624 | "\n",
625 | " for store_id in store_id_set_list:\n",
626 | " df = pd.read_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
627 | " df = pd.concat([df, df3[df3.index.isin(index_store[store_id])].reset_index(drop=True)], axis=1)\n",
628 | " df.to_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
629 | "\n",
630 | " del(df3)\n",
631 | " del(store_id_set_list)\n",
632 | " gc.collect()\n"
633 | ]
634 | },
635 | {
636 | "cell_type": "code",
637 | "execution_count": 11,
638 | "id": "99c401a3",
639 | "metadata": {
640 | "execution": {
641 | "iopub.execute_input": "2022-08-10T08:07:27.840997Z",
642 | "iopub.status.busy": "2022-08-10T08:07:27.840613Z",
643 | "iopub.status.idle": "2022-08-10T08:07:27.848549Z",
644 | "shell.execute_reply": "2022-08-10T08:07:27.847005Z"
645 | },
646 | "papermill": {
647 | "duration": 0.01682,
648 | "end_time": "2022-08-10T08:07:27.851116",
649 | "exception": false,
650 | "start_time": "2022-08-10T08:07:27.834296",
651 | "status": "completed"
652 | },
653 | "tags": []
654 | },
655 | "outputs": [],
656 | "source": [
657 | "def load_grid_by_store(end_train_day_x, predict_horizon, store_id):\n",
658 | " df = pd.read_feather(f\"grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + predict_horizon}.feather\")\n",
659 | " \n",
660 | " remove_features = ['id', 'state_id', 'store_id', 'date', 'wm_yr_wk', 'd', 'sales']\n",
661 | " enable_features = [col for col in list(df) if col not in remove_features]\n",
662 | " df = df[['id', 'd', 'sales'] + enable_features]\n",
663 | " df = reduce_mem_usage(df, verbose=False)\n",
664 | " gc.collect()\n",
665 | " \n",
666 | " return df, enable_features"
667 | ]
668 | },
669 | {
670 | "cell_type": "code",
671 | "execution_count": 12,
672 | "id": "4963ee96",
673 | "metadata": {
674 | "execution": {
675 | "iopub.execute_input": "2022-08-10T08:07:27.862855Z",
676 | "iopub.status.busy": "2022-08-10T08:07:27.862469Z",
677 | "iopub.status.idle": "2022-08-10T08:07:27.880802Z",
678 | "shell.execute_reply": "2022-08-10T08:07:27.879234Z"
679 | },
680 | "papermill": {
681 | "duration": 0.02759,
682 | "end_time": "2022-08-10T08:07:27.883767",
683 | "exception": false,
684 | "start_time": "2022-08-10T08:07:27.856177",
685 | "status": "completed"
686 | },
687 | "tags": []
688 | },
689 | "outputs": [],
690 | "source": [
691 | "def train(train_df, seed, end_train_day_x, predict_horizon):\n",
692 | " \n",
693 | " lgb_params = {\n",
694 | " 'boosting_type': 'goss',\n",
695 | " 'objective': 'tweedie',\n",
696 | " 'tweedie_variance_power': 1.1,\n",
697 | " 'metric': 'rmse',\n",
698 | " #'subsample': 0.5,\n",
699 | " #'subsample_freq': 1,\n",
700 | " 'learning_rate': 0.03,\n",
701 | " 'num_leaves': 2 ** 11 - 1,\n",
702 | " 'min_data_in_leaf': 2 ** 12 - 1,\n",
703 | " 'feature_fraction': 0.5,\n",
704 | " 'max_bin': 100,\n",
705 | " 'boost_from_average': False,\n",
706 | " 'num_boost_round': 1400,\n",
707 | " 'verbose': -1,\n",
708 | " 'num_threads': os.cpu_count(),\n",
709 | " 'force_row_wise': True,\n",
710 | " }\n",
711 | "\n",
712 | " random.seed(seed)\n",
713 | " np.random.seed(seed)\n",
714 | " os.environ['PYTHONHASHSEED'] = str(seed)\n",
715 | " \n",
716 | " lgb_params['seed'] = seed\n",
717 | "\n",
718 | " store_id_set_list = list(train_df['store_id'].unique())\n",
719 | " print(f\"training stores: {store_id_set_list}\")\n",
720 | " \n",
721 | " feature_importance_all_df = pd.DataFrame()\n",
722 | " for store_index, store_id in enumerate(store_id_set_list):\n",
723 | " print(f'now training {store_id} store')\n",
724 | "\n",
725 | " grid_df, enable_features = load_grid_by_store(end_train_day_x, predict_horizon, store_id)\n",
726 | "\n",
727 | " train_mask = grid_df['d'] <= end_train_day_x\n",
728 | " valid_mask = train_mask & (grid_df['d'] > (end_train_day_x - predict_horizon))\n",
729 | " preds_mask = grid_df['d'] > (end_train_day_x - 100)\n",
730 | "\n",
731 | " train_data = lgb.Dataset(grid_df[train_mask][enable_features],\n",
732 | " label=grid_df[train_mask]['sales'])\n",
733 | "\n",
734 | " valid_data = lgb.Dataset(grid_df[valid_mask][enable_features],\n",
735 | " label=grid_df[valid_mask]['sales'])\n",
736 | "\n",
737 | "\n",
738 | " # Saving part of the dataset for later predictions\n",
739 | " # Removing features that we need to calculate recursively\n",
740 | " grid_df = grid_df[preds_mask].reset_index(drop=True)\n",
741 | " grid_df.to_feather(f'test_{store_id}_{predict_horizon}.feather')\n",
742 | " del(grid_df)\n",
743 | " gc.collect()\n",
744 | " \n",
745 | " estimator = lgb.train(lgb_params,\n",
746 | " train_data,\n",
747 | " valid_sets=[valid_data],\n",
748 | " callbacks=[lgb.log_evaluation(period=100, show_stdv=False)],\n",
749 | " )\n",
750 | "\n",
751 | " model_name = str(f'lgb_model_{store_id}_{predict_horizon}.bin')\n",
752 | " feature_importance_store_df = pd.DataFrame(sorted(zip(enable_features, estimator.feature_importance())),\n",
753 | " columns=['feature_name', 'importance'])\n",
754 | " feature_importance_store_df = feature_importance_store_df.sort_values('importance', ascending=False)\n",
755 | " feature_importance_store_df['store_id'] = store_id\n",
756 | " feature_importance_store_df.to_csv(f'feature_importance_{store_id}_{predict_horizon}.csv', index=False)\n",
757 | " feature_importance_all_df = pd.concat([feature_importance_all_df, feature_importance_store_df])\n",
758 | " pickle.dump(estimator, open(model_name, 'wb'))\n",
759 | "\n",
760 | " del([train_data, valid_data, estimator])\n",
761 | " gc.collect()\n",
762 | "\n",
763 | " feature_importance_all_df.to_csv(f'feature_importance_all_{predict_horizon}.csv', index=False)\n",
764 | " feature_importance_agg_df = feature_importance_all_df.groupby(\n",
765 | " 'feature_name')['importance'].agg(['mean', 'std']).reset_index()\n",
766 | " feature_importance_agg_df.columns = ['feature_name', 'importance_mean', 'importance_std']\n",
767 | " feature_importance_agg_df = feature_importance_agg_df.sort_values('importance_mean', ascending=False)\n",
768 | " feature_importance_agg_df.to_csv(f'feature_importance_agg_{predict_horizon}.csv', index=False)"
769 | ]
770 | },
771 | {
772 | "cell_type": "code",
773 | "execution_count": 13,
774 | "id": "554ece3a",
775 | "metadata": {
776 | "execution": {
777 | "iopub.execute_input": "2022-08-10T08:07:27.897066Z",
778 | "iopub.status.busy": "2022-08-10T08:07:27.895859Z",
779 | "iopub.status.idle": "2022-08-10T08:07:27.904925Z",
780 | "shell.execute_reply": "2022-08-10T08:07:27.903387Z"
781 | },
782 | "papermill": {
783 | "duration": 0.01868,
784 | "end_time": "2022-08-10T08:07:27.907791",
785 | "exception": false,
786 | "start_time": "2022-08-10T08:07:27.889111",
787 | "status": "completed"
788 | },
789 | "tags": []
790 | },
791 | "outputs": [],
792 | "source": [
793 | "def train_pipeline(train_df, prices_df, calendar_df, end_train_day_x_list, prediction_horizon_list):\n",
794 | " \n",
795 | " for end_train_day_x in end_train_day_x_list:\n",
796 | " \n",
797 | " for predict_horizon in prediction_horizon_list:\n",
798 | " \n",
799 | " print(f\"end training point day: {end_train_day_x} - prediction horizon: {predict_horizon} days\")\n",
800 | "\n",
801 | " # Data preparation\n",
802 | " generate_base_grid(train_df, end_train_day_x, predict_horizon)\n",
803 | " calc_release_week(prices_df, end_train_day_x, predict_horizon)\n",
804 | " generate_grid_price(prices_df, calendar_df, end_train_day_x, predict_horizon)\n",
805 | " generate_grid_calendar(calendar_df, end_train_day_x, predict_horizon)\n",
806 | " modify_grid_base(end_train_day_x, predict_horizon)\n",
807 | " generate_lag_feature(end_train_day_x, predict_horizon)\n",
808 | " generate_target_encoding_feature(end_train_day_x, predict_horizon)\n",
809 | " assemble_grid_by_store(train_df, end_train_day_x, predict_horizon)\n",
810 | "\n",
811 | " # Modelling\n",
812 | " train(train_df, seed, end_train_day_x, predict_horizon)\n",
813 | " "
814 | ]
815 | },
816 | {
817 | "cell_type": "code",
818 | "execution_count": 14,
819 | "id": "410f73df",
820 | "metadata": {
821 | "execution": {
822 | "iopub.execute_input": "2022-08-10T08:07:27.920150Z",
823 | "iopub.status.busy": "2022-08-10T08:07:27.919161Z",
824 | "iopub.status.idle": "2022-08-10T14:27:41.322208Z",
825 | "shell.execute_reply": "2022-08-10T14:27:41.319779Z"
826 | },
827 | "papermill": {
828 | "duration": 22813.414584,
829 | "end_time": "2022-08-10T14:27:41.327465",
830 | "exception": false,
831 | "start_time": "2022-08-10T08:07:27.912881",
832 | "status": "completed"
833 | },
834 | "tags": []
835 | },
836 | "outputs": [
837 | {
838 | "name": "stdout",
839 | "output_type": "stream",
840 | "text": [
841 | "end training point day: 1941 - prediction horizon: 7 days\n",
842 | "training stores: ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n",
843 | "now training CA_1 store\n",
844 | "[100]\tvalid_0's rmse: 2.11961\n",
845 | "[200]\tvalid_0's rmse: 2.08594\n",
846 | "[300]\tvalid_0's rmse: 2.07158\n",
847 | "[400]\tvalid_0's rmse: 2.06135\n",
848 | "[500]\tvalid_0's rmse: 2.0516\n",
849 | "[600]\tvalid_0's rmse: 2.04147\n",
850 | "[700]\tvalid_0's rmse: 2.03248\n",
851 | "[800]\tvalid_0's rmse: 2.02314\n",
852 | "[900]\tvalid_0's rmse: 2.01467\n",
853 | "[1000]\tvalid_0's rmse: 2.0082\n",
854 | "[1100]\tvalid_0's rmse: 2.00236\n",
855 | "[1200]\tvalid_0's rmse: 1.99554\n",
856 | "[1300]\tvalid_0's rmse: 1.98872\n",
857 | "[1400]\tvalid_0's rmse: 1.98268\n",
858 | "now training CA_2 store\n",
859 | "[100]\tvalid_0's rmse: 1.93827\n",
860 | "[200]\tvalid_0's rmse: 1.8924\n",
861 | "[300]\tvalid_0's rmse: 1.88216\n",
862 | "[400]\tvalid_0's rmse: 1.8741\n",
863 | "[500]\tvalid_0's rmse: 1.86848\n",
864 | "[600]\tvalid_0's rmse: 1.86395\n",
865 | "[700]\tvalid_0's rmse: 1.85787\n",
866 | "[800]\tvalid_0's rmse: 1.85276\n",
867 | "[900]\tvalid_0's rmse: 1.84744\n",
868 | "[1000]\tvalid_0's rmse: 1.84233\n",
869 | "[1100]\tvalid_0's rmse: 1.83787\n",
870 | "[1200]\tvalid_0's rmse: 1.83283\n",
871 | "[1300]\tvalid_0's rmse: 1.82886\n",
872 | "[1400]\tvalid_0's rmse: 1.82393\n",
873 | "now training CA_3 store\n",
874 | "[100]\tvalid_0's rmse: 2.55821\n",
875 | "[200]\tvalid_0's rmse: 2.5251\n",
876 | "[300]\tvalid_0's rmse: 2.49299\n",
877 | "[400]\tvalid_0's rmse: 2.47561\n",
878 | "[500]\tvalid_0's rmse: 2.45753\n",
879 | "[600]\tvalid_0's rmse: 2.44637\n",
880 | "[700]\tvalid_0's rmse: 2.43447\n",
881 | "[800]\tvalid_0's rmse: 2.42418\n",
882 | "[900]\tvalid_0's rmse: 2.41244\n",
883 | "[1000]\tvalid_0's rmse: 2.40177\n",
884 | "[1100]\tvalid_0's rmse: 2.39844\n",
885 | "[1200]\tvalid_0's rmse: 2.38979\n",
886 | "[1300]\tvalid_0's rmse: 2.38049\n",
887 | "[1400]\tvalid_0's rmse: 2.37056\n",
888 | "now training CA_4 store\n",
889 | "[100]\tvalid_0's rmse: 1.4716\n",
890 | "[200]\tvalid_0's rmse: 1.46235\n",
891 | "[300]\tvalid_0's rmse: 1.45692\n",
892 | "[400]\tvalid_0's rmse: 1.45259\n",
893 | "[500]\tvalid_0's rmse: 1.44899\n",
894 | "[600]\tvalid_0's rmse: 1.44584\n",
895 | "[700]\tvalid_0's rmse: 1.44156\n",
896 | "[800]\tvalid_0's rmse: 1.43793\n",
897 | "[900]\tvalid_0's rmse: 1.43426\n",
898 | "[1000]\tvalid_0's rmse: 1.43048\n",
899 | "[1100]\tvalid_0's rmse: 1.42657\n",
900 | "[1200]\tvalid_0's rmse: 1.42317\n",
901 | "[1300]\tvalid_0's rmse: 1.4202\n",
902 | "[1400]\tvalid_0's rmse: 1.41725\n",
903 | "now training TX_1 store\n",
904 | "[100]\tvalid_0's rmse: 1.74942\n",
905 | "[200]\tvalid_0's rmse: 1.71853\n",
906 | "[300]\tvalid_0's rmse: 1.70859\n",
907 | "[400]\tvalid_0's rmse: 1.69937\n",
908 | "[500]\tvalid_0's rmse: 1.69244\n",
909 | "[600]\tvalid_0's rmse: 1.68681\n",
910 | "[700]\tvalid_0's rmse: 1.68112\n",
911 | "[800]\tvalid_0's rmse: 1.67622\n",
912 | "[900]\tvalid_0's rmse: 1.67036\n",
913 | "[1000]\tvalid_0's rmse: 1.66465\n",
914 | "[1100]\tvalid_0's rmse: 1.65869\n",
915 | "[1200]\tvalid_0's rmse: 1.65302\n",
916 | "[1300]\tvalid_0's rmse: 1.64834\n",
917 | "[1400]\tvalid_0's rmse: 1.64406\n",
918 | "now training TX_2 store\n",
919 | "[100]\tvalid_0's rmse: 1.74093\n",
920 | "[200]\tvalid_0's rmse: 1.7194\n",
921 | "[300]\tvalid_0's rmse: 1.71397\n",
922 | "[400]\tvalid_0's rmse: 1.70955\n",
923 | "[500]\tvalid_0's rmse: 1.70409\n",
924 | "[600]\tvalid_0's rmse: 1.69892\n",
925 | "[700]\tvalid_0's rmse: 1.69506\n",
926 | "[800]\tvalid_0's rmse: 1.69203\n",
927 | "[900]\tvalid_0's rmse: 1.68986\n",
928 | "[1000]\tvalid_0's rmse: 1.6856\n",
929 | "[1100]\tvalid_0's rmse: 1.68255\n",
930 | "[1200]\tvalid_0's rmse: 1.67991\n",
931 | "[1300]\tvalid_0's rmse: 1.67587\n",
932 | "[1400]\tvalid_0's rmse: 1.67447\n",
933 | "now training TX_3 store\n",
934 | "[100]\tvalid_0's rmse: 1.87038\n",
935 | "[200]\tvalid_0's rmse: 1.82816\n",
936 | "[300]\tvalid_0's rmse: 1.81563\n",
937 | "[400]\tvalid_0's rmse: 1.80955\n",
938 | "[500]\tvalid_0's rmse: 1.80216\n",
939 | "[600]\tvalid_0's rmse: 1.79559\n",
940 | "[700]\tvalid_0's rmse: 1.78854\n",
941 | "[800]\tvalid_0's rmse: 1.78229\n",
942 | "[900]\tvalid_0's rmse: 1.77731\n",
943 | "[1000]\tvalid_0's rmse: 1.77219\n",
944 | "[1100]\tvalid_0's rmse: 1.76657\n",
945 | "[1200]\tvalid_0's rmse: 1.76191\n",
946 | "[1300]\tvalid_0's rmse: 1.75738\n",
947 | "[1400]\tvalid_0's rmse: 1.75304\n",
948 | "now training WI_1 store\n",
949 | "[100]\tvalid_0's rmse: 1.60254\n",
950 | "[200]\tvalid_0's rmse: 1.5855\n",
951 | "[300]\tvalid_0's rmse: 1.57873\n",
952 | "[400]\tvalid_0's rmse: 1.57396\n",
953 | "[500]\tvalid_0's rmse: 1.56776\n",
954 | "[600]\tvalid_0's rmse: 1.56346\n",
955 | "[700]\tvalid_0's rmse: 1.56\n",
956 | "[800]\tvalid_0's rmse: 1.55477\n",
957 | "[900]\tvalid_0's rmse: 1.55072\n",
958 | "[1000]\tvalid_0's rmse: 1.54603\n",
959 | "[1100]\tvalid_0's rmse: 1.54153\n",
960 | "[1200]\tvalid_0's rmse: 1.53808\n",
961 | "[1300]\tvalid_0's rmse: 1.53512\n",
962 | "[1400]\tvalid_0's rmse: 1.53214\n",
963 | "now training WI_2 store\n",
964 | "[100]\tvalid_0's rmse: 2.28903\n",
965 | "[200]\tvalid_0's rmse: 2.26415\n",
966 | "[300]\tvalid_0's rmse: 2.2559\n",
967 | "[400]\tvalid_0's rmse: 2.24477\n",
968 | "[500]\tvalid_0's rmse: 2.23688\n",
969 | "[600]\tvalid_0's rmse: 2.22695\n",
970 | "[700]\tvalid_0's rmse: 2.21777\n",
971 | "[800]\tvalid_0's rmse: 2.20965\n",
972 | "[900]\tvalid_0's rmse: 2.20261\n",
973 | "[1000]\tvalid_0's rmse: 2.19455\n",
974 | "[1100]\tvalid_0's rmse: 2.18845\n",
975 | "[1200]\tvalid_0's rmse: 2.17985\n",
976 | "[1300]\tvalid_0's rmse: 2.17433\n",
977 | "[1400]\tvalid_0's rmse: 2.16629\n",
978 | "now training WI_3 store\n",
979 | "[100]\tvalid_0's rmse: 1.78742\n",
980 | "[200]\tvalid_0's rmse: 1.74242\n",
981 | "[300]\tvalid_0's rmse: 1.73532\n",
982 | "[400]\tvalid_0's rmse: 1.72769\n",
983 | "[500]\tvalid_0's rmse: 1.72285\n",
984 | "[600]\tvalid_0's rmse: 1.7178\n",
985 | "[700]\tvalid_0's rmse: 1.71326\n",
986 | "[800]\tvalid_0's rmse: 1.70875\n",
987 | "[900]\tvalid_0's rmse: 1.7037\n",
988 | "[1000]\tvalid_0's rmse: 1.7018\n",
989 | "[1100]\tvalid_0's rmse: 1.69844\n",
990 | "[1200]\tvalid_0's rmse: 1.6947\n",
991 | "[1300]\tvalid_0's rmse: 1.68921\n",
992 | "[1400]\tvalid_0's rmse: 1.68565\n"
993 | ]
994 | }
995 | ],
996 | "source": [
997 | "end_train_day_x_list = [1941] # [1941, 1913, 1885, 1857, 1829, 1577]\n",
998 | "prediction_horizon_list = [7] # [7, 14, 21, 28]\n",
999 | "seed = 42\n",
1000 | "\n",
1001 | "train_pipeline(train_df, prices_df, calendar_df, end_train_day_x_list, prediction_horizon_list)"
1002 | ]
1003 | }
1004 | ],
1005 | "metadata": {
1006 | "kernelspec": {
1007 | "display_name": "Python 3",
1008 | "language": "python",
1009 | "name": "python3"
1010 | },
1011 | "language_info": {
1012 | "codemirror_mode": {
1013 | "name": "ipython",
1014 | "version": 3
1015 | },
1016 | "file_extension": ".py",
1017 | "mimetype": "text/x-python",
1018 | "name": "python",
1019 | "nbconvert_exporter": "python",
1020 | "pygments_lexer": "ipython3",
1021 | "version": "3.7.12"
1022 | },
1023 | "papermill": {
1024 | "default_parameters": {},
1025 | "duration": 23046.125553,
1026 | "end_time": "2022-08-10T14:27:43.600007",
1027 | "environment_variables": {},
1028 | "exception": null,
1029 | "input_path": "__notebook__.ipynb",
1030 | "output_path": "__notebook__.ipynb",
1031 | "parameters": {},
1032 | "start_time": "2022-08-10T08:03:37.474454",
1033 | "version": "2.3.4"
1034 | }
1035 | },
1036 | "nbformat": 4,
1037 | "nbformat_minor": 5
1038 | }
1039 |
--------------------------------------------------------------------------------
/chapter_02/m5-uncertainty-predict-quantile-with-gcp.ipynb:
--------------------------------------------------------------------------------
1 | {"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!mkdir /root/.kaggle","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import json\nwith open(\"/root/.kaggle/kaggle.json\", \"w\") as kaggle_json:\n json.dump({\"username\":\"YOUR USERNAME\",\"key\":\"YOUR KEY\"}, kaggle_json)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!chmod 600 /root/.kaggle/kaggle.json","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir ../input/m5-train-day-1941-horizon-7\n!kaggle kernels output lucamassaron/m5-train-day-1941-horizon-7 -p ../input/m5-train-day-1941-horizon-7/","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir ../input/m5-train-day-1941-horizon-14\n!kaggle kernels output lucamassaron/m5-train-day-1941-horizon-14 -p ../input/m5-train-day-1941-horizon-14/","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir ../input/m5-train-day-1941-horizon-21\n!kaggle kernels output lucamassaron/m5-train-day-1941-horizon-21 -p ../input/m5-train-day-1941-horizon-21/","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir ../input/m5-train-day-1941-horizon-28\n!kaggle kernels output lucamassaron/m5-train-day-1941-horizon-28 -p ../input/m5-train-day-1941-horizon-28/","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ls ../input/","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install gluonts --quiet","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport random\nimport math\nfrom decimal import Decimal as dec\nimport datetime\nimport time\nimport gc\nimport lightgbm as lgb\nimport pickle\n\nfrom gluonts.model.rotbaum._model import LSF\n\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=UserWarning)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def predict_uncertainty(end_train_day_x_list, prediction_horizon_list, min_bin_size, quantile):\n \n store_id_set_list = ['CA_1', 'CA_2', 'CA_3', 'CA_4', 'TX_1', 'TX_2', 'TX_3', 'WI_1', 'WI_2', 'WI_3']\n \n print(f\"predicting quantile={quantile}\")\n pred_v_all_df = list()\n\n for end_train_day_x in end_train_day_x_list:\n previous_prediction_horizon = 0\n for prediction_horizon in prediction_horizon_list:\n print(f\"prediction horizon=+{prediction_horizon}\")\n notebook_name = f\"../input/m5-train-day-{end_train_day_x}-horizon-{prediction_horizon}\"\n\n pred_v_df = pd.DataFrame()\n\n for store_index, store_id in enumerate(store_id_set_list):\n\n model_path = str(f'{notebook_name}/lgb_model_{store_id}_{prediction_horizon}.bin')\n print(f'loading {model_path}')\n estimator = pickle.load(open(model_path, 'rb'))\n base_test = pd.read_feather(f\"{notebook_name}/test_{store_id}_{prediction_horizon}.feather\")\n enable_features = [col for col in base_test.columns if col not in ['id', 'd', 'sales']]\n\n grid_full = pd.read_feather(f\"{notebook_name}/grid_full_store_{store_id}_{end_train_day_x}_to_{end_train_day_x + prediction_horizon}.feather\") \n lsf = LSF(model=estimator, min_bin_size=min_bin_size)\n lsf.fit(x_train=grid_full[enable_features], y_train=grid_full['sales'].fillna(0), \n seed=0, x_train_is_dataframe=True, model_is_already_trained=True)\n\n for predict_day in range(previous_prediction_horizon + 1, prediction_horizon + 1):\n print('[{3} -> {4}] predict {0}/{1} {2} day {5}'.format(\n store_index + 1, len(store_id_set_list), store_id,\n previous_prediction_horizon + 1, prediction_horizon, predict_day))\n mask = base_test['d'] == (end_train_day_x + predict_day)\n base_test.loc[mask, 'sales'] = lsf.predict(base_test[mask][enable_features], quantile=quantile)\n\n temp_v_df = base_test[\n (base_test['d'] >= end_train_day_x + previous_prediction_horizon + 1) &\n (base_test['d'] < end_train_day_x + prediction_horizon + 1)\n ][['id', 'd', 'sales']]\n\n if len(pred_v_df)!=0:\n pred_v_df = pd.concat([pred_v_df, temp_v_df])\n else:\n pred_v_df = temp_v_df.copy()\n\n del(temp_v_df)\n gc.collect()\n\n previous_prediction_horizon = prediction_horizon\n pred_v_all_df.append(pred_v_df)\n\n pred_v_all_df = pd.concat(pred_v_all_df)\n\n submission = pd.read_csv(\"../input/m5-forecasting-accuracy/sample_submission.csv\")\n\n pred_v_all_df.d = pred_v_all_df.d - end_train_day_x_list\n pred_h_all_df = pred_v_all_df.pivot(index='id', columns='d', values='sales')\n pred_h_all_df = pred_h_all_df.reset_index()\n pred_h_all_df.columns = submission.columns\n\n submission = submission[['id']].merge(pred_h_all_df, on=['id'], how='left').fillna(0)\n submission.to_csv(f\"m5_predictions_quantile={quantile}.csv\", index=False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for quantile in [0.005, 0.025, 0.165, 0.25 , 0.5 , 0.75 , 0.835, 0.975, 0.995]:\n predict_uncertainty(end_train_day_x_list=[1941], \n prediction_horizon_list=[7, 14, 21, 28], \n min_bin_size=300,\n quantile=quantile)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}
--------------------------------------------------------------------------------
/cover.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/The-Kaggle-Workbook/f264cf5d1d6d4bf03b876e3f2aa667ebf42a36db/cover.png
--------------------------------------------------------------------------------