1_Data_Creation-Laure-Dumont.ipynb ADDED
@@ -0,0 +1,1899 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "4ba6aba8"
7
+ },
8
+ "source": [
9
+ "# 🤖 **Data Collection, Creation, Storage, and Processing**\n"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "markdown",
14
+ "metadata": {
15
+ "id": "jpASMyIQMaAq"
16
+ },
17
+ "source": [
18
+ "## **1.** 📦 Install required packages"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "execution_count": 1,
24
+ "metadata": {
25
+ "colab": {
26
+ "base_uri": "https://localhost:8080/"
27
+ },
28
+ "id": "f48c8f8c",
29
+ "outputId": "d5b58dc0-1b02-40c1-f5a7-f4e66bf36bbd"
30
+ },
31
+ "outputs": [
32
+ {
33
+ "output_type": "stream",
34
+ "name": "stdout",
35
+ "text": [
36
+ "Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.12/dist-packages (4.13.5)\n",
37
+ "Requirement already satisfied: pandas in /usr/local/lib/python3.12/dist-packages (2.2.2)\n",
38
+ "Requirement already satisfied: matplotlib in /usr/local/lib/python3.12/dist-packages (3.10.0)\n",
39
+ "Requirement already satisfied: seaborn in /usr/local/lib/python3.12/dist-packages (0.13.2)\n",
40
+ "Requirement already satisfied: numpy in /usr/local/lib/python3.12/dist-packages (2.0.2)\n",
41
+ "Requirement already satisfied: textblob in /usr/local/lib/python3.12/dist-packages (0.19.0)\n",
42
+ "Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (2.8.3)\n",
43
+ "Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.12/dist-packages (from beautifulsoup4) (4.15.0)\n",
44
+ "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.12/dist-packages (from pandas) (2.9.0.post0)\n",
45
+ "Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.2)\n",
46
+ "Requirement already satisfied: tzdata>=2022.7 in /usr/local/lib/python3.12/dist-packages (from pandas) (2025.3)\n",
47
+ "Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.3.3)\n",
48
+ "Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (0.12.1)\n",
49
+ "Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (4.61.1)\n",
50
+ "Requirement already satisfied: kiwisolver>=1.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (1.4.9)\n",
51
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (26.0)\n",
52
+ "Requirement already satisfied: pillow>=8 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (11.3.0)\n",
53
+ "Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.12/dist-packages (from matplotlib) (3.3.2)\n",
54
+ "Requirement already satisfied: nltk>=3.9 in /usr/local/lib/python3.12/dist-packages (from textblob) (3.9.1)\n",
55
+ "Requirement already satisfied: click in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (8.3.1)\n",
56
+ "Requirement already satisfied: joblib in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (1.5.3)\n",
57
+ "Requirement already satisfied: regex>=2021.8.3 in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (2025.11.3)\n",
58
+ "Requirement already satisfied: tqdm in /usr/local/lib/python3.12/dist-packages (from nltk>=3.9->textblob) (4.67.3)\n",
59
+ "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.12/dist-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n"
60
+ ]
61
+ }
62
+ ],
63
+ "source": [
64
+ "!pip install beautifulsoup4 pandas matplotlib seaborn numpy textblob"
65
+ ]
66
+ },
67
+ {
68
+ "cell_type": "markdown",
69
+ "metadata": {
70
+ "id": "lquNYCbfL9IM"
71
+ },
72
+ "source": [
73
+ "## **2.** ⛏ Web-scrape all book titles, prices, and ratings from books.toscrape.com"
74
+ ]
75
+ },
76
+ {
77
+ "cell_type": "markdown",
78
+ "metadata": {
79
+ "id": "0IWuNpxxYDJF"
80
+ },
81
+ "source": [
82
+ "### *a. Initial setup*\n",
83
+ "Define the base url of the website you will scrape as well as how and what you will scrape"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": 2,
89
+ "metadata": {
90
+ "id": "91d52125"
91
+ },
92
+ "outputs": [],
93
+ "source": [
94
+ "import requests\n",
95
+ "from bs4 import BeautifulSoup\n",
96
+ "import pandas as pd\n",
97
+ "import time\n",
98
+ "\n",
99
+ "base_url = \"https://books.toscrape.com/catalogue/page-{}.html\"\n",
100
+ "headers = {\"User-Agent\": \"Mozilla/5.0\"}\n",
101
+ "\n",
102
+ "titles, prices, ratings = [], [], []"
103
+ ]
104
+ },
105
+ {
106
+ "cell_type": "markdown",
107
+ "metadata": {
108
+ "id": "oCdTsin2Yfp3"
109
+ },
110
+ "source": [
111
+ "### *b. Fill titles, prices, and ratings from the web pages*"
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": 3,
117
+ "metadata": {
118
+ "id": "xqO5Y3dnYhxt"
119
+ },
120
+ "outputs": [],
121
+ "source": [
122
+ "# Loop through all 50 pages\n",
123
+ "for page in range(1, 51):\n",
124
+ " url = base_url.format(page)\n",
125
+ " response = requests.get(url, headers=headers)\n",
126
+ " soup = BeautifulSoup(response.content, \"html.parser\")\n",
127
+ " books = soup.find_all(\"article\", class_=\"product_pod\")\n",
128
+ "\n",
129
+ " for book in books:\n",
130
+ " titles.append(book.h3.a[\"title\"])\n",
131
+ " prices.append(float(book.find(\"p\", class_=\"price_color\").text[1:]))\n",
132
+ " ratings.append(book.p.get(\"class\")[1])\n",
133
+ "\n",
134
+ " time.sleep(0.5) # polite scraping delay"
135
+ ]
136
+ },
137
+ {
138
+ "cell_type": "markdown",
139
+ "metadata": {
140
+ "id": "T0TOeRC4Yrnn"
141
+ },
142
+ "source": [
143
+ "### *c. ✋🏻🛑⛔️ Create a dataframe df_books that contains the now complete \"title\", \"price\", and \"rating\" objects*"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": 8,
149
+ "metadata": {
150
+ "id": "l5FkkNhUYTHh",
151
+ "colab": {
152
+ "base_uri": "https://localhost:8080/"
153
+ },
154
+ "outputId": "08be9afa-064e-4578-f369-2ef40ffb3eb8"
155
+ },
156
+ "outputs": [
157
+ {
158
+ "output_type": "stream",
159
+ "name": "stdout",
160
+ "text": [
161
+ " title price rating\n",
162
+ "0 A Light in the Attic 51.77 Three\n",
163
+ "1 Tipping the Velvet 53.74 One\n",
164
+ "2 Soumission 50.10 One\n",
165
+ "3 Sharp Objects 47.82 Four\n",
166
+ "4 Sapiens: A Brief History of Humankind 54.23 Five\n"
167
+ ]
168
+ }
169
+ ],
170
+ "source": [
171
+ "df_books = pd.DataFrame({\n",
172
+ " \"title\": titles,\n",
173
+ " \"price\": prices,\n",
174
+ " \"rating\": ratings\n",
175
+ "})\n",
176
+ "\n",
177
+ "print(df_books.head())"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "markdown",
182
+ "metadata": {
183
+ "id": "duI5dv3CZYvF"
184
+ },
185
+ "source": [
186
+ "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
187
+ ]
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "execution_count": 9,
192
+ "metadata": {
193
+ "id": "lC1U_YHtZifh"
194
+ },
195
+ "outputs": [],
196
+ "source": [
197
+ "# 💾 Save to CSV\n",
198
+ "df_books.to_csv(\"books_data.csv\", index=False)\n",
199
+ "\n",
200
+ "# 💾 Or save to Excel\n",
201
+ "# df_books.to_excel(\"books_data.xlsx\", index=False)"
202
+ ]
203
+ },
204
+ {
205
+ "cell_type": "markdown",
206
+ "metadata": {
207
+ "id": "qMjRKMBQZlJi"
208
+ },
209
+ "source": [
210
+ "### *e. ✋🏻🛑⛔️ View first fiew lines*"
211
+ ]
212
+ },
213
+ {
214
+ "cell_type": "code",
215
+ "execution_count": 10,
216
+ "metadata": {
217
+ "colab": {
218
+ "base_uri": "https://localhost:8080/",
219
+ "height": 201
220
+ },
221
+ "id": "O_wIvTxYZqCK",
222
+ "outputId": "bc750b76-0850-4aeb-abbb-2567e436b081"
223
+ },
224
+ "outputs": [
225
+ {
226
+ "output_type": "execute_result",
227
+ "data": {
228
+ "text/plain": [
229
+ " title price rating\n",
230
+ "0 A Light in the Attic 51.77 Three\n",
231
+ "1 Tipping the Velvet 53.74 One\n",
232
+ "2 Soumission 50.10 One\n",
233
+ "3 Sharp Objects 47.82 Four\n",
234
+ "4 Sapiens: A Brief History of Humankind 54.23 Five"
235
+ ],
236
+ "text/html": [
237
+ "\n",
238
+ " <div id=\"df-38d4b1c4-a739-4622-af0c-bc5364b6f219\" class=\"colab-df-container\">\n",
239
+ " <div>\n",
240
+ "<style scoped>\n",
241
+ " .dataframe tbody tr th:only-of-type {\n",
242
+ " vertical-align: middle;\n",
243
+ " }\n",
244
+ "\n",
245
+ " .dataframe tbody tr th {\n",
246
+ " vertical-align: top;\n",
247
+ " }\n",
248
+ "\n",
249
+ " .dataframe thead th {\n",
250
+ " text-align: right;\n",
251
+ " }\n",
252
+ "</style>\n",
253
+ "<table border=\"1\" class=\"dataframe\">\n",
254
+ " <thead>\n",
255
+ " <tr style=\"text-align: right;\">\n",
256
+ " <th></th>\n",
257
+ " <th>title</th>\n",
258
+ " <th>price</th>\n",
259
+ " <th>rating</th>\n",
260
+ " </tr>\n",
261
+ " </thead>\n",
262
+ " <tbody>\n",
263
+ " <tr>\n",
264
+ " <th>0</th>\n",
265
+ " <td>A Light in the Attic</td>\n",
266
+ " <td>51.77</td>\n",
267
+ " <td>Three</td>\n",
268
+ " </tr>\n",
269
+ " <tr>\n",
270
+ " <th>1</th>\n",
271
+ " <td>Tipping the Velvet</td>\n",
272
+ " <td>53.74</td>\n",
273
+ " <td>One</td>\n",
274
+ " </tr>\n",
275
+ " <tr>\n",
276
+ " <th>2</th>\n",
277
+ " <td>Soumission</td>\n",
278
+ " <td>50.10</td>\n",
279
+ " <td>One</td>\n",
280
+ " </tr>\n",
281
+ " <tr>\n",
282
+ " <th>3</th>\n",
283
+ " <td>Sharp Objects</td>\n",
284
+ " <td>47.82</td>\n",
285
+ " <td>Four</td>\n",
286
+ " </tr>\n",
287
+ " <tr>\n",
288
+ " <th>4</th>\n",
289
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
290
+ " <td>54.23</td>\n",
291
+ " <td>Five</td>\n",
292
+ " </tr>\n",
293
+ " </tbody>\n",
294
+ "</table>\n",
295
+ "</div>\n",
296
+ " <div class=\"colab-df-buttons\">\n",
297
+ "\n",
298
+ " <div class=\"colab-df-container\">\n",
299
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-38d4b1c4-a739-4622-af0c-bc5364b6f219')\"\n",
300
+ " title=\"Convert this dataframe to an interactive table.\"\n",
301
+ " style=\"display:none;\">\n",
302
+ "\n",
303
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
304
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
305
+ " </svg>\n",
306
+ " </button>\n",
307
+ "\n",
308
+ " <style>\n",
309
+ " .colab-df-container {\n",
310
+ " display:flex;\n",
311
+ " gap: 12px;\n",
312
+ " }\n",
313
+ "\n",
314
+ " .colab-df-convert {\n",
315
+ " background-color: #E8F0FE;\n",
316
+ " border: none;\n",
317
+ " border-radius: 50%;\n",
318
+ " cursor: pointer;\n",
319
+ " display: none;\n",
320
+ " fill: #1967D2;\n",
321
+ " height: 32px;\n",
322
+ " padding: 0 0 0 0;\n",
323
+ " width: 32px;\n",
324
+ " }\n",
325
+ "\n",
326
+ " .colab-df-convert:hover {\n",
327
+ " background-color: #E2EBFA;\n",
328
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
329
+ " fill: #174EA6;\n",
330
+ " }\n",
331
+ "\n",
332
+ " .colab-df-buttons div {\n",
333
+ " margin-bottom: 4px;\n",
334
+ " }\n",
335
+ "\n",
336
+ " [theme=dark] .colab-df-convert {\n",
337
+ " background-color: #3B4455;\n",
338
+ " fill: #D2E3FC;\n",
339
+ " }\n",
340
+ "\n",
341
+ " [theme=dark] .colab-df-convert:hover {\n",
342
+ " background-color: #434B5C;\n",
343
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
344
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
345
+ " fill: #FFFFFF;\n",
346
+ " }\n",
347
+ " </style>\n",
348
+ "\n",
349
+ " <script>\n",
350
+ " const buttonEl =\n",
351
+ " document.querySelector('#df-38d4b1c4-a739-4622-af0c-bc5364b6f219 button.colab-df-convert');\n",
352
+ " buttonEl.style.display =\n",
353
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
354
+ "\n",
355
+ " async function convertToInteractive(key) {\n",
356
+ " const element = document.querySelector('#df-38d4b1c4-a739-4622-af0c-bc5364b6f219');\n",
357
+ " const dataTable =\n",
358
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
359
+ " [key], {});\n",
360
+ " if (!dataTable) return;\n",
361
+ "\n",
362
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
363
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
364
+ " + ' to learn more about interactive tables.';\n",
365
+ " element.innerHTML = '';\n",
366
+ " dataTable['output_type'] = 'display_data';\n",
367
+ " await google.colab.output.renderOutput(dataTable, element);\n",
368
+ " const docLink = document.createElement('div');\n",
369
+ " docLink.innerHTML = docLinkHtml;\n",
370
+ " element.appendChild(docLink);\n",
371
+ " }\n",
372
+ " </script>\n",
373
+ " </div>\n",
374
+ "\n",
375
+ "\n",
376
+ " </div>\n",
377
+ " </div>\n"
378
+ ],
379
+ "application/vnd.google.colaboratory.intrinsic+json": {
380
+ "type": "dataframe",
381
+ "variable_name": "df_books",
382
+ "summary": "{\n \"name\": \"df_books\",\n \"rows\": 1000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 14.446689669952772,\n \"min\": 10.0,\n \"max\": 59.99,\n \"num_unique_values\": 903,\n \"samples\": [\n 19.73,\n 55.65,\n 46.31\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
383
+ }
384
+ },
385
+ "metadata": {},
386
+ "execution_count": 10
387
+ }
388
+ ],
389
+ "source": [
390
+ "df_books.head()"
391
+ ]
392
+ },
393
+ {
394
+ "cell_type": "markdown",
395
+ "metadata": {
396
+ "id": "p-1Pr2szaqLk"
397
+ },
398
+ "source": [
399
+ "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
400
+ ]
401
+ },
402
+ {
403
+ "cell_type": "markdown",
404
+ "metadata": {
405
+ "id": "SIaJUGIpaH4V"
406
+ },
407
+ "source": [
408
+ "### *a. Initial setup*"
409
+ ]
410
+ },
411
+ {
412
+ "cell_type": "code",
413
+ "execution_count": 11,
414
+ "metadata": {
415
+ "id": "-gPXGcRPuV_9"
416
+ },
417
+ "outputs": [],
418
+ "source": [
419
+ "import numpy as np\n",
420
+ "import random\n",
421
+ "from datetime import datetime\n",
422
+ "import warnings\n",
423
+ "\n",
424
+ "warnings.filterwarnings(\"ignore\")\n",
425
+ "random.seed(2025)\n",
426
+ "np.random.seed(2025)"
427
+ ]
428
+ },
429
+ {
430
+ "cell_type": "markdown",
431
+ "metadata": {
432
+ "id": "pY4yCoIuaQqp"
433
+ },
434
+ "source": [
435
+ "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "code",
440
+ "execution_count": 12,
441
+ "metadata": {
442
+ "id": "mnd5hdAbaNjz"
443
+ },
444
+ "outputs": [],
445
+ "source": [
446
+ "def generate_popularity_score(rating):\n",
447
+ " base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
448
+ " trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
449
+ " return int(np.clip(base + trend_factor, 1, 5))"
450
+ ]
451
+ },
452
+ {
453
+ "cell_type": "markdown",
454
+ "metadata": {
455
+ "id": "n4-TaNTFgPak"
456
+ },
457
+ "source": [
458
+ "### *c. ✋🏻🛑⛔️ Run the function to create a \"popularity_score\" column from \"rating\"*"
459
+ ]
460
+ },
461
+ {
462
+ "cell_type": "code",
463
+ "execution_count": 13,
464
+ "metadata": {
465
+ "id": "V-G3OCUCgR07",
466
+ "colab": {
467
+ "base_uri": "https://localhost:8080/",
468
+ "height": 201
469
+ },
470
+ "outputId": "952ec48b-58bc-488f-c33c-c87fcaa34014"
471
+ },
472
+ "outputs": [
473
+ {
474
+ "output_type": "execute_result",
475
+ "data": {
476
+ "text/plain": [
477
+ " title price rating popularity_score\n",
478
+ "0 A Light in the Attic 51.77 Three 3\n",
479
+ "1 Tipping the Velvet 53.74 One 2\n",
480
+ "2 Soumission 50.10 One 2\n",
481
+ "3 Sharp Objects 47.82 Four 4\n",
482
+ "4 Sapiens: A Brief History of Humankind 54.23 Five 3"
483
+ ],
484
+ "text/html": [
485
+ "\n",
486
+ " <div id=\"df-7de90955-8b5f-4399-b4a1-c12307a4cbf7\" class=\"colab-df-container\">\n",
487
+ " <div>\n",
488
+ "<style scoped>\n",
489
+ " .dataframe tbody tr th:only-of-type {\n",
490
+ " vertical-align: middle;\n",
491
+ " }\n",
492
+ "\n",
493
+ " .dataframe tbody tr th {\n",
494
+ " vertical-align: top;\n",
495
+ " }\n",
496
+ "\n",
497
+ " .dataframe thead th {\n",
498
+ " text-align: right;\n",
499
+ " }\n",
500
+ "</style>\n",
501
+ "<table border=\"1\" class=\"dataframe\">\n",
502
+ " <thead>\n",
503
+ " <tr style=\"text-align: right;\">\n",
504
+ " <th></th>\n",
505
+ " <th>title</th>\n",
506
+ " <th>price</th>\n",
507
+ " <th>rating</th>\n",
508
+ " <th>popularity_score</th>\n",
509
+ " </tr>\n",
510
+ " </thead>\n",
511
+ " <tbody>\n",
512
+ " <tr>\n",
513
+ " <th>0</th>\n",
514
+ " <td>A Light in the Attic</td>\n",
515
+ " <td>51.77</td>\n",
516
+ " <td>Three</td>\n",
517
+ " <td>3</td>\n",
518
+ " </tr>\n",
519
+ " <tr>\n",
520
+ " <th>1</th>\n",
521
+ " <td>Tipping the Velvet</td>\n",
522
+ " <td>53.74</td>\n",
523
+ " <td>One</td>\n",
524
+ " <td>2</td>\n",
525
+ " </tr>\n",
526
+ " <tr>\n",
527
+ " <th>2</th>\n",
528
+ " <td>Soumission</td>\n",
529
+ " <td>50.10</td>\n",
530
+ " <td>One</td>\n",
531
+ " <td>2</td>\n",
532
+ " </tr>\n",
533
+ " <tr>\n",
534
+ " <th>3</th>\n",
535
+ " <td>Sharp Objects</td>\n",
536
+ " <td>47.82</td>\n",
537
+ " <td>Four</td>\n",
538
+ " <td>4</td>\n",
539
+ " </tr>\n",
540
+ " <tr>\n",
541
+ " <th>4</th>\n",
542
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
543
+ " <td>54.23</td>\n",
544
+ " <td>Five</td>\n",
545
+ " <td>3</td>\n",
546
+ " </tr>\n",
547
+ " </tbody>\n",
548
+ "</table>\n",
549
+ "</div>\n",
550
+ " <div class=\"colab-df-buttons\">\n",
551
+ "\n",
552
+ " <div class=\"colab-df-container\">\n",
553
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-7de90955-8b5f-4399-b4a1-c12307a4cbf7')\"\n",
554
+ " title=\"Convert this dataframe to an interactive table.\"\n",
555
+ " style=\"display:none;\">\n",
556
+ "\n",
557
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
558
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
559
+ " </svg>\n",
560
+ " </button>\n",
561
+ "\n",
562
+ " <style>\n",
563
+ " .colab-df-container {\n",
564
+ " display:flex;\n",
565
+ " gap: 12px;\n",
566
+ " }\n",
567
+ "\n",
568
+ " .colab-df-convert {\n",
569
+ " background-color: #E8F0FE;\n",
570
+ " border: none;\n",
571
+ " border-radius: 50%;\n",
572
+ " cursor: pointer;\n",
573
+ " display: none;\n",
574
+ " fill: #1967D2;\n",
575
+ " height: 32px;\n",
576
+ " padding: 0 0 0 0;\n",
577
+ " width: 32px;\n",
578
+ " }\n",
579
+ "\n",
580
+ " .colab-df-convert:hover {\n",
581
+ " background-color: #E2EBFA;\n",
582
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
583
+ " fill: #174EA6;\n",
584
+ " }\n",
585
+ "\n",
586
+ " .colab-df-buttons div {\n",
587
+ " margin-bottom: 4px;\n",
588
+ " }\n",
589
+ "\n",
590
+ " [theme=dark] .colab-df-convert {\n",
591
+ " background-color: #3B4455;\n",
592
+ " fill: #D2E3FC;\n",
593
+ " }\n",
594
+ "\n",
595
+ " [theme=dark] .colab-df-convert:hover {\n",
596
+ " background-color: #434B5C;\n",
597
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
598
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
599
+ " fill: #FFFFFF;\n",
600
+ " }\n",
601
+ " </style>\n",
602
+ "\n",
603
+ " <script>\n",
604
+ " const buttonEl =\n",
605
+ " document.querySelector('#df-7de90955-8b5f-4399-b4a1-c12307a4cbf7 button.colab-df-convert');\n",
606
+ " buttonEl.style.display =\n",
607
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
608
+ "\n",
609
+ " async function convertToInteractive(key) {\n",
610
+ " const element = document.querySelector('#df-7de90955-8b5f-4399-b4a1-c12307a4cbf7');\n",
611
+ " const dataTable =\n",
612
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
613
+ " [key], {});\n",
614
+ " if (!dataTable) return;\n",
615
+ "\n",
616
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
617
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
618
+ " + ' to learn more about interactive tables.';\n",
619
+ " element.innerHTML = '';\n",
620
+ " dataTable['output_type'] = 'display_data';\n",
621
+ " await google.colab.output.renderOutput(dataTable, element);\n",
622
+ " const docLink = document.createElement('div');\n",
623
+ " docLink.innerHTML = docLinkHtml;\n",
624
+ " element.appendChild(docLink);\n",
625
+ " }\n",
626
+ " </script>\n",
627
+ " </div>\n",
628
+ "\n",
629
+ "\n",
630
+ " </div>\n",
631
+ " </div>\n"
632
+ ],
633
+ "application/vnd.google.colaboratory.intrinsic+json": {
634
+ "type": "dataframe",
635
+ "variable_name": "df_books",
636
+ "summary": "{\n \"name\": \"df_books\",\n \"rows\": 1000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 14.446689669952772,\n \"min\": 10.0,\n \"max\": 59.99,\n \"num_unique_values\": 903,\n \"samples\": [\n 19.73,\n 55.65,\n 46.31\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"popularity_score\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 5,\n \"num_unique_values\": 5,\n \"samples\": [\n 2,\n 5,\n 4\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
637
+ }
638
+ },
639
+ "metadata": {},
640
+ "execution_count": 13
641
+ }
642
+ ],
643
+ "source": [
644
+ "df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)\n",
645
+ "\n",
646
+ "df_books.head()"
647
+ ]
648
+ },
649
+ {
650
+ "cell_type": "markdown",
651
+ "metadata": {
652
+ "id": "HnngRNTgacYt"
653
+ },
654
+ "source": [
655
+ "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
656
+ ]
657
+ },
658
+ {
659
+ "cell_type": "code",
660
+ "execution_count": 14,
661
+ "metadata": {
662
+ "id": "kUtWmr8maZLZ"
663
+ },
664
+ "outputs": [],
665
+ "source": [
666
+ "def get_sentiment(popularity_score):\n",
667
+ " if popularity_score <= 2:\n",
668
+ " return \"negative\"\n",
669
+ " elif popularity_score == 3:\n",
670
+ " return \"neutral\"\n",
671
+ " else:\n",
672
+ " return \"positive\""
673
+ ]
674
+ },
675
+ {
676
+ "cell_type": "markdown",
677
+ "metadata": {
678
+ "id": "HF9F9HIzgT7Z"
679
+ },
680
+ "source": [
681
+ "### *e. ✋🏻🛑⛔️ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
682
+ ]
683
+ },
684
+ {
685
+ "cell_type": "code",
686
+ "execution_count": 15,
687
+ "metadata": {
688
+ "id": "tafQj8_7gYCG",
689
+ "colab": {
690
+ "base_uri": "https://localhost:8080/",
691
+ "height": 201
692
+ },
693
+ "outputId": "69794113-db3a-44a2-9fe2-5bea51145ddf"
694
+ },
695
+ "outputs": [
696
+ {
697
+ "output_type": "execute_result",
698
+ "data": {
699
+ "text/plain": [
700
+ " title price rating popularity_score \\\n",
701
+ "0 A Light in the Attic 51.77 Three 3 \n",
702
+ "1 Tipping the Velvet 53.74 One 2 \n",
703
+ "2 Soumission 50.10 One 2 \n",
704
+ "3 Sharp Objects 47.82 Four 4 \n",
705
+ "4 Sapiens: A Brief History of Humankind 54.23 Five 3 \n",
706
+ "\n",
707
+ " sentiment_label \n",
708
+ "0 neutral \n",
709
+ "1 negative \n",
710
+ "2 negative \n",
711
+ "3 positive \n",
712
+ "4 neutral "
713
+ ],
714
+ "text/html": [
715
+ "\n",
716
+ " <div id=\"df-340485d6-3ef5-435d-bbc6-67c661d86195\" class=\"colab-df-container\">\n",
717
+ " <div>\n",
718
+ "<style scoped>\n",
719
+ " .dataframe tbody tr th:only-of-type {\n",
720
+ " vertical-align: middle;\n",
721
+ " }\n",
722
+ "\n",
723
+ " .dataframe tbody tr th {\n",
724
+ " vertical-align: top;\n",
725
+ " }\n",
726
+ "\n",
727
+ " .dataframe thead th {\n",
728
+ " text-align: right;\n",
729
+ " }\n",
730
+ "</style>\n",
731
+ "<table border=\"1\" class=\"dataframe\">\n",
732
+ " <thead>\n",
733
+ " <tr style=\"text-align: right;\">\n",
734
+ " <th></th>\n",
735
+ " <th>title</th>\n",
736
+ " <th>price</th>\n",
737
+ " <th>rating</th>\n",
738
+ " <th>popularity_score</th>\n",
739
+ " <th>sentiment_label</th>\n",
740
+ " </tr>\n",
741
+ " </thead>\n",
742
+ " <tbody>\n",
743
+ " <tr>\n",
744
+ " <th>0</th>\n",
745
+ " <td>A Light in the Attic</td>\n",
746
+ " <td>51.77</td>\n",
747
+ " <td>Three</td>\n",
748
+ " <td>3</td>\n",
749
+ " <td>neutral</td>\n",
750
+ " </tr>\n",
751
+ " <tr>\n",
752
+ " <th>1</th>\n",
753
+ " <td>Tipping the Velvet</td>\n",
754
+ " <td>53.74</td>\n",
755
+ " <td>One</td>\n",
756
+ " <td>2</td>\n",
757
+ " <td>negative</td>\n",
758
+ " </tr>\n",
759
+ " <tr>\n",
760
+ " <th>2</th>\n",
761
+ " <td>Soumission</td>\n",
762
+ " <td>50.10</td>\n",
763
+ " <td>One</td>\n",
764
+ " <td>2</td>\n",
765
+ " <td>negative</td>\n",
766
+ " </tr>\n",
767
+ " <tr>\n",
768
+ " <th>3</th>\n",
769
+ " <td>Sharp Objects</td>\n",
770
+ " <td>47.82</td>\n",
771
+ " <td>Four</td>\n",
772
+ " <td>4</td>\n",
773
+ " <td>positive</td>\n",
774
+ " </tr>\n",
775
+ " <tr>\n",
776
+ " <th>4</th>\n",
777
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
778
+ " <td>54.23</td>\n",
779
+ " <td>Five</td>\n",
780
+ " <td>3</td>\n",
781
+ " <td>neutral</td>\n",
782
+ " </tr>\n",
783
+ " </tbody>\n",
784
+ "</table>\n",
785
+ "</div>\n",
786
+ " <div class=\"colab-df-buttons\">\n",
787
+ "\n",
788
+ " <div class=\"colab-df-container\">\n",
789
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-340485d6-3ef5-435d-bbc6-67c661d86195')\"\n",
790
+ " title=\"Convert this dataframe to an interactive table.\"\n",
791
+ " style=\"display:none;\">\n",
792
+ "\n",
793
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
794
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
795
+ " </svg>\n",
796
+ " </button>\n",
797
+ "\n",
798
+ " <style>\n",
799
+ " .colab-df-container {\n",
800
+ " display:flex;\n",
801
+ " gap: 12px;\n",
802
+ " }\n",
803
+ "\n",
804
+ " .colab-df-convert {\n",
805
+ " background-color: #E8F0FE;\n",
806
+ " border: none;\n",
807
+ " border-radius: 50%;\n",
808
+ " cursor: pointer;\n",
809
+ " display: none;\n",
810
+ " fill: #1967D2;\n",
811
+ " height: 32px;\n",
812
+ " padding: 0 0 0 0;\n",
813
+ " width: 32px;\n",
814
+ " }\n",
815
+ "\n",
816
+ " .colab-df-convert:hover {\n",
817
+ " background-color: #E2EBFA;\n",
818
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
819
+ " fill: #174EA6;\n",
820
+ " }\n",
821
+ "\n",
822
+ " .colab-df-buttons div {\n",
823
+ " margin-bottom: 4px;\n",
824
+ " }\n",
825
+ "\n",
826
+ " [theme=dark] .colab-df-convert {\n",
827
+ " background-color: #3B4455;\n",
828
+ " fill: #D2E3FC;\n",
829
+ " }\n",
830
+ "\n",
831
+ " [theme=dark] .colab-df-convert:hover {\n",
832
+ " background-color: #434B5C;\n",
833
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
834
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
835
+ " fill: #FFFFFF;\n",
836
+ " }\n",
837
+ " </style>\n",
838
+ "\n",
839
+ " <script>\n",
840
+ " const buttonEl =\n",
841
+ " document.querySelector('#df-340485d6-3ef5-435d-bbc6-67c661d86195 button.colab-df-convert');\n",
842
+ " buttonEl.style.display =\n",
843
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
844
+ "\n",
845
+ " async function convertToInteractive(key) {\n",
846
+ " const element = document.querySelector('#df-340485d6-3ef5-435d-bbc6-67c661d86195');\n",
847
+ " const dataTable =\n",
848
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
849
+ " [key], {});\n",
850
+ " if (!dataTable) return;\n",
851
+ "\n",
852
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
853
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
854
+ " + ' to learn more about interactive tables.';\n",
855
+ " element.innerHTML = '';\n",
856
+ " dataTable['output_type'] = 'display_data';\n",
857
+ " await google.colab.output.renderOutput(dataTable, element);\n",
858
+ " const docLink = document.createElement('div');\n",
859
+ " docLink.innerHTML = docLinkHtml;\n",
860
+ " element.appendChild(docLink);\n",
861
+ " }\n",
862
+ " </script>\n",
863
+ " </div>\n",
864
+ "\n",
865
+ "\n",
866
+ " </div>\n",
867
+ " </div>\n"
868
+ ],
869
+ "application/vnd.google.colaboratory.intrinsic+json": {
870
+ "type": "dataframe",
871
+ "variable_name": "df_books",
872
+ "summary": "{\n \"name\": \"df_books\",\n \"rows\": 1000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 14.446689669952772,\n \"min\": 10.0,\n \"max\": 59.99,\n \"num_unique_values\": 903,\n \"samples\": [\n 19.73,\n 55.65,\n 46.31\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"One\",\n \"Two\",\n \"Four\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"popularity_score\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1,\n \"min\": 1,\n \"max\": 5,\n \"num_unique_values\": 5,\n \"samples\": [\n 2,\n 5,\n 4\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"sentiment_label\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"neutral\",\n \"negative\",\n \"positive\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
873
+ }
874
+ },
875
+ "metadata": {},
876
+ "execution_count": 15
877
+ }
878
+ ],
879
+ "source": [
880
+ "df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)\n",
881
+ "\n",
882
+ "df_books.head()"
883
+ ]
884
+ },
885
+ {
886
+ "cell_type": "markdown",
887
+ "metadata": {
888
+ "id": "T8AdKkmASq9a"
889
+ },
890
+ "source": [
891
+ "## **4.** 📈 Generate synthetic book sales data of 18 months"
892
+ ]
893
+ },
894
+ {
895
+ "cell_type": "markdown",
896
+ "metadata": {
897
+ "id": "OhXbdGD5fH0c"
898
+ },
899
+ "source": [
900
+ "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
901
+ ]
902
+ },
903
+ {
904
+ "cell_type": "code",
905
+ "execution_count": 16,
906
+ "metadata": {
907
+ "id": "qkVhYPXGbgEn"
908
+ },
909
+ "outputs": [],
910
+ "source": [
911
+ "def generate_sales_profile(sentiment):\n",
912
+ " months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
913
+ "\n",
914
+ " if sentiment == \"positive\":\n",
915
+ " base = random.randint(200, 300)\n",
916
+ " trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
917
+ " elif sentiment == \"negative\":\n",
918
+ " base = random.randint(20, 80)\n",
919
+ " trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
920
+ " else: # neutral\n",
921
+ " base = random.randint(80, 160)\n",
922
+ " trend = np.full(len(months), base + random.randint(-10, 10))\n",
923
+ "\n",
924
+ " seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
925
+ " noise = np.random.normal(0, 5, len(months))\n",
926
+ " monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
927
+ "\n",
928
+ " return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
929
+ ]
930
+ },
931
+ {
932
+ "cell_type": "markdown",
933
+ "metadata": {
934
+ "id": "L2ak1HlcgoTe"
935
+ },
936
+ "source": [
937
+ "### *b. Run the function as part of building sales_data*"
938
+ ]
939
+ },
940
+ {
941
+ "cell_type": "code",
942
+ "execution_count": 17,
943
+ "metadata": {
944
+ "id": "SlJ24AUafoDB"
945
+ },
946
+ "outputs": [],
947
+ "source": [
948
+ "sales_data = []\n",
949
+ "for _, row in df_books.iterrows():\n",
950
+ " records = generate_sales_profile(row[\"sentiment_label\"])\n",
951
+ " for month, units in records:\n",
952
+ " sales_data.append({\n",
953
+ " \"title\": row[\"title\"],\n",
954
+ " \"month\": month,\n",
955
+ " \"units_sold\": units,\n",
956
+ " \"sentiment_label\": row[\"sentiment_label\"]\n",
957
+ " })"
958
+ ]
959
+ },
960
+ {
961
+ "cell_type": "markdown",
962
+ "metadata": {
963
+ "id": "4IXZKcCSgxnq"
964
+ },
965
+ "source": [
966
+ "### *c. ✋🏻🛑⛔️ Create a df_sales DataFrame from sales_data*"
967
+ ]
968
+ },
969
+ {
970
+ "cell_type": "code",
971
+ "execution_count": 18,
972
+ "metadata": {
973
+ "id": "wcN6gtiZg-ws",
974
+ "colab": {
975
+ "base_uri": "https://localhost:8080/",
976
+ "height": 201
977
+ },
978
+ "outputId": "e2431349-19c7-40a1-8f41-3b2312dc955b"
979
+ },
980
+ "outputs": [
981
+ {
982
+ "output_type": "execute_result",
983
+ "data": {
984
+ "text/plain": [
985
+ " title month units_sold sentiment_label\n",
986
+ "0 A Light in the Attic 2024-08 100 neutral\n",
987
+ "1 A Light in the Attic 2024-09 109 neutral\n",
988
+ "2 A Light in the Attic 2024-10 102 neutral\n",
989
+ "3 A Light in the Attic 2024-11 107 neutral\n",
990
+ "4 A Light in the Attic 2024-12 108 neutral"
991
+ ],
992
+ "text/html": [
993
+ "\n",
994
+ " <div id=\"df-7c6711de-a3f1-4b94-bf77-68f611287c7a\" class=\"colab-df-container\">\n",
995
+ " <div>\n",
996
+ "<style scoped>\n",
997
+ " .dataframe tbody tr th:only-of-type {\n",
998
+ " vertical-align: middle;\n",
999
+ " }\n",
1000
+ "\n",
1001
+ " .dataframe tbody tr th {\n",
1002
+ " vertical-align: top;\n",
1003
+ " }\n",
1004
+ "\n",
1005
+ " .dataframe thead th {\n",
1006
+ " text-align: right;\n",
1007
+ " }\n",
1008
+ "</style>\n",
1009
+ "<table border=\"1\" class=\"dataframe\">\n",
1010
+ " <thead>\n",
1011
+ " <tr style=\"text-align: right;\">\n",
1012
+ " <th></th>\n",
1013
+ " <th>title</th>\n",
1014
+ " <th>month</th>\n",
1015
+ " <th>units_sold</th>\n",
1016
+ " <th>sentiment_label</th>\n",
1017
+ " </tr>\n",
1018
+ " </thead>\n",
1019
+ " <tbody>\n",
1020
+ " <tr>\n",
1021
+ " <th>0</th>\n",
1022
+ " <td>A Light in the Attic</td>\n",
1023
+ " <td>2024-08</td>\n",
1024
+ " <td>100</td>\n",
1025
+ " <td>neutral</td>\n",
1026
+ " </tr>\n",
1027
+ " <tr>\n",
1028
+ " <th>1</th>\n",
1029
+ " <td>A Light in the Attic</td>\n",
1030
+ " <td>2024-09</td>\n",
1031
+ " <td>109</td>\n",
1032
+ " <td>neutral</td>\n",
1033
+ " </tr>\n",
1034
+ " <tr>\n",
1035
+ " <th>2</th>\n",
1036
+ " <td>A Light in the Attic</td>\n",
1037
+ " <td>2024-10</td>\n",
1038
+ " <td>102</td>\n",
1039
+ " <td>neutral</td>\n",
1040
+ " </tr>\n",
1041
+ " <tr>\n",
1042
+ " <th>3</th>\n",
1043
+ " <td>A Light in the Attic</td>\n",
1044
+ " <td>2024-11</td>\n",
1045
+ " <td>107</td>\n",
1046
+ " <td>neutral</td>\n",
1047
+ " </tr>\n",
1048
+ " <tr>\n",
1049
+ " <th>4</th>\n",
1050
+ " <td>A Light in the Attic</td>\n",
1051
+ " <td>2024-12</td>\n",
1052
+ " <td>108</td>\n",
1053
+ " <td>neutral</td>\n",
1054
+ " </tr>\n",
1055
+ " </tbody>\n",
1056
+ "</table>\n",
1057
+ "</div>\n",
1058
+ " <div class=\"colab-df-buttons\">\n",
1059
+ "\n",
1060
+ " <div class=\"colab-df-container\">\n",
1061
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-7c6711de-a3f1-4b94-bf77-68f611287c7a')\"\n",
1062
+ " title=\"Convert this dataframe to an interactive table.\"\n",
1063
+ " style=\"display:none;\">\n",
1064
+ "\n",
1065
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
1066
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
1067
+ " </svg>\n",
1068
+ " </button>\n",
1069
+ "\n",
1070
+ " <style>\n",
1071
+ " .colab-df-container {\n",
1072
+ " display:flex;\n",
1073
+ " gap: 12px;\n",
1074
+ " }\n",
1075
+ "\n",
1076
+ " .colab-df-convert {\n",
1077
+ " background-color: #E8F0FE;\n",
1078
+ " border: none;\n",
1079
+ " border-radius: 50%;\n",
1080
+ " cursor: pointer;\n",
1081
+ " display: none;\n",
1082
+ " fill: #1967D2;\n",
1083
+ " height: 32px;\n",
1084
+ " padding: 0 0 0 0;\n",
1085
+ " width: 32px;\n",
1086
+ " }\n",
1087
+ "\n",
1088
+ " .colab-df-convert:hover {\n",
1089
+ " background-color: #E2EBFA;\n",
1090
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
1091
+ " fill: #174EA6;\n",
1092
+ " }\n",
1093
+ "\n",
1094
+ " .colab-df-buttons div {\n",
1095
+ " margin-bottom: 4px;\n",
1096
+ " }\n",
1097
+ "\n",
1098
+ " [theme=dark] .colab-df-convert {\n",
1099
+ " background-color: #3B4455;\n",
1100
+ " fill: #D2E3FC;\n",
1101
+ " }\n",
1102
+ "\n",
1103
+ " [theme=dark] .colab-df-convert:hover {\n",
1104
+ " background-color: #434B5C;\n",
1105
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
1106
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
1107
+ " fill: #FFFFFF;\n",
1108
+ " }\n",
1109
+ " </style>\n",
1110
+ "\n",
1111
+ " <script>\n",
1112
+ " const buttonEl =\n",
1113
+ " document.querySelector('#df-7c6711de-a3f1-4b94-bf77-68f611287c7a button.colab-df-convert');\n",
1114
+ " buttonEl.style.display =\n",
1115
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
1116
+ "\n",
1117
+ " async function convertToInteractive(key) {\n",
1118
+ " const element = document.querySelector('#df-7c6711de-a3f1-4b94-bf77-68f611287c7a');\n",
1119
+ " const dataTable =\n",
1120
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
1121
+ " [key], {});\n",
1122
+ " if (!dataTable) return;\n",
1123
+ "\n",
1124
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
1125
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
1126
+ " + ' to learn more about interactive tables.';\n",
1127
+ " element.innerHTML = '';\n",
1128
+ " dataTable['output_type'] = 'display_data';\n",
1129
+ " await google.colab.output.renderOutput(dataTable, element);\n",
1130
+ " const docLink = document.createElement('div');\n",
1131
+ " docLink.innerHTML = docLinkHtml;\n",
1132
+ " element.appendChild(docLink);\n",
1133
+ " }\n",
1134
+ " </script>\n",
1135
+ " </div>\n",
1136
+ "\n",
1137
+ "\n",
1138
+ " </div>\n",
1139
+ " </div>\n"
1140
+ ],
1141
+ "application/vnd.google.colaboratory.intrinsic+json": {
1142
+ "type": "dataframe",
1143
+ "variable_name": "df_sales",
1144
+ "summary": "{\n \"name\": \"df_sales\",\n \"rows\": 18000,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 999,\n \"samples\": [\n \"The Grownup\",\n \"Persepolis: The Story of a Childhood (Persepolis #1-2)\",\n \"Ayumi's Violin\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"month\",\n \"properties\": {\n \"dtype\": \"object\",\n \"num_unique_values\": 18,\n \"samples\": [\n \"2024-08\",\n \"2024-09\",\n \"2025-04\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"units_sold\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 98,\n \"min\": 0,\n \"max\": 362,\n \"num_unique_values\": 354,\n \"samples\": [\n 214,\n 289,\n 205\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"sentiment_label\",\n \"properties\": {\n \"dtype\": \"category\",\n \"num_unique_values\": 3,\n \"samples\": [\n \"neutral\",\n \"negative\",\n \"positive\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
1145
+ }
1146
+ },
1147
+ "metadata": {},
1148
+ "execution_count": 18
1149
+ }
1150
+ ],
1151
+ "source": [
1152
+ "df_sales = pd.DataFrame(sales_data)\n",
1153
+ "\n",
1154
+ "df_sales.head()"
1155
+ ]
1156
+ },
1157
+ {
1158
+ "cell_type": "markdown",
1159
+ "metadata": {
1160
+ "id": "EhIjz9WohAmZ"
1161
+ },
1162
+ "source": [
1163
+ "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
1164
+ ]
1165
+ },
1166
+ {
1167
+ "cell_type": "code",
1168
+ "execution_count": 19,
1169
+ "metadata": {
1170
+ "colab": {
1171
+ "base_uri": "https://localhost:8080/"
1172
+ },
1173
+ "id": "MzbZvLcAhGaH",
1174
+ "outputId": "6c2082be-618b-4de2-c354-fb23a594663c"
1175
+ },
1176
+ "outputs": [
1177
+ {
1178
+ "output_type": "stream",
1179
+ "name": "stdout",
1180
+ "text": [
1181
+ " title month units_sold sentiment_label\n",
1182
+ "0 A Light in the Attic 2024-08 100 neutral\n",
1183
+ "1 A Light in the Attic 2024-09 109 neutral\n",
1184
+ "2 A Light in the Attic 2024-10 102 neutral\n",
1185
+ "3 A Light in the Attic 2024-11 107 neutral\n",
1186
+ "4 A Light in the Attic 2024-12 108 neutral\n"
1187
+ ]
1188
+ }
1189
+ ],
1190
+ "source": [
1191
+ "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
1192
+ "\n",
1193
+ "print(df_sales.head())"
1194
+ ]
1195
+ },
1196
+ {
1197
+ "cell_type": "markdown",
1198
+ "metadata": {
1199
+ "id": "7g9gqBgQMtJn"
1200
+ },
1201
+ "source": [
1202
+ "## **5.** 🎯 Generate synthetic customer reviews"
1203
+ ]
1204
+ },
1205
+ {
1206
+ "cell_type": "markdown",
1207
+ "metadata": {
1208
+ "id": "Gi4y9M9KuDWx"
1209
+ },
1210
+ "source": [
1211
+ "### *a. ✋🏻🛑⛔️ Ask ChatGPT to create a list of 50 distinct generic book review texts for the sentiment labels \"positive\", \"neutral\", and \"negative\" called synthetic_reviews_by_sentiment*"
1212
+ ]
1213
+ },
1214
+ {
1215
+ "cell_type": "code",
1216
+ "execution_count": 20,
1217
+ "metadata": {
1218
+ "id": "b3cd2a50"
1219
+ },
1220
+ "outputs": [],
1221
+ "source": [
1222
+ "synthetic_reviews_by_sentiment = {\n",
1223
+ " \"positive\": [\n",
1224
+ " \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
1225
+ " \"Brilliantly written! The characters were unforgettable and the plot was engaging.\",\n",
1226
+ " \"One of the best books I've read this year — inspiring and emotionally rich.\",\n",
1227
+ " ],\n",
1228
+ " \"neutral\": [\n",
1229
+ " \"An average book — not great, but not bad either.\",\n",
1230
+ " \"Some parts really stood out, others felt a bit flat.\",\n",
1231
+ " \"It was okay overall. A decent way to pass the time.\",\n",
1232
+ " ],\n",
1233
+ " \"negative\": [\n",
1234
+ " \"I struggled to get through this one — it just didn’t grab me.\",\n",
1235
+ " \"The plot was confusing and the characters felt underdeveloped.\",\n",
1236
+ " \"Disappointing. I had high hopes, but they weren't met.\",\n",
1237
+ " ]\n",
1238
+ "}"
1239
+ ]
1240
+ },
1241
+ {
1242
+ "cell_type": "markdown",
1243
+ "metadata": {
1244
+ "id": "fQhfVaDmuULT"
1245
+ },
1246
+ "source": [
1247
+ "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
1248
+ ]
1249
+ },
1250
+ {
1251
+ "cell_type": "code",
1252
+ "execution_count": 22,
1253
+ "metadata": {
1254
+ "id": "l2SRc3PjuTGM"
1255
+ },
1256
+ "outputs": [],
1257
+ "source": [
1258
+ "review_rows = []\n",
1259
+ "\n",
1260
+ "for _, row in df_books.iterrows():\n",
1261
+ " title = row['title']\n",
1262
+ " sentiment_label = row['sentiment_label']\n",
1263
+ " review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
1264
+ "\n",
1265
+ " k = min(10, len(review_pool)) # évite l'erreur\n",
1266
+ " sampled_reviews = random.sample(review_pool, k)\n",
1267
+ "\n",
1268
+ " for review_text in sampled_reviews:\n",
1269
+ " review_rows.append({\n",
1270
+ " \"title\": title,\n",
1271
+ " \"sentiment_label\": sentiment_label,\n",
1272
+ " \"review_text\": review_text,\n",
1273
+ " \"rating\": row['rating'],\n",
1274
+ " \"popularity_score\": row['popularity_score']\n",
1275
+ " })"
1276
+ ]
1277
+ },
1278
+ {
1279
+ "cell_type": "markdown",
1280
+ "metadata": {
1281
+ "id": "bmJMXF-Bukdm"
1282
+ },
1283
+ "source": [
1284
+ "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
1285
+ ]
1286
+ },
1287
+ {
1288
+ "cell_type": "code",
1289
+ "execution_count": 23,
1290
+ "metadata": {
1291
+ "id": "ZUKUqZsuumsp"
1292
+ },
1293
+ "outputs": [],
1294
+ "source": [
1295
+ "df_reviews = pd.DataFrame(review_rows)\n",
1296
+ "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
1297
+ ]
1298
+ },
1299
+ {
1300
+ "cell_type": "markdown",
1301
+ "source": [
1302
+ "### *c. inputs for R*"
1303
+ ],
1304
+ "metadata": {
1305
+ "id": "_602pYUS3gY5"
1306
+ }
1307
+ },
1308
+ {
1309
+ "cell_type": "code",
1310
+ "execution_count": 24,
1311
+ "metadata": {
1312
+ "colab": {
1313
+ "base_uri": "https://localhost:8080/"
1314
+ },
1315
+ "id": "3946e521",
1316
+ "outputId": "153a8926-fd75-469a-b014-a5521aa7e993"
1317
+ },
1318
+ "outputs": [
1319
+ {
1320
+ "output_type": "stream",
1321
+ "name": "stdout",
1322
+ "text": [
1323
+ "✅ Wrote synthetic_title_level_features.csv\n",
1324
+ "✅ Wrote synthetic_monthly_revenue_series.csv\n"
1325
+ ]
1326
+ }
1327
+ ],
1328
+ "source": [
1329
+ "import numpy as np\n",
1330
+ "\n",
1331
+ "def _safe_num(s):\n",
1332
+ " return pd.to_numeric(\n",
1333
+ " pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
1334
+ " errors=\"coerce\"\n",
1335
+ " )\n",
1336
+ "\n",
1337
+ "# --- Clean book metadata (price/rating) ---\n",
1338
+ "df_books_r = df_books.copy()\n",
1339
+ "if \"price\" in df_books_r.columns:\n",
1340
+ " df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
1341
+ "if \"rating\" in df_books_r.columns:\n",
1342
+ " df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
1343
+ "\n",
1344
+ "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
1345
+ "\n",
1346
+ "# --- Clean sales ---\n",
1347
+ "df_sales_r = df_sales.copy()\n",
1348
+ "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
1349
+ "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
1350
+ "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
1351
+ "\n",
1352
+ "# --- Clean reviews ---\n",
1353
+ "df_reviews_r = df_reviews.copy()\n",
1354
+ "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
1355
+ "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
1356
+ "if \"rating\" in df_reviews_r.columns:\n",
1357
+ " df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
1358
+ "if \"popularity_score\" in df_reviews_r.columns:\n",
1359
+ " df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
1360
+ "\n",
1361
+ "# --- Sentiment shares per title (from reviews) ---\n",
1362
+ "sent_counts = (\n",
1363
+ " df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
1364
+ " .size()\n",
1365
+ " .unstack(fill_value=0)\n",
1366
+ ")\n",
1367
+ "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
1368
+ " if lab not in sent_counts.columns:\n",
1369
+ " sent_counts[lab] = 0\n",
1370
+ "\n",
1371
+ "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
1372
+ "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
1373
+ "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
1374
+ "sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
1375
+ "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
1376
+ "sent_counts = sent_counts.reset_index()\n",
1377
+ "\n",
1378
+ "# --- Sales aggregation per title ---\n",
1379
+ "sales_by_title = (\n",
1380
+ " df_sales_r.dropna(subset=[\"title\"])\n",
1381
+ " .groupby(\"title\", as_index=False)\n",
1382
+ " .agg(\n",
1383
+ " months_observed=(\"month\", \"nunique\"),\n",
1384
+ " avg_units_sold=(\"units_sold\", \"mean\"),\n",
1385
+ " total_units_sold=(\"units_sold\", \"sum\"),\n",
1386
+ " )\n",
1387
+ ")\n",
1388
+ "\n",
1389
+ "# --- Title-level features (join sales + books + sentiment) ---\n",
1390
+ "df_title = (\n",
1391
+ " sales_by_title\n",
1392
+ " .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
1393
+ " .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
1394
+ " on=\"title\", how=\"left\")\n",
1395
+ ")\n",
1396
+ "\n",
1397
+ "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
1398
+ "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
1399
+ "\n",
1400
+ "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
1401
+ "print(\"✅ Wrote synthetic_title_level_features.csv\")\n",
1402
+ "\n",
1403
+ "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
1404
+ "monthly_rev = (\n",
1405
+ " df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
1406
+ ")\n",
1407
+ "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
1408
+ "\n",
1409
+ "df_monthly = (\n",
1410
+ " monthly_rev.dropna(subset=[\"month\"])\n",
1411
+ " .groupby(\"month\", as_index=False)[\"revenue\"]\n",
1412
+ " .sum()\n",
1413
+ " .rename(columns={\"revenue\": \"total_revenue\"})\n",
1414
+ " .sort_values(\"month\")\n",
1415
+ ")\n",
1416
+ "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
1417
+ "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
1418
+ " df_monthly = (\n",
1419
+ " df_sales_r.dropna(subset=[\"month\"])\n",
1420
+ " .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
1421
+ " .sum()\n",
1422
+ " .rename(columns={\"units_sold\": \"total_revenue\"})\n",
1423
+ " .sort_values(\"month\")\n",
1424
+ " )\n",
1425
+ "\n",
1426
+ "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
1427
+ "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
1428
+ "print(\"✅ Wrote synthetic_monthly_revenue_series.csv\")\n"
1429
+ ]
1430
+ },
1431
+ {
1432
+ "cell_type": "markdown",
1433
+ "metadata": {
1434
+ "id": "RYvGyVfXuo54"
1435
+ },
1436
+ "source": [
1437
+ "### *d. ✋🏻🛑⛔️ View the first few lines*"
1438
+ ]
1439
+ },
1440
+ {
1441
+ "cell_type": "code",
1442
+ "execution_count": 26,
1443
+ "metadata": {
1444
+ "colab": {
1445
+ "base_uri": "https://localhost:8080/",
1446
+ "height": 582
1447
+ },
1448
+ "id": "xfE8NMqOurKo",
1449
+ "outputId": "7d4e55a3-c54b-4767-dffd-97571a4b6844"
1450
+ },
1451
+ "outputs": [
1452
+ {
1453
+ "output_type": "stream",
1454
+ "name": "stdout",
1455
+ "text": [
1456
+ "=== Title Level Features ===\n"
1457
+ ]
1458
+ },
1459
+ {
1460
+ "output_type": "display_data",
1461
+ "data": {
1462
+ "text/plain": [
1463
+ " title months_observed \\\n",
1464
+ "0 \"Most Blessed of the Patriarchs\": Thomas Jeffe... 18 \n",
1465
+ "1 #GIRLBOSS 18 \n",
1466
+ "2 #HigherSelfie: Wake Up Your Life. Free Your So... 18 \n",
1467
+ "3 'Salem's Lot 18 \n",
1468
+ "4 (Un)Qualified: How God Uses Broken People to D... 18 \n",
1469
+ "\n",
1470
+ " avg_units_sold total_units_sold price rating share_positive \\\n",
1471
+ "0 285.555556 5140 44.48 NaN 1.0 \n",
1472
+ "1 47.944444 863 50.96 NaN 0.0 \n",
1473
+ "2 226.777778 4082 23.11 NaN 1.0 \n",
1474
+ "3 246.055556 4429 49.56 NaN 1.0 \n",
1475
+ "4 294.444444 5300 54.00 NaN 1.0 \n",
1476
+ "\n",
1477
+ " share_neutral share_negative total_reviews avg_revenue total_revenue \n",
1478
+ "0 0.0 0.0 3 12701.511111 228627.20 \n",
1479
+ "1 0.0 1.0 3 2443.248889 43978.48 \n",
1480
+ "2 0.0 0.0 3 5240.834444 94335.02 \n",
1481
+ "3 0.0 0.0 3 12194.513333 219501.24 \n",
1482
+ "4 0.0 0.0 3 15900.000000 286200.00 "
1483
+ ],
1484
+ "text/html": [
1485
+ "\n",
1486
+ " <div id=\"df-df208499-199e-4afa-9d88-ddc263b70c68\" class=\"colab-df-container\">\n",
1487
+ " <div>\n",
1488
+ "<style scoped>\n",
1489
+ " .dataframe tbody tr th:only-of-type {\n",
1490
+ " vertical-align: middle;\n",
1491
+ " }\n",
1492
+ "\n",
1493
+ " .dataframe tbody tr th {\n",
1494
+ " vertical-align: top;\n",
1495
+ " }\n",
1496
+ "\n",
1497
+ " .dataframe thead th {\n",
1498
+ " text-align: right;\n",
1499
+ " }\n",
1500
+ "</style>\n",
1501
+ "<table border=\"1\" class=\"dataframe\">\n",
1502
+ " <thead>\n",
1503
+ " <tr style=\"text-align: right;\">\n",
1504
+ " <th></th>\n",
1505
+ " <th>title</th>\n",
1506
+ " <th>months_observed</th>\n",
1507
+ " <th>avg_units_sold</th>\n",
1508
+ " <th>total_units_sold</th>\n",
1509
+ " <th>price</th>\n",
1510
+ " <th>rating</th>\n",
1511
+ " <th>share_positive</th>\n",
1512
+ " <th>share_neutral</th>\n",
1513
+ " <th>share_negative</th>\n",
1514
+ " <th>total_reviews</th>\n",
1515
+ " <th>avg_revenue</th>\n",
1516
+ " <th>total_revenue</th>\n",
1517
+ " </tr>\n",
1518
+ " </thead>\n",
1519
+ " <tbody>\n",
1520
+ " <tr>\n",
1521
+ " <th>0</th>\n",
1522
+ " <td>\"Most Blessed of the Patriarchs\": Thomas Jeffe...</td>\n",
1523
+ " <td>18</td>\n",
1524
+ " <td>285.555556</td>\n",
1525
+ " <td>5140</td>\n",
1526
+ " <td>44.48</td>\n",
1527
+ " <td>NaN</td>\n",
1528
+ " <td>1.0</td>\n",
1529
+ " <td>0.0</td>\n",
1530
+ " <td>0.0</td>\n",
1531
+ " <td>3</td>\n",
1532
+ " <td>12701.511111</td>\n",
1533
+ " <td>228627.20</td>\n",
1534
+ " </tr>\n",
1535
+ " <tr>\n",
1536
+ " <th>1</th>\n",
1537
+ " <td>#GIRLBOSS</td>\n",
1538
+ " <td>18</td>\n",
1539
+ " <td>47.944444</td>\n",
1540
+ " <td>863</td>\n",
1541
+ " <td>50.96</td>\n",
1542
+ " <td>NaN</td>\n",
1543
+ " <td>0.0</td>\n",
1544
+ " <td>0.0</td>\n",
1545
+ " <td>1.0</td>\n",
1546
+ " <td>3</td>\n",
1547
+ " <td>2443.248889</td>\n",
1548
+ " <td>43978.48</td>\n",
1549
+ " </tr>\n",
1550
+ " <tr>\n",
1551
+ " <th>2</th>\n",
1552
+ " <td>#HigherSelfie: Wake Up Your Life. Free Your So...</td>\n",
1553
+ " <td>18</td>\n",
1554
+ " <td>226.777778</td>\n",
1555
+ " <td>4082</td>\n",
1556
+ " <td>23.11</td>\n",
1557
+ " <td>NaN</td>\n",
1558
+ " <td>1.0</td>\n",
1559
+ " <td>0.0</td>\n",
1560
+ " <td>0.0</td>\n",
1561
+ " <td>3</td>\n",
1562
+ " <td>5240.834444</td>\n",
1563
+ " <td>94335.02</td>\n",
1564
+ " </tr>\n",
1565
+ " <tr>\n",
1566
+ " <th>3</th>\n",
1567
+ " <td>'Salem's Lot</td>\n",
1568
+ " <td>18</td>\n",
1569
+ " <td>246.055556</td>\n",
1570
+ " <td>4429</td>\n",
1571
+ " <td>49.56</td>\n",
1572
+ " <td>NaN</td>\n",
1573
+ " <td>1.0</td>\n",
1574
+ " <td>0.0</td>\n",
1575
+ " <td>0.0</td>\n",
1576
+ " <td>3</td>\n",
1577
+ " <td>12194.513333</td>\n",
1578
+ " <td>219501.24</td>\n",
1579
+ " </tr>\n",
1580
+ " <tr>\n",
1581
+ " <th>4</th>\n",
1582
+ " <td>(Un)Qualified: How God Uses Broken People to D...</td>\n",
1583
+ " <td>18</td>\n",
1584
+ " <td>294.444444</td>\n",
1585
+ " <td>5300</td>\n",
1586
+ " <td>54.00</td>\n",
1587
+ " <td>NaN</td>\n",
1588
+ " <td>1.0</td>\n",
1589
+ " <td>0.0</td>\n",
1590
+ " <td>0.0</td>\n",
1591
+ " <td>3</td>\n",
1592
+ " <td>15900.000000</td>\n",
1593
+ " <td>286200.00</td>\n",
1594
+ " </tr>\n",
1595
+ " </tbody>\n",
1596
+ "</table>\n",
1597
+ "</div>\n",
1598
+ " <div class=\"colab-df-buttons\">\n",
1599
+ "\n",
1600
+ " <div class=\"colab-df-container\">\n",
1601
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-df208499-199e-4afa-9d88-ddc263b70c68')\"\n",
1602
+ " title=\"Convert this dataframe to an interactive table.\"\n",
1603
+ " style=\"display:none;\">\n",
1604
+ "\n",
1605
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
1606
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
1607
+ " </svg>\n",
1608
+ " </button>\n",
1609
+ "\n",
1610
+ " <style>\n",
1611
+ " .colab-df-container {\n",
1612
+ " display:flex;\n",
1613
+ " gap: 12px;\n",
1614
+ " }\n",
1615
+ "\n",
1616
+ " .colab-df-convert {\n",
1617
+ " background-color: #E8F0FE;\n",
1618
+ " border: none;\n",
1619
+ " border-radius: 50%;\n",
1620
+ " cursor: pointer;\n",
1621
+ " display: none;\n",
1622
+ " fill: #1967D2;\n",
1623
+ " height: 32px;\n",
1624
+ " padding: 0 0 0 0;\n",
1625
+ " width: 32px;\n",
1626
+ " }\n",
1627
+ "\n",
1628
+ " .colab-df-convert:hover {\n",
1629
+ " background-color: #E2EBFA;\n",
1630
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
1631
+ " fill: #174EA6;\n",
1632
+ " }\n",
1633
+ "\n",
1634
+ " .colab-df-buttons div {\n",
1635
+ " margin-bottom: 4px;\n",
1636
+ " }\n",
1637
+ "\n",
1638
+ " [theme=dark] .colab-df-convert {\n",
1639
+ " background-color: #3B4455;\n",
1640
+ " fill: #D2E3FC;\n",
1641
+ " }\n",
1642
+ "\n",
1643
+ " [theme=dark] .colab-df-convert:hover {\n",
1644
+ " background-color: #434B5C;\n",
1645
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
1646
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
1647
+ " fill: #FFFFFF;\n",
1648
+ " }\n",
1649
+ " </style>\n",
1650
+ "\n",
1651
+ " <script>\n",
1652
+ " const buttonEl =\n",
1653
+ " document.querySelector('#df-df208499-199e-4afa-9d88-ddc263b70c68 button.colab-df-convert');\n",
1654
+ " buttonEl.style.display =\n",
1655
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
1656
+ "\n",
1657
+ " async function convertToInteractive(key) {\n",
1658
+ " const element = document.querySelector('#df-df208499-199e-4afa-9d88-ddc263b70c68');\n",
1659
+ " const dataTable =\n",
1660
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
1661
+ " [key], {});\n",
1662
+ " if (!dataTable) return;\n",
1663
+ "\n",
1664
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
1665
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
1666
+ " + ' to learn more about interactive tables.';\n",
1667
+ " element.innerHTML = '';\n",
1668
+ " dataTable['output_type'] = 'display_data';\n",
1669
+ " await google.colab.output.renderOutput(dataTable, element);\n",
1670
+ " const docLink = document.createElement('div');\n",
1671
+ " docLink.innerHTML = docLinkHtml;\n",
1672
+ " element.appendChild(docLink);\n",
1673
+ " }\n",
1674
+ " </script>\n",
1675
+ " </div>\n",
1676
+ "\n",
1677
+ "\n",
1678
+ " </div>\n",
1679
+ " </div>\n"
1680
+ ],
1681
+ "application/vnd.google.colaboratory.intrinsic+json": {
1682
+ "type": "dataframe",
1683
+ "summary": "{\n \"name\": \"display(df_monthly\",\n \"rows\": 5,\n \"fields\": [\n {\n \"column\": \"title\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"#GIRLBOSS\",\n \"(Un)Qualified: How God Uses Broken People to Do Big Things\",\n \"#HigherSelfie: Wake Up Your Life. Free Your Soul. Find Your Tribe.\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"months_observed\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 18,\n \"max\": 18,\n \"num_unique_values\": 1,\n \"samples\": [\n 18\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"avg_units_sold\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 100.20894374958456,\n \"min\": 47.94444444444444,\n \"max\": 294.44444444444446,\n \"num_unique_values\": 5,\n \"samples\": [\n 47.94444444444444\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"total_units_sold\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 1803,\n \"min\": 863,\n \"max\": 5300,\n \"num_unique_values\": 5,\n \"samples\": [\n 863\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"price\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 12.400476603743908,\n \"min\": 23.11,\n \"max\": 54.0,\n \"num_unique_values\": 5,\n \"samples\": [\n 50.96\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"rating\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": null,\n \"min\": null,\n \"max\": null,\n \"num_unique_values\": 0,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"share_positive\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.44721359549995804,\n \"min\": 0.0,\n \"max\": 1.0,\n \"num_unique_values\": 2,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"share_neutral\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.0,\n \"min\": 0.0,\n \"max\": 0.0,\n \"num_unique_values\": 1,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"share_negative\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0.44721359549995804,\n \"min\": 0.0,\n \"max\": 1.0,\n \"num_unique_values\": 2,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"total_reviews\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 0,\n \"min\": 3,\n \"max\": 3,\n \"num_unique_values\": 1,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"avg_revenue\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 5617.298744073206,\n \"min\": 2443.248888888889,\n \"max\": 15900.0,\n \"num_unique_values\": 5,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"total_revenue\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 101111.37739331771,\n \"min\": 43978.48,\n \"max\": 286200.0,\n \"num_unique_values\": 5,\n \"samples\": [],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
1684
+ }
1685
+ },
1686
+ "metadata": {}
1687
+ },
1688
+ {
1689
+ "output_type": "stream",
1690
+ "name": "stdout",
1691
+ "text": [
1692
+ "\n",
1693
+ "=== Monthly Revenue Series ===\n"
1694
+ ]
1695
+ },
1696
+ {
1697
+ "output_type": "display_data",
1698
+ "data": {
1699
+ "text/plain": [
1700
+ " month total_revenue\n",
1701
+ "0 2024-08-01 5631956.77\n",
1702
+ "1 2024-09-01 5856653.68\n",
1703
+ "2 2024-10-01 6006876.26\n",
1704
+ "3 2024-11-01 6061519.85\n",
1705
+ "4 2024-12-01 6014276.79"
1706
+ ],
1707
+ "text/html": [
1708
+ "\n",
1709
+ " <div id=\"df-221ee90f-15dc-4886-9fe9-d57045ecc527\" class=\"colab-df-container\">\n",
1710
+ " <div>\n",
1711
+ "<style scoped>\n",
1712
+ " .dataframe tbody tr th:only-of-type {\n",
1713
+ " vertical-align: middle;\n",
1714
+ " }\n",
1715
+ "\n",
1716
+ " .dataframe tbody tr th {\n",
1717
+ " vertical-align: top;\n",
1718
+ " }\n",
1719
+ "\n",
1720
+ " .dataframe thead th {\n",
1721
+ " text-align: right;\n",
1722
+ " }\n",
1723
+ "</style>\n",
1724
+ "<table border=\"1\" class=\"dataframe\">\n",
1725
+ " <thead>\n",
1726
+ " <tr style=\"text-align: right;\">\n",
1727
+ " <th></th>\n",
1728
+ " <th>month</th>\n",
1729
+ " <th>total_revenue</th>\n",
1730
+ " </tr>\n",
1731
+ " </thead>\n",
1732
+ " <tbody>\n",
1733
+ " <tr>\n",
1734
+ " <th>0</th>\n",
1735
+ " <td>2024-08-01</td>\n",
1736
+ " <td>5631956.77</td>\n",
1737
+ " </tr>\n",
1738
+ " <tr>\n",
1739
+ " <th>1</th>\n",
1740
+ " <td>2024-09-01</td>\n",
1741
+ " <td>5856653.68</td>\n",
1742
+ " </tr>\n",
1743
+ " <tr>\n",
1744
+ " <th>2</th>\n",
1745
+ " <td>2024-10-01</td>\n",
1746
+ " <td>6006876.26</td>\n",
1747
+ " </tr>\n",
1748
+ " <tr>\n",
1749
+ " <th>3</th>\n",
1750
+ " <td>2024-11-01</td>\n",
1751
+ " <td>6061519.85</td>\n",
1752
+ " </tr>\n",
1753
+ " <tr>\n",
1754
+ " <th>4</th>\n",
1755
+ " <td>2024-12-01</td>\n",
1756
+ " <td>6014276.79</td>\n",
1757
+ " </tr>\n",
1758
+ " </tbody>\n",
1759
+ "</table>\n",
1760
+ "</div>\n",
1761
+ " <div class=\"colab-df-buttons\">\n",
1762
+ "\n",
1763
+ " <div class=\"colab-df-container\">\n",
1764
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-221ee90f-15dc-4886-9fe9-d57045ecc527')\"\n",
1765
+ " title=\"Convert this dataframe to an interactive table.\"\n",
1766
+ " style=\"display:none;\">\n",
1767
+ "\n",
1768
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
1769
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
1770
+ " </svg>\n",
1771
+ " </button>\n",
1772
+ "\n",
1773
+ " <style>\n",
1774
+ " .colab-df-container {\n",
1775
+ " display:flex;\n",
1776
+ " gap: 12px;\n",
1777
+ " }\n",
1778
+ "\n",
1779
+ " .colab-df-convert {\n",
1780
+ " background-color: #E8F0FE;\n",
1781
+ " border: none;\n",
1782
+ " border-radius: 50%;\n",
1783
+ " cursor: pointer;\n",
1784
+ " display: none;\n",
1785
+ " fill: #1967D2;\n",
1786
+ " height: 32px;\n",
1787
+ " padding: 0 0 0 0;\n",
1788
+ " width: 32px;\n",
1789
+ " }\n",
1790
+ "\n",
1791
+ " .colab-df-convert:hover {\n",
1792
+ " background-color: #E2EBFA;\n",
1793
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
1794
+ " fill: #174EA6;\n",
1795
+ " }\n",
1796
+ "\n",
1797
+ " .colab-df-buttons div {\n",
1798
+ " margin-bottom: 4px;\n",
1799
+ " }\n",
1800
+ "\n",
1801
+ " [theme=dark] .colab-df-convert {\n",
1802
+ " background-color: #3B4455;\n",
1803
+ " fill: #D2E3FC;\n",
1804
+ " }\n",
1805
+ "\n",
1806
+ " [theme=dark] .colab-df-convert:hover {\n",
1807
+ " background-color: #434B5C;\n",
1808
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
1809
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
1810
+ " fill: #FFFFFF;\n",
1811
+ " }\n",
1812
+ " </style>\n",
1813
+ "\n",
1814
+ " <script>\n",
1815
+ " const buttonEl =\n",
1816
+ " document.querySelector('#df-221ee90f-15dc-4886-9fe9-d57045ecc527 button.colab-df-convert');\n",
1817
+ " buttonEl.style.display =\n",
1818
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
1819
+ "\n",
1820
+ " async function convertToInteractive(key) {\n",
1821
+ " const element = document.querySelector('#df-221ee90f-15dc-4886-9fe9-d57045ecc527');\n",
1822
+ " const dataTable =\n",
1823
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
1824
+ " [key], {});\n",
1825
+ " if (!dataTable) return;\n",
1826
+ "\n",
1827
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
1828
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
1829
+ " + ' to learn more about interactive tables.';\n",
1830
+ " element.innerHTML = '';\n",
1831
+ " dataTable['output_type'] = 'display_data';\n",
1832
+ " await google.colab.output.renderOutput(dataTable, element);\n",
1833
+ " const docLink = document.createElement('div');\n",
1834
+ " docLink.innerHTML = docLinkHtml;\n",
1835
+ " element.appendChild(docLink);\n",
1836
+ " }\n",
1837
+ " </script>\n",
1838
+ " </div>\n",
1839
+ "\n",
1840
+ "\n",
1841
+ " </div>\n",
1842
+ " </div>\n"
1843
+ ],
1844
+ "application/vnd.google.colaboratory.intrinsic+json": {
1845
+ "type": "dataframe",
1846
+ "summary": "{\n \"name\": \"display(df_monthly\",\n \"rows\": 5,\n \"fields\": [\n {\n \"column\": \"month\",\n \"properties\": {\n \"dtype\": \"object\",\n \"num_unique_values\": 5,\n \"samples\": [\n \"2024-09-01\",\n \"2024-12-01\",\n \"2024-10-01\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"total_revenue\",\n \"properties\": {\n \"dtype\": \"number\",\n \"std\": 175556.39765987248,\n \"min\": 5631956.77,\n \"max\": 6061519.85,\n \"num_unique_values\": 5,\n \"samples\": [\n 5856653.68,\n 6014276.79,\n 6006876.26\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}"
1847
+ }
1848
+ },
1849
+ "metadata": {}
1850
+ }
1851
+ ],
1852
+ "source": [
1853
+ "print(\"=== Title Level Features ===\")\n",
1854
+ "display(df_title.head())\n",
1855
+ "\n",
1856
+ "print(\"\\n=== Monthly Revenue Series ===\")\n",
1857
+ "display(df_monthly.head())"
1858
+ ]
1859
+ }
1860
+ ],
1861
+ "metadata": {
1862
+ "colab": {
1863
+ "collapsed_sections": [
1864
+ "jpASMyIQMaAq",
1865
+ "lquNYCbfL9IM",
1866
+ "0IWuNpxxYDJF",
1867
+ "oCdTsin2Yfp3",
1868
+ "T0TOeRC4Yrnn",
1869
+ "duI5dv3CZYvF",
1870
+ "qMjRKMBQZlJi",
1871
+ "p-1Pr2szaqLk",
1872
+ "SIaJUGIpaH4V",
1873
+ "pY4yCoIuaQqp",
1874
+ "n4-TaNTFgPak",
1875
+ "HnngRNTgacYt",
1876
+ "HF9F9HIzgT7Z",
1877
+ "T8AdKkmASq9a",
1878
+ "OhXbdGD5fH0c",
1879
+ "L2ak1HlcgoTe",
1880
+ "4IXZKcCSgxnq",
1881
+ "EhIjz9WohAmZ",
1882
+ "Gi4y9M9KuDWx",
1883
+ "fQhfVaDmuULT",
1884
+ "bmJMXF-Bukdm",
1885
+ "RYvGyVfXuo54"
1886
+ ],
1887
+ "provenance": []
1888
+ },
1889
+ "kernelspec": {
1890
+ "display_name": "Python 3",
1891
+ "name": "python3"
1892
+ },
1893
+ "language_info": {
1894
+ "name": "python"
1895
+ }
1896
+ },
1897
+ "nbformat": 4,
1898
+ "nbformat_minor": 0
1899
+ }
2a_Python_Analysis-Laure-Dumont.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
R_analysis_Laure_Dumont.ipynb ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "75fd9cc6",
6
+ "metadata": {
7
+ "id": "75fd9cc6"
8
+ },
9
+ "source": [
10
+ "# **🤖 Benchmarking & Modeling**"
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "fb807724",
16
+ "metadata": {
17
+ "id": "fb807724"
18
+ },
19
+ "source": [
20
+ "## **1.** 📦 Setup"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "execution_count": 6,
26
+ "id": "d40cd131",
27
+ "metadata": {
28
+ "id": "d40cd131",
29
+ "outputId": "f520f27c-3e9c-470d-c36b-0267ff1c4949",
30
+ "colab": {
31
+ "base_uri": "https://localhost:8080/"
32
+ }
33
+ },
34
+ "outputs": [
35
+ {
36
+ "output_type": "stream",
37
+ "name": "stderr",
38
+ "text": [
39
+ "Installing packages into ‘/usr/local/lib/R/site-library’\n",
40
+ "(as ‘lib’ is unspecified)\n",
41
+ "\n",
42
+ "Warning message in install.packages(c(\"readr\", \"dplyr\", \"stringr\", \"tidyr\", \"lubridate\", :\n",
43
+ "“installation of package ‘forecast’ had non-zero exit status”\n"
44
+ ]
45
+ }
46
+ ],
47
+ "source": [
48
+ "install.packages(c(\n",
49
+ " \"readr\",\"dplyr\",\"stringr\",\"tidyr\",\"lubridate\",\n",
50
+ " \"ggplot2\",\"forecast\",\"broom\",\"jsonlite\"\n",
51
+ "), repos=\"https://cloud.r-project.org\")"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "source": [
57
+ "#do above first and then Runtime → Restart session and then do:\n",
58
+ "library(readr)\n",
59
+ "library(dplyr)\n",
60
+ "library(stringr)\n",
61
+ "library(tidyr)\n",
62
+ "library(lubridate)\n",
63
+ "library(ggplot2)\n",
64
+ "library(forecast)\n",
65
+ "library(broom)\n",
66
+ "library(jsonlite)"
67
+ ],
68
+ "metadata": {
69
+ "colab": {
70
+ "base_uri": "https://localhost:8080/"
71
+ },
72
+ "id": "FR_YZUD9J_Py",
73
+ "outputId": "6b801e29-0053-469f-b4c9-05d8ead19904"
74
+ },
75
+ "id": "FR_YZUD9J_Py",
76
+ "execution_count": 1,
77
+ "outputs": [
78
+ {
79
+ "output_type": "stream",
80
+ "name": "stderr",
81
+ "text": [
82
+ "\n",
83
+ "Attaching package: ‘dplyr’\n",
84
+ "\n",
85
+ "\n",
86
+ "The following objects are masked from ‘package:stats’:\n",
87
+ "\n",
88
+ " filter, lag\n",
89
+ "\n",
90
+ "\n",
91
+ "The following objects are masked from ‘package:base’:\n",
92
+ "\n",
93
+ " intersect, setdiff, setequal, union\n",
94
+ "\n",
95
+ "\n",
96
+ "\n",
97
+ "Attaching package: ‘lubridate’\n",
98
+ "\n",
99
+ "\n",
100
+ "The following objects are masked from ‘package:base’:\n",
101
+ "\n",
102
+ " date, intersect, setdiff, union\n",
103
+ "\n",
104
+ "\n"
105
+ ]
106
+ }
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "markdown",
111
+ "id": "f01d02e7",
112
+ "metadata": {
113
+ "id": "f01d02e7"
114
+ },
115
+ "source": [
116
+ "## **2.** ✅️ Load & inspect inputs"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "execution_count": 3,
122
+ "id": "29e8f6ce",
123
+ "metadata": {
124
+ "colab": {
125
+ "base_uri": "https://localhost:8080/"
126
+ },
127
+ "id": "29e8f6ce",
128
+ "outputId": "9af6e4c9-59d9-4475-a106-beada0b3338c"
129
+ },
130
+ "outputs": [
131
+ {
132
+ "output_type": "stream",
133
+ "name": "stdout",
134
+ "text": [
135
+ "Loaded: 1000 rows (title-level), 18 rows (monthly)\n"
136
+ ]
137
+ }
138
+ ],
139
+ "source": [
140
+ "\n",
141
+ "must_exist <- function(path, label) {\n",
142
+ " if (!file.exists(path)) stop(paste0(\"Missing \", label, \": \", path))\n",
143
+ "}\n",
144
+ "\n",
145
+ "TITLE_PATH <- \"synthetic_title_level_features.csv\"\n",
146
+ "MONTH_PATH <- \"synthetic_monthly_revenue_series.csv\"\n",
147
+ "\n",
148
+ "must_exist(TITLE_PATH, \"TITLE_PATH\")\n",
149
+ "must_exist(MONTH_PATH, \"MONTH_PATH\")\n",
150
+ "\n",
151
+ "df_title <- read_csv(TITLE_PATH, show_col_types = FALSE)\n",
152
+ "df_month <- read_csv(MONTH_PATH, show_col_types = FALSE)\n",
153
+ "\n",
154
+ "cat(\"Loaded:\", nrow(df_title), \"rows (title-level),\", nrow(df_month), \"rows (monthly)\n",
155
+ "\")"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "execution_count": 4,
161
+ "id": "9fd04262",
162
+ "metadata": {
163
+ "colab": {
164
+ "base_uri": "https://localhost:8080/"
165
+ },
166
+ "id": "9fd04262",
167
+ "outputId": "b7c028ba-157c-4d4f-db6c-9098104adec5"
168
+ },
169
+ "outputs": [
170
+ {
171
+ "output_type": "stream",
172
+ "name": "stdout",
173
+ "text": [
174
+ "\u001b[90m# A tibble: 1 × 6\u001b[39m\n",
175
+ " n na_avg_revenue na_price na_rating na_share_pos na_share_neg\n",
176
+ " \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m \u001b[3m\u001b[90m<int>\u001b[39m\u001b[23m\n",
177
+ "\u001b[90m1\u001b[39m \u001b[4m1\u001b[24m000 0 0 \u001b[4m1\u001b[24m000 0 0\n",
178
+ "Monthly rows after parsing: 18 \n"
179
+ ]
180
+ }
181
+ ],
182
+ "source": [
183
+ "\n",
184
+ "# ---------- helpers ----------\n",
185
+ "safe_num <- function(x) {\n",
186
+ " # strips anything that is not digit or dot\n",
187
+ " suppressWarnings(as.numeric(str_replace_all(as.character(x), \"[^0-9.]\", \"\")))\n",
188
+ "}\n",
189
+ "\n",
190
+ "parse_rating <- function(x) {\n",
191
+ " # Accept: 4, \"4\", \"4.0\", \"4/5\", \"4 out of 5\", \"⭐⭐⭐⭐\", etc.\n",
192
+ " x <- as.character(x)\n",
193
+ " x <- str_replace_all(x, \"⭐\", \"\")\n",
194
+ " x <- str_to_lower(x)\n",
195
+ " x <- str_replace_all(x, \"stars?\", \"\")\n",
196
+ " x <- str_replace_all(x, \"out of\", \"/\")\n",
197
+ " x <- str_replace_all(x, \"\\\\s+\", \"\")\n",
198
+ " x <- str_replace_all(x, \"[^0-9./]\", \"\")\n",
199
+ " suppressWarnings(as.numeric(str_extract(x, \"^[0-9.]+\")))\n",
200
+ "}\n",
201
+ "\n",
202
+ "parse_month <- function(x) {\n",
203
+ " x <- as.character(x)\n",
204
+ " # try YYYY-MM-DD, then YYYY-MM\n",
205
+ " out <- suppressWarnings(ymd(x))\n",
206
+ " if (mean(is.na(out)) > 0.5) out <- suppressWarnings(ymd(paste0(x, \"-01\")))\n",
207
+ " na_idx <- which(is.na(out))\n",
208
+ " if (length(na_idx) > 0) out[na_idx] <- suppressWarnings(ymd(paste0(x[na_idx], \"-01\")))\n",
209
+ " out\n",
210
+ "}\n",
211
+ "\n",
212
+ "# ---------- normalize keys ----------\n",
213
+ "df_title <- df_title %>% mutate(title = str_squish(as.character(title)))\n",
214
+ "df_month <- df_month %>% mutate(month = as.character(month))\n",
215
+ "\n",
216
+ "# ---------- parse numeric columns defensively ----------\n",
217
+ "need_cols_title <- c(\"title\",\"avg_revenue\",\"total_revenue\",\"price\",\"rating\",\"share_positive\",\"share_negative\",\"share_neutral\")\n",
218
+ "missing_title <- setdiff(need_cols_title, names(df_title))\n",
219
+ "if (length(missing_title) > 0) stop(paste0(\"df_title missing columns: \", paste(missing_title, collapse=\", \")))\n",
220
+ "\n",
221
+ "df_title <- df_title %>%\n",
222
+ " mutate(\n",
223
+ " avg_revenue = safe_num(avg_revenue),\n",
224
+ " total_revenue = safe_num(total_revenue),\n",
225
+ " price = safe_num(price),\n",
226
+ " rating = parse_rating(rating),\n",
227
+ " share_positive = safe_num(share_positive),\n",
228
+ " share_negative = safe_num(share_negative),\n",
229
+ " share_neutral = safe_num(share_neutral)\n",
230
+ " )\n",
231
+ "\n",
232
+ "# basic sanity stats\n",
233
+ "hyg <- df_title %>%\n",
234
+ " summarise(\n",
235
+ " n = n(),\n",
236
+ " na_avg_revenue = sum(is.na(avg_revenue)),\n",
237
+ " na_price = sum(is.na(price)),\n",
238
+ " na_rating = sum(is.na(rating)),\n",
239
+ " na_share_pos = sum(is.na(share_positive)),\n",
240
+ " na_share_neg = sum(is.na(share_negative))\n",
241
+ " )\n",
242
+ "\n",
243
+ "print(hyg)\n",
244
+ "\n",
245
+ "# monthly parsing\n",
246
+ "need_cols_month <- c(\"month\",\"total_revenue\")\n",
247
+ "missing_month <- setdiff(need_cols_month, names(df_month))\n",
248
+ "if (length(missing_month) > 0) stop(paste0(\"df_month missing columns: \", paste(missing_month, collapse=\", \")))\n",
249
+ "\n",
250
+ "df_month2 <- df_month %>%\n",
251
+ " mutate(\n",
252
+ " month = parse_month(month),\n",
253
+ " total_revenue = safe_num(total_revenue)\n",
254
+ " ) %>%\n",
255
+ " filter(!is.na(month)) %>%\n",
256
+ " arrange(month)\n",
257
+ "\n",
258
+ "cat(\"Monthly rows after parsing:\", nrow(df_month2), \"\\n\")"
259
+ ]
260
+ },
261
+ {
262
+ "cell_type": "markdown",
263
+ "id": "b8971bc4",
264
+ "metadata": {
265
+ "id": "b8971bc4"
266
+ },
267
+ "source": [
268
+ "## **3.** 💾 Folder for R outputs for Hugging Face"
269
+ ]
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "execution_count": 5,
274
+ "id": "dfaa06b1",
275
+ "metadata": {
276
+ "colab": {
277
+ "base_uri": "https://localhost:8080/"
278
+ },
279
+ "id": "dfaa06b1",
280
+ "outputId": "85005150-1d3f-4c16-ffbe-ca7b91b379ab"
281
+ },
282
+ "outputs": [
283
+ {
284
+ "output_type": "stream",
285
+ "name": "stdout",
286
+ "text": [
287
+ "R outputs will be written to: /content/artifacts/r \n"
288
+ ]
289
+ }
290
+ ],
291
+ "source": [
292
+ "\n",
293
+ "ART_DIR <- \"artifacts\"\n",
294
+ "R_FIG_DIR <- file.path(ART_DIR, \"r\", \"figures\")\n",
295
+ "R_TAB_DIR <- file.path(ART_DIR, \"r\", \"tables\")\n",
296
+ "\n",
297
+ "dir.create(R_FIG_DIR, recursive = TRUE, showWarnings = FALSE)\n",
298
+ "dir.create(R_TAB_DIR, recursive = TRUE, showWarnings = FALSE)\n",
299
+ "\n",
300
+ "cat(\"R outputs will be written to:\", normalizePath(file.path(ART_DIR, \"r\"), winslash = \"/\"), \"\n",
301
+ "\")"
302
+ ]
303
+ },
304
+ {
305
+ "cell_type": "markdown",
306
+ "id": "f880c72d",
307
+ "metadata": {
308
+ "id": "f880c72d"
309
+ },
310
+ "source": [
311
+ "## **4.** 🔮 Forecast book sales benchmarking with `accuracy()`"
312
+ ]
313
+ },
314
+ {
315
+ "cell_type": "markdown",
316
+ "source": [
317
+ "We benchmark **three** models on a holdout window (last *h* months):\n",
318
+ "- ARIMA + Fourier (seasonality upgrade)\n",
319
+ "- ETS\n",
320
+ "- Naive baseline\n",
321
+ "\n",
322
+ "Then we export:\n",
323
+ "- `accuracy_table.csv`\n",
324
+ "- `forecast_compare.png`\n",
325
+ "- `rmse_comparison.png`"
326
+ ],
327
+ "metadata": {
328
+ "id": "R0JZlzKegmzW"
329
+ },
330
+ "id": "R0JZlzKegmzW"
331
+ },
332
+ {
333
+ "cell_type": "code",
334
+ "execution_count": 6,
335
+ "id": "62e87992",
336
+ "metadata": {
337
+ "colab": {
338
+ "base_uri": "https://localhost:8080/",
339
+ "height": 82
340
+ },
341
+ "id": "62e87992",
342
+ "outputId": "533ff3fe-2c85-4312-ab04-36007d0cbe1b"
343
+ },
344
+ "outputs": [
345
+ {
346
+ "output_type": "stream",
347
+ "name": "stdout",
348
+ "text": [
349
+ "✅ Saved: artifacts/r/tables/accuracy_table.csv\n",
350
+ "✅ Saved: artifacts/r/figures/rmse_comparison.png\n"
351
+ ]
352
+ },
353
+ {
354
+ "output_type": "display_data",
355
+ "data": {
356
+ "text/html": [
357
+ "<strong>agg_record_805943657:</strong> 2"
358
+ ],
359
+ "text/markdown": "**agg_record_805943657:** 2",
360
+ "text/latex": "\\textbf{agg\\textbackslash{}\\_record\\textbackslash{}\\_805943657:} 2",
361
+ "text/plain": [
362
+ "agg_record_805943657 \n",
363
+ " 2 "
364
+ ]
365
+ },
366
+ "metadata": {}
367
+ },
368
+ {
369
+ "output_type": "stream",
370
+ "name": "stdout",
371
+ "text": [
372
+ "✅ Saved: artifacts/r/figures/forecast_compare.png\n"
373
+ ]
374
+ }
375
+ ],
376
+ "source": [
377
+ "\n",
378
+ "# Build monthly ts\n",
379
+ "start_year <- year(min(df_month2$month, na.rm = TRUE))\n",
380
+ "start_mon <- month(min(df_month2$month, na.rm = TRUE))\n",
381
+ "\n",
382
+ "y <- ts(df_month2$total_revenue, frequency = 12, start = c(start_year, start_mon))\n",
383
+ "\n",
384
+ "# holdout size: min(6, 20% of series), at least 1\n",
385
+ "h_test <- min(6, max(1, floor(length(y) / 5)))\n",
386
+ "train_ts <- head(y, length(y) - h_test)\n",
387
+ "test_ts <- tail(y, h_test)\n",
388
+ "\n",
389
+ "# Model A: ARIMA + Fourier\n",
390
+ "K <- 2\n",
391
+ "xreg_train <- fourier(train_ts, K = K)\n",
392
+ "fit_arima <- auto.arima(train_ts, xreg = xreg_train)\n",
393
+ "xreg_future <- fourier(train_ts, K = K, h = h_test)\n",
394
+ "fc_arima <- forecast(fit_arima, xreg = xreg_future, h = h_test)\n",
395
+ "\n",
396
+ "# Model B: ETS\n",
397
+ "fit_ets <- ets(train_ts)\n",
398
+ "fc_ets <- forecast(fit_ets, h = h_test)\n",
399
+ "\n",
400
+ "# Model C: Naive baseline\n",
401
+ "fc_naive <- naive(train_ts, h = h_test)\n",
402
+ "\n",
403
+ "# accuracy() tables\n",
404
+ "acc_arima <- as.data.frame(accuracy(fc_arima, test_ts))\n",
405
+ "acc_ets <- as.data.frame(accuracy(fc_ets, test_ts))\n",
406
+ "acc_naive <- as.data.frame(accuracy(fc_naive, test_ts))\n",
407
+ "\n",
408
+ "accuracy_tbl <- bind_rows(\n",
409
+ " acc_arima %>% mutate(model = \"ARIMA+Fourier\"),\n",
410
+ " acc_ets %>% mutate(model = \"ETS\"),\n",
411
+ " acc_naive %>% mutate(model = \"Naive\")\n",
412
+ ") %>% relocate(model)\n",
413
+ "\n",
414
+ "write_csv(accuracy_tbl, file.path(R_TAB_DIR, \"accuracy_table.csv\"))\n",
415
+ "cat(\"✅ Saved: artifacts/r/tables/accuracy_table.csv\\n\")\n",
416
+ "\n",
417
+ "# RMSE bar chart\n",
418
+ "p_rmse <- ggplot(accuracy_tbl, aes(x = reorder(model, RMSE), y = RMSE)) +\n",
419
+ " geom_col() +\n",
420
+ " coord_flip() +\n",
421
+ " labs(title = \"Forecast model comparison (RMSE on holdout)\", x = \"\", y = \"RMSE\") +\n",
422
+ " theme_minimal()\n",
423
+ "\n",
424
+ "ggsave(file.path(R_FIG_DIR, \"rmse_comparison.png\"), p_rmse, width = 8, height = 4, dpi = 160)\n",
425
+ "cat(\"✅ Saved: artifacts/r/figures/rmse_comparison.png\\n\")\n",
426
+ "\n",
427
+ "# Side-by-side forecast plots (simple, no extra deps)\n",
428
+ "png(file.path(R_FIG_DIR, \"forecast_compare.png\"), width = 1200, height = 500)\n",
429
+ "par(mfrow = c(1, 3))\n",
430
+ "plot(fc_arima, main = \"ARIMA + Fourier\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
431
+ "plot(fc_ets, main = \"ETS\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
432
+ "plot(fc_naive, main = \"Naive\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
433
+ "dev.off()\n",
434
+ "cat(\"✅ Saved: artifacts/r/figures/forecast_compare.png\\n\")"
435
+ ]
436
+ },
437
+ {
438
+ "cell_type": "markdown",
439
+ "id": "30bc017b",
440
+ "metadata": {
441
+ "id": "30bc017b"
442
+ },
443
+ "source": [
444
+ "## **5.** 💾 Some R metadata for Hugging Face"
445
+ ]
446
+ },
447
+ {
448
+ "cell_type": "code",
449
+ "execution_count": 7,
450
+ "id": "645cb12b",
451
+ "metadata": {
452
+ "colab": {
453
+ "base_uri": "https://localhost:8080/"
454
+ },
455
+ "id": "645cb12b",
456
+ "outputId": "d454e0a5-b986-45ca-9069-65a1c21ce540"
457
+ },
458
+ "outputs": [
459
+ {
460
+ "output_type": "stream",
461
+ "name": "stdout",
462
+ "text": [
463
+ "✅ Saved: artifacts/r/tables/r_meta.json\n",
464
+ "DONE. R artifacts written to: artifacts/r \n"
465
+ ]
466
+ }
467
+ ],
468
+ "source": [
469
+ "# =========================================================\n",
470
+ "# Metadata export (aligned with current notebook objects)\n",
471
+ "# =========================================================\n",
472
+ "\n",
473
+ "meta <- list(\n",
474
+ "\n",
475
+ " # ---------------------------\n",
476
+ " # Dataset footprint\n",
477
+ " # ---------------------------\n",
478
+ " n_titles = nrow(df_title),\n",
479
+ " n_months = nrow(df_month2),\n",
480
+ "\n",
481
+ " # ---------------------------\n",
482
+ " # Forecasting info\n",
483
+ " # (only if these objects exist in your forecasting section)\n",
484
+ " # ---------------------------\n",
485
+ " forecasting = list(\n",
486
+ " holdout_h = h_test,\n",
487
+ " arima_order = forecast::arimaorder(fit_arima),\n",
488
+ " ets_method = fit_ets$method\n",
489
+ " )\n",
490
+ ")\n",
491
+ "\n",
492
+ "jsonlite::write_json(\n",
493
+ " meta,\n",
494
+ " path = file.path(R_TAB_DIR, \"r_meta.json\"),\n",
495
+ " pretty = TRUE,\n",
496
+ " auto_unbox = TRUE\n",
497
+ ")\n",
498
+ "\n",
499
+ "cat(\"✅ Saved: artifacts/r/tables/r_meta.json\\n\")\n",
500
+ "cat(\"DONE. R artifacts written to:\", file.path(ART_DIR, \"r\"), \"\\n\")\n"
501
+ ]
502
+ }
503
+ ],
504
+ "metadata": {
505
+ "colab": {
506
+ "provenance": []
507
+ },
508
+ "kernelspec": {
509
+ "name": "ir",
510
+ "display_name": "R"
511
+ },
512
+ "language_info": {
513
+ "name": "R"
514
+ }
515
+ },
516
+ "nbformat": 4,
517
+ "nbformat_minor": 5
518
+ }