1_Data_Creation_Sacchetti.ipynb ADDED
@@ -0,0 +1,1396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": null,
24
+ "metadata": {
25
+ "colab": {
26
+ "base_uri": "https://localhost:8080/"
27
+ },
28
+ "id": "f48c8f8c",
29
+ "outputId": "1808862a-4973-44c2-fdc6-9ea78aa3bf64"
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": null,
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": null,
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\n",
144
+ "\n",
145
+ "\"title\", \"price\", and \"rating\" objects*"
146
+ ]
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "execution_count": null,
151
+ "metadata": {
152
+ "id": "l5FkkNhUYTHh",
153
+ "colab": {
154
+ "base_uri": "https://localhost:8080/"
155
+ },
156
+ "outputId": "3412e0e9-4799-4c13-982e-507183252d02"
157
+ },
158
+ "outputs": [
159
+ {
160
+ "output_type": "stream",
161
+ "name": "stdout",
162
+ "text": [
163
+ " title price rating\n",
164
+ "0 A Light in the Attic 51.77 Three\n",
165
+ "1 Tipping the Velvet 53.74 One\n",
166
+ "2 Soumission 50.10 One\n",
167
+ "3 Sharp Objects 47.82 Four\n",
168
+ "4 Sapiens: A Brief History of Humankind 54.23 Five\n",
169
+ "(1000, 3)\n"
170
+ ]
171
+ }
172
+ ],
173
+ "source": [
174
+ "# 📚 Create dataframe with scraped data\n",
175
+ "df_books = pd.DataFrame({\n",
176
+ " \"title\": titles,\n",
177
+ " \"price\": prices,\n",
178
+ " \"rating\": ratings\n",
179
+ "})\n",
180
+ "\n",
181
+ "# Quick check\n",
182
+ "print(df_books.head())\n",
183
+ "print(df_books.shape)"
184
+ ]
185
+ },
186
+ {
187
+ "cell_type": "markdown",
188
+ "metadata": {
189
+ "id": "duI5dv3CZYvF"
190
+ },
191
+ "source": [
192
+ "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "execution_count": null,
198
+ "metadata": {
199
+ "id": "lC1U_YHtZifh"
200
+ },
201
+ "outputs": [],
202
+ "source": [
203
+ "# 💾 Save to CSV\n",
204
+ "df_books.to_csv(\"books_data.csv\", index=False)\n",
205
+ "\n",
206
+ "# 💾 Or save to Excel\n",
207
+ "# df_books.to_excel(\"books_data.xlsx\", index=False)"
208
+ ]
209
+ },
210
+ {
211
+ "cell_type": "markdown",
212
+ "metadata": {
213
+ "id": "qMjRKMBQZlJi"
214
+ },
215
+ "source": [
216
+ "### *e. ✋🏻🛑⛔️ View first fiew lines*"
217
+ ]
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "execution_count": null,
222
+ "metadata": {
223
+ "colab": {
224
+ "base_uri": "https://localhost:8080/",
225
+ "height": 206
226
+ },
227
+ "id": "O_wIvTxYZqCK",
228
+ "outputId": "fac945e5-0b0f-4df7-ec3a-227e8a7b4a41"
229
+ },
230
+ "outputs": [
231
+ {
232
+ "output_type": "execute_result",
233
+ "data": {
234
+ "text/plain": [
235
+ " title price rating\n",
236
+ "0 A Light in the Attic 51.77 Three\n",
237
+ "1 Tipping the Velvet 53.74 One\n",
238
+ "2 Soumission 50.10 One\n",
239
+ "3 Sharp Objects 47.82 Four\n",
240
+ "4 Sapiens: A Brief History of Humankind 54.23 Five"
241
+ ],
242
+ "text/html": [
243
+ "\n",
244
+ " <div id=\"df-d05796d7-498e-441d-9db8-542f16b98349\" class=\"colab-df-container\">\n",
245
+ " <div>\n",
246
+ "<style scoped>\n",
247
+ " .dataframe tbody tr th:only-of-type {\n",
248
+ " vertical-align: middle;\n",
249
+ " }\n",
250
+ "\n",
251
+ " .dataframe tbody tr th {\n",
252
+ " vertical-align: top;\n",
253
+ " }\n",
254
+ "\n",
255
+ " .dataframe thead th {\n",
256
+ " text-align: right;\n",
257
+ " }\n",
258
+ "</style>\n",
259
+ "<table border=\"1\" class=\"dataframe\">\n",
260
+ " <thead>\n",
261
+ " <tr style=\"text-align: right;\">\n",
262
+ " <th></th>\n",
263
+ " <th>title</th>\n",
264
+ " <th>price</th>\n",
265
+ " <th>rating</th>\n",
266
+ " </tr>\n",
267
+ " </thead>\n",
268
+ " <tbody>\n",
269
+ " <tr>\n",
270
+ " <th>0</th>\n",
271
+ " <td>A Light in the Attic</td>\n",
272
+ " <td>51.77</td>\n",
273
+ " <td>Three</td>\n",
274
+ " </tr>\n",
275
+ " <tr>\n",
276
+ " <th>1</th>\n",
277
+ " <td>Tipping the Velvet</td>\n",
278
+ " <td>53.74</td>\n",
279
+ " <td>One</td>\n",
280
+ " </tr>\n",
281
+ " <tr>\n",
282
+ " <th>2</th>\n",
283
+ " <td>Soumission</td>\n",
284
+ " <td>50.10</td>\n",
285
+ " <td>One</td>\n",
286
+ " </tr>\n",
287
+ " <tr>\n",
288
+ " <th>3</th>\n",
289
+ " <td>Sharp Objects</td>\n",
290
+ " <td>47.82</td>\n",
291
+ " <td>Four</td>\n",
292
+ " </tr>\n",
293
+ " <tr>\n",
294
+ " <th>4</th>\n",
295
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
296
+ " <td>54.23</td>\n",
297
+ " <td>Five</td>\n",
298
+ " </tr>\n",
299
+ " </tbody>\n",
300
+ "</table>\n",
301
+ "</div>\n",
302
+ " <div class=\"colab-df-buttons\">\n",
303
+ "\n",
304
+ " <div class=\"colab-df-container\">\n",
305
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-d05796d7-498e-441d-9db8-542f16b98349')\"\n",
306
+ " title=\"Convert this dataframe to an interactive table.\"\n",
307
+ " style=\"display:none;\">\n",
308
+ "\n",
309
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
310
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
311
+ " </svg>\n",
312
+ " </button>\n",
313
+ "\n",
314
+ " <style>\n",
315
+ " .colab-df-container {\n",
316
+ " display:flex;\n",
317
+ " gap: 12px;\n",
318
+ " }\n",
319
+ "\n",
320
+ " .colab-df-convert {\n",
321
+ " background-color: #E8F0FE;\n",
322
+ " border: none;\n",
323
+ " border-radius: 50%;\n",
324
+ " cursor: pointer;\n",
325
+ " display: none;\n",
326
+ " fill: #1967D2;\n",
327
+ " height: 32px;\n",
328
+ " padding: 0 0 0 0;\n",
329
+ " width: 32px;\n",
330
+ " }\n",
331
+ "\n",
332
+ " .colab-df-convert:hover {\n",
333
+ " background-color: #E2EBFA;\n",
334
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
335
+ " fill: #174EA6;\n",
336
+ " }\n",
337
+ "\n",
338
+ " .colab-df-buttons div {\n",
339
+ " margin-bottom: 4px;\n",
340
+ " }\n",
341
+ "\n",
342
+ " [theme=dark] .colab-df-convert {\n",
343
+ " background-color: #3B4455;\n",
344
+ " fill: #D2E3FC;\n",
345
+ " }\n",
346
+ "\n",
347
+ " [theme=dark] .colab-df-convert:hover {\n",
348
+ " background-color: #434B5C;\n",
349
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
350
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
351
+ " fill: #FFFFFF;\n",
352
+ " }\n",
353
+ " </style>\n",
354
+ "\n",
355
+ " <script>\n",
356
+ " const buttonEl =\n",
357
+ " document.querySelector('#df-d05796d7-498e-441d-9db8-542f16b98349 button.colab-df-convert');\n",
358
+ " buttonEl.style.display =\n",
359
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
360
+ "\n",
361
+ " async function convertToInteractive(key) {\n",
362
+ " const element = document.querySelector('#df-d05796d7-498e-441d-9db8-542f16b98349');\n",
363
+ " const dataTable =\n",
364
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
365
+ " [key], {});\n",
366
+ " if (!dataTable) return;\n",
367
+ "\n",
368
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
369
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
370
+ " + ' to learn more about interactive tables.';\n",
371
+ " element.innerHTML = '';\n",
372
+ " dataTable['output_type'] = 'display_data';\n",
373
+ " await google.colab.output.renderOutput(dataTable, element);\n",
374
+ " const docLink = document.createElement('div');\n",
375
+ " docLink.innerHTML = docLinkHtml;\n",
376
+ " element.appendChild(docLink);\n",
377
+ " }\n",
378
+ " </script>\n",
379
+ " </div>\n",
380
+ "\n",
381
+ "\n",
382
+ " </div>\n",
383
+ " </div>\n"
384
+ ],
385
+ "application/vnd.google.colaboratory.intrinsic+json": {
386
+ "type": "dataframe",
387
+ "variable_name": "df_books",
388
+ "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}"
389
+ }
390
+ },
391
+ "metadata": {},
392
+ "execution_count": 32
393
+ }
394
+ ],
395
+ "source": [
396
+ "# View first few rows\n",
397
+ "df_books.head()"
398
+ ]
399
+ },
400
+ {
401
+ "cell_type": "markdown",
402
+ "metadata": {
403
+ "id": "p-1Pr2szaqLk"
404
+ },
405
+ "source": [
406
+ "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
407
+ ]
408
+ },
409
+ {
410
+ "cell_type": "markdown",
411
+ "metadata": {
412
+ "id": "SIaJUGIpaH4V"
413
+ },
414
+ "source": [
415
+ "### *a. Initial setup*"
416
+ ]
417
+ },
418
+ {
419
+ "cell_type": "code",
420
+ "execution_count": null,
421
+ "metadata": {
422
+ "id": "-gPXGcRPuV_9"
423
+ },
424
+ "outputs": [],
425
+ "source": [
426
+ "import numpy as np\n",
427
+ "import random\n",
428
+ "from datetime import datetime\n",
429
+ "import warnings\n",
430
+ "\n",
431
+ "warnings.filterwarnings(\"ignore\")\n",
432
+ "random.seed(2025)\n",
433
+ "np.random.seed(2025)"
434
+ ]
435
+ },
436
+ {
437
+ "cell_type": "markdown",
438
+ "metadata": {
439
+ "id": "pY4yCoIuaQqp"
440
+ },
441
+ "source": [
442
+ "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
443
+ ]
444
+ },
445
+ {
446
+ "cell_type": "code",
447
+ "execution_count": null,
448
+ "metadata": {
449
+ "id": "mnd5hdAbaNjz"
450
+ },
451
+ "outputs": [],
452
+ "source": [
453
+ "def generate_popularity_score(rating):\n",
454
+ " base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
455
+ " trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
456
+ " return int(np.clip(base + trend_factor, 1, 5))"
457
+ ]
458
+ },
459
+ {
460
+ "cell_type": "markdown",
461
+ "metadata": {
462
+ "id": "n4-TaNTFgPak"
463
+ },
464
+ "source": [
465
+ "### *c. ✋🏻🛑⛔️ Run the function to create a \"popularity_score\" column from \"rating\"*"
466
+ ]
467
+ },
468
+ {
469
+ "cell_type": "code",
470
+ "execution_count": null,
471
+ "metadata": {
472
+ "id": "V-G3OCUCgR07",
473
+ "colab": {
474
+ "base_uri": "https://localhost:8080/",
475
+ "height": 206
476
+ },
477
+ "outputId": "a2bd661e-bc8a-4438-8707-4e96ebf4d7d3"
478
+ },
479
+ "outputs": [
480
+ {
481
+ "output_type": "execute_result",
482
+ "data": {
483
+ "text/plain": [
484
+ " title price rating popularity_score\n",
485
+ "0 A Light in the Attic 51.77 Three 3\n",
486
+ "1 Tipping the Velvet 53.74 One 2\n",
487
+ "2 Soumission 50.10 One 2\n",
488
+ "3 Sharp Objects 47.82 Four 4\n",
489
+ "4 Sapiens: A Brief History of Humankind 54.23 Five 3"
490
+ ],
491
+ "text/html": [
492
+ "\n",
493
+ " <div id=\"df-6cc9aabb-7677-4090-85d5-67de6681bdf1\" class=\"colab-df-container\">\n",
494
+ " <div>\n",
495
+ "<style scoped>\n",
496
+ " .dataframe tbody tr th:only-of-type {\n",
497
+ " vertical-align: middle;\n",
498
+ " }\n",
499
+ "\n",
500
+ " .dataframe tbody tr th {\n",
501
+ " vertical-align: top;\n",
502
+ " }\n",
503
+ "\n",
504
+ " .dataframe thead th {\n",
505
+ " text-align: right;\n",
506
+ " }\n",
507
+ "</style>\n",
508
+ "<table border=\"1\" class=\"dataframe\">\n",
509
+ " <thead>\n",
510
+ " <tr style=\"text-align: right;\">\n",
511
+ " <th></th>\n",
512
+ " <th>title</th>\n",
513
+ " <th>price</th>\n",
514
+ " <th>rating</th>\n",
515
+ " <th>popularity_score</th>\n",
516
+ " </tr>\n",
517
+ " </thead>\n",
518
+ " <tbody>\n",
519
+ " <tr>\n",
520
+ " <th>0</th>\n",
521
+ " <td>A Light in the Attic</td>\n",
522
+ " <td>51.77</td>\n",
523
+ " <td>Three</td>\n",
524
+ " <td>3</td>\n",
525
+ " </tr>\n",
526
+ " <tr>\n",
527
+ " <th>1</th>\n",
528
+ " <td>Tipping the Velvet</td>\n",
529
+ " <td>53.74</td>\n",
530
+ " <td>One</td>\n",
531
+ " <td>2</td>\n",
532
+ " </tr>\n",
533
+ " <tr>\n",
534
+ " <th>2</th>\n",
535
+ " <td>Soumission</td>\n",
536
+ " <td>50.10</td>\n",
537
+ " <td>One</td>\n",
538
+ " <td>2</td>\n",
539
+ " </tr>\n",
540
+ " <tr>\n",
541
+ " <th>3</th>\n",
542
+ " <td>Sharp Objects</td>\n",
543
+ " <td>47.82</td>\n",
544
+ " <td>Four</td>\n",
545
+ " <td>4</td>\n",
546
+ " </tr>\n",
547
+ " <tr>\n",
548
+ " <th>4</th>\n",
549
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
550
+ " <td>54.23</td>\n",
551
+ " <td>Five</td>\n",
552
+ " <td>3</td>\n",
553
+ " </tr>\n",
554
+ " </tbody>\n",
555
+ "</table>\n",
556
+ "</div>\n",
557
+ " <div class=\"colab-df-buttons\">\n",
558
+ "\n",
559
+ " <div class=\"colab-df-container\">\n",
560
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-6cc9aabb-7677-4090-85d5-67de6681bdf1')\"\n",
561
+ " title=\"Convert this dataframe to an interactive table.\"\n",
562
+ " style=\"display:none;\">\n",
563
+ "\n",
564
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
565
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
566
+ " </svg>\n",
567
+ " </button>\n",
568
+ "\n",
569
+ " <style>\n",
570
+ " .colab-df-container {\n",
571
+ " display:flex;\n",
572
+ " gap: 12px;\n",
573
+ " }\n",
574
+ "\n",
575
+ " .colab-df-convert {\n",
576
+ " background-color: #E8F0FE;\n",
577
+ " border: none;\n",
578
+ " border-radius: 50%;\n",
579
+ " cursor: pointer;\n",
580
+ " display: none;\n",
581
+ " fill: #1967D2;\n",
582
+ " height: 32px;\n",
583
+ " padding: 0 0 0 0;\n",
584
+ " width: 32px;\n",
585
+ " }\n",
586
+ "\n",
587
+ " .colab-df-convert:hover {\n",
588
+ " background-color: #E2EBFA;\n",
589
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
590
+ " fill: #174EA6;\n",
591
+ " }\n",
592
+ "\n",
593
+ " .colab-df-buttons div {\n",
594
+ " margin-bottom: 4px;\n",
595
+ " }\n",
596
+ "\n",
597
+ " [theme=dark] .colab-df-convert {\n",
598
+ " background-color: #3B4455;\n",
599
+ " fill: #D2E3FC;\n",
600
+ " }\n",
601
+ "\n",
602
+ " [theme=dark] .colab-df-convert:hover {\n",
603
+ " background-color: #434B5C;\n",
604
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
605
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
606
+ " fill: #FFFFFF;\n",
607
+ " }\n",
608
+ " </style>\n",
609
+ "\n",
610
+ " <script>\n",
611
+ " const buttonEl =\n",
612
+ " document.querySelector('#df-6cc9aabb-7677-4090-85d5-67de6681bdf1 button.colab-df-convert');\n",
613
+ " buttonEl.style.display =\n",
614
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
615
+ "\n",
616
+ " async function convertToInteractive(key) {\n",
617
+ " const element = document.querySelector('#df-6cc9aabb-7677-4090-85d5-67de6681bdf1');\n",
618
+ " const dataTable =\n",
619
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
620
+ " [key], {});\n",
621
+ " if (!dataTable) return;\n",
622
+ "\n",
623
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
624
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
625
+ " + ' to learn more about interactive tables.';\n",
626
+ " element.innerHTML = '';\n",
627
+ " dataTable['output_type'] = 'display_data';\n",
628
+ " await google.colab.output.renderOutput(dataTable, element);\n",
629
+ " const docLink = document.createElement('div');\n",
630
+ " docLink.innerHTML = docLinkHtml;\n",
631
+ " element.appendChild(docLink);\n",
632
+ " }\n",
633
+ " </script>\n",
634
+ " </div>\n",
635
+ "\n",
636
+ "\n",
637
+ " </div>\n",
638
+ " </div>\n"
639
+ ],
640
+ "application/vnd.google.colaboratory.intrinsic+json": {
641
+ "type": "dataframe",
642
+ "variable_name": "df_books",
643
+ "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}"
644
+ }
645
+ },
646
+ "metadata": {},
647
+ "execution_count": 35
648
+ }
649
+ ],
650
+ "source": [
651
+ "# 🧩 Create popularity_score column from rating\n",
652
+ "df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)\n",
653
+ "\n",
654
+ "# Check result\n",
655
+ "df_books.head()"
656
+ ]
657
+ },
658
+ {
659
+ "cell_type": "markdown",
660
+ "metadata": {
661
+ "id": "HnngRNTgacYt"
662
+ },
663
+ "source": [
664
+ "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
665
+ ]
666
+ },
667
+ {
668
+ "cell_type": "code",
669
+ "execution_count": null,
670
+ "metadata": {
671
+ "id": "kUtWmr8maZLZ"
672
+ },
673
+ "outputs": [],
674
+ "source": [
675
+ "def get_sentiment(popularity_score):\n",
676
+ " if popularity_score <= 2:\n",
677
+ " return \"negative\"\n",
678
+ " elif popularity_score == 3:\n",
679
+ " return \"neutral\"\n",
680
+ " else:\n",
681
+ " return \"positive\""
682
+ ]
683
+ },
684
+ {
685
+ "cell_type": "markdown",
686
+ "metadata": {
687
+ "id": "HF9F9HIzgT7Z"
688
+ },
689
+ "source": [
690
+ "### *e. ✋🏻🛑⛔️ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
691
+ ]
692
+ },
693
+ {
694
+ "cell_type": "code",
695
+ "execution_count": null,
696
+ "metadata": {
697
+ "id": "tafQj8_7gYCG",
698
+ "colab": {
699
+ "base_uri": "https://localhost:8080/",
700
+ "height": 206
701
+ },
702
+ "outputId": "5f6b236d-b59a-41b1-b0aa-d8df4f90c6da"
703
+ },
704
+ "outputs": [
705
+ {
706
+ "output_type": "execute_result",
707
+ "data": {
708
+ "text/plain": [
709
+ " title price rating popularity_score \\\n",
710
+ "0 A Light in the Attic 51.77 Three 3 \n",
711
+ "1 Tipping the Velvet 53.74 One 2 \n",
712
+ "2 Soumission 50.10 One 2 \n",
713
+ "3 Sharp Objects 47.82 Four 4 \n",
714
+ "4 Sapiens: A Brief History of Humankind 54.23 Five 3 \n",
715
+ "\n",
716
+ " sentiment_label \n",
717
+ "0 neutral \n",
718
+ "1 negative \n",
719
+ "2 negative \n",
720
+ "3 positive \n",
721
+ "4 neutral "
722
+ ],
723
+ "text/html": [
724
+ "\n",
725
+ " <div id=\"df-03e93382-6eb0-465f-adfd-0f75c20d87de\" class=\"colab-df-container\">\n",
726
+ " <div>\n",
727
+ "<style scoped>\n",
728
+ " .dataframe tbody tr th:only-of-type {\n",
729
+ " vertical-align: middle;\n",
730
+ " }\n",
731
+ "\n",
732
+ " .dataframe tbody tr th {\n",
733
+ " vertical-align: top;\n",
734
+ " }\n",
735
+ "\n",
736
+ " .dataframe thead th {\n",
737
+ " text-align: right;\n",
738
+ " }\n",
739
+ "</style>\n",
740
+ "<table border=\"1\" class=\"dataframe\">\n",
741
+ " <thead>\n",
742
+ " <tr style=\"text-align: right;\">\n",
743
+ " <th></th>\n",
744
+ " <th>title</th>\n",
745
+ " <th>price</th>\n",
746
+ " <th>rating</th>\n",
747
+ " <th>popularity_score</th>\n",
748
+ " <th>sentiment_label</th>\n",
749
+ " </tr>\n",
750
+ " </thead>\n",
751
+ " <tbody>\n",
752
+ " <tr>\n",
753
+ " <th>0</th>\n",
754
+ " <td>A Light in the Attic</td>\n",
755
+ " <td>51.77</td>\n",
756
+ " <td>Three</td>\n",
757
+ " <td>3</td>\n",
758
+ " <td>neutral</td>\n",
759
+ " </tr>\n",
760
+ " <tr>\n",
761
+ " <th>1</th>\n",
762
+ " <td>Tipping the Velvet</td>\n",
763
+ " <td>53.74</td>\n",
764
+ " <td>One</td>\n",
765
+ " <td>2</td>\n",
766
+ " <td>negative</td>\n",
767
+ " </tr>\n",
768
+ " <tr>\n",
769
+ " <th>2</th>\n",
770
+ " <td>Soumission</td>\n",
771
+ " <td>50.10</td>\n",
772
+ " <td>One</td>\n",
773
+ " <td>2</td>\n",
774
+ " <td>negative</td>\n",
775
+ " </tr>\n",
776
+ " <tr>\n",
777
+ " <th>3</th>\n",
778
+ " <td>Sharp Objects</td>\n",
779
+ " <td>47.82</td>\n",
780
+ " <td>Four</td>\n",
781
+ " <td>4</td>\n",
782
+ " <td>positive</td>\n",
783
+ " </tr>\n",
784
+ " <tr>\n",
785
+ " <th>4</th>\n",
786
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
787
+ " <td>54.23</td>\n",
788
+ " <td>Five</td>\n",
789
+ " <td>3</td>\n",
790
+ " <td>neutral</td>\n",
791
+ " </tr>\n",
792
+ " </tbody>\n",
793
+ "</table>\n",
794
+ "</div>\n",
795
+ " <div class=\"colab-df-buttons\">\n",
796
+ "\n",
797
+ " <div class=\"colab-df-container\">\n",
798
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-03e93382-6eb0-465f-adfd-0f75c20d87de')\"\n",
799
+ " title=\"Convert this dataframe to an interactive table.\"\n",
800
+ " style=\"display:none;\">\n",
801
+ "\n",
802
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
803
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
804
+ " </svg>\n",
805
+ " </button>\n",
806
+ "\n",
807
+ " <style>\n",
808
+ " .colab-df-container {\n",
809
+ " display:flex;\n",
810
+ " gap: 12px;\n",
811
+ " }\n",
812
+ "\n",
813
+ " .colab-df-convert {\n",
814
+ " background-color: #E8F0FE;\n",
815
+ " border: none;\n",
816
+ " border-radius: 50%;\n",
817
+ " cursor: pointer;\n",
818
+ " display: none;\n",
819
+ " fill: #1967D2;\n",
820
+ " height: 32px;\n",
821
+ " padding: 0 0 0 0;\n",
822
+ " width: 32px;\n",
823
+ " }\n",
824
+ "\n",
825
+ " .colab-df-convert:hover {\n",
826
+ " background-color: #E2EBFA;\n",
827
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
828
+ " fill: #174EA6;\n",
829
+ " }\n",
830
+ "\n",
831
+ " .colab-df-buttons div {\n",
832
+ " margin-bottom: 4px;\n",
833
+ " }\n",
834
+ "\n",
835
+ " [theme=dark] .colab-df-convert {\n",
836
+ " background-color: #3B4455;\n",
837
+ " fill: #D2E3FC;\n",
838
+ " }\n",
839
+ "\n",
840
+ " [theme=dark] .colab-df-convert:hover {\n",
841
+ " background-color: #434B5C;\n",
842
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
843
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
844
+ " fill: #FFFFFF;\n",
845
+ " }\n",
846
+ " </style>\n",
847
+ "\n",
848
+ " <script>\n",
849
+ " const buttonEl =\n",
850
+ " document.querySelector('#df-03e93382-6eb0-465f-adfd-0f75c20d87de button.colab-df-convert');\n",
851
+ " buttonEl.style.display =\n",
852
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
853
+ "\n",
854
+ " async function convertToInteractive(key) {\n",
855
+ " const element = document.querySelector('#df-03e93382-6eb0-465f-adfd-0f75c20d87de');\n",
856
+ " const dataTable =\n",
857
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
858
+ " [key], {});\n",
859
+ " if (!dataTable) return;\n",
860
+ "\n",
861
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
862
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
863
+ " + ' to learn more about interactive tables.';\n",
864
+ " element.innerHTML = '';\n",
865
+ " dataTable['output_type'] = 'display_data';\n",
866
+ " await google.colab.output.renderOutput(dataTable, element);\n",
867
+ " const docLink = document.createElement('div');\n",
868
+ " docLink.innerHTML = docLinkHtml;\n",
869
+ " element.appendChild(docLink);\n",
870
+ " }\n",
871
+ " </script>\n",
872
+ " </div>\n",
873
+ "\n",
874
+ "\n",
875
+ " </div>\n",
876
+ " </div>\n"
877
+ ],
878
+ "application/vnd.google.colaboratory.intrinsic+json": {
879
+ "type": "dataframe",
880
+ "variable_name": "df_books",
881
+ "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}"
882
+ }
883
+ },
884
+ "metadata": {},
885
+ "execution_count": 37
886
+ }
887
+ ],
888
+ "source": [
889
+ "# 🧠 Create sentiment_label column from popularity_score\n",
890
+ "df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)\n",
891
+ "\n",
892
+ "# Verify\n",
893
+ "df_books.head()"
894
+ ]
895
+ },
896
+ {
897
+ "cell_type": "markdown",
898
+ "metadata": {
899
+ "id": "T8AdKkmASq9a"
900
+ },
901
+ "source": [
902
+ "## **4.** 📈 Generate synthetic book sales data of 18 months"
903
+ ]
904
+ },
905
+ {
906
+ "cell_type": "markdown",
907
+ "metadata": {
908
+ "id": "OhXbdGD5fH0c"
909
+ },
910
+ "source": [
911
+ "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
912
+ ]
913
+ },
914
+ {
915
+ "cell_type": "code",
916
+ "execution_count": null,
917
+ "metadata": {
918
+ "id": "qkVhYPXGbgEn"
919
+ },
920
+ "outputs": [],
921
+ "source": [
922
+ "def generate_sales_profile(sentiment):\n",
923
+ " months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
924
+ "\n",
925
+ " if sentiment == \"positive\":\n",
926
+ " base = random.randint(200, 300)\n",
927
+ " trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
928
+ " elif sentiment == \"negative\":\n",
929
+ " base = random.randint(20, 80)\n",
930
+ " trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
931
+ " else: # neutral\n",
932
+ " base = random.randint(80, 160)\n",
933
+ " trend = np.full(len(months), base + random.randint(-10, 10))\n",
934
+ "\n",
935
+ " seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
936
+ " noise = np.random.normal(0, 5, len(months))\n",
937
+ " monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
938
+ "\n",
939
+ " return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
940
+ ]
941
+ },
942
+ {
943
+ "cell_type": "markdown",
944
+ "metadata": {
945
+ "id": "L2ak1HlcgoTe"
946
+ },
947
+ "source": [
948
+ "### *b. Run the function as part of building sales_data*"
949
+ ]
950
+ },
951
+ {
952
+ "cell_type": "code",
953
+ "execution_count": null,
954
+ "metadata": {
955
+ "id": "SlJ24AUafoDB"
956
+ },
957
+ "outputs": [],
958
+ "source": [
959
+ "sales_data = []\n",
960
+ "for _, row in df_books.iterrows():\n",
961
+ " records = generate_sales_profile(row[\"sentiment_label\"])\n",
962
+ " for month, units in records:\n",
963
+ " sales_data.append({\n",
964
+ " \"title\": row[\"title\"],\n",
965
+ " \"month\": month,\n",
966
+ " \"units_sold\": units,\n",
967
+ " \"sentiment_label\": row[\"sentiment_label\"]\n",
968
+ " })"
969
+ ]
970
+ },
971
+ {
972
+ "cell_type": "markdown",
973
+ "metadata": {
974
+ "id": "4IXZKcCSgxnq"
975
+ },
976
+ "source": [
977
+ "### *c. ✋🏻🛑⛔️ Create a df_sales DataFrame from sales_data*"
978
+ ]
979
+ },
980
+ {
981
+ "cell_type": "code",
982
+ "execution_count": null,
983
+ "metadata": {
984
+ "id": "wcN6gtiZg-ws",
985
+ "colab": {
986
+ "base_uri": "https://localhost:8080/"
987
+ },
988
+ "outputId": "360a1b46-5ea0-4f19-ad53-14fa255f8478"
989
+ },
990
+ "outputs": [
991
+ {
992
+ "output_type": "execute_result",
993
+ "data": {
994
+ "text/plain": [
995
+ "(18000, 4)"
996
+ ]
997
+ },
998
+ "metadata": {},
999
+ "execution_count": 40
1000
+ }
1001
+ ],
1002
+ "source": [
1003
+ "# 📊 Create sales DataFrame\n",
1004
+ "df_sales = pd.DataFrame(sales_data)\n",
1005
+ "\n",
1006
+ "# Quick check\n",
1007
+ "df_sales.head()\n",
1008
+ "df_sales.shape"
1009
+ ]
1010
+ },
1011
+ {
1012
+ "cell_type": "markdown",
1013
+ "metadata": {
1014
+ "id": "EhIjz9WohAmZ"
1015
+ },
1016
+ "source": [
1017
+ "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
1018
+ ]
1019
+ },
1020
+ {
1021
+ "cell_type": "code",
1022
+ "execution_count": null,
1023
+ "metadata": {
1024
+ "colab": {
1025
+ "base_uri": "https://localhost:8080/"
1026
+ },
1027
+ "id": "MzbZvLcAhGaH",
1028
+ "outputId": "c2dbb7eb-6dbc-400f-f038-7f42e2d06dec"
1029
+ },
1030
+ "outputs": [
1031
+ {
1032
+ "output_type": "stream",
1033
+ "name": "stdout",
1034
+ "text": [
1035
+ " title month units_sold sentiment_label\n",
1036
+ "0 A Light in the Attic 2024-08 100 neutral\n",
1037
+ "1 A Light in the Attic 2024-09 109 neutral\n",
1038
+ "2 A Light in the Attic 2024-10 102 neutral\n",
1039
+ "3 A Light in the Attic 2024-11 107 neutral\n",
1040
+ "4 A Light in the Attic 2024-12 108 neutral\n"
1041
+ ]
1042
+ }
1043
+ ],
1044
+ "source": [
1045
+ "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
1046
+ "\n",
1047
+ "print(df_sales.head())"
1048
+ ]
1049
+ },
1050
+ {
1051
+ "cell_type": "markdown",
1052
+ "metadata": {
1053
+ "id": "7g9gqBgQMtJn"
1054
+ },
1055
+ "source": [
1056
+ "## **5.** 🎯 Generate synthetic customer reviews"
1057
+ ]
1058
+ },
1059
+ {
1060
+ "cell_type": "markdown",
1061
+ "metadata": {
1062
+ "id": "Gi4y9M9KuDWx"
1063
+ },
1064
+ "source": [
1065
+ "### *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*"
1066
+ ]
1067
+ },
1068
+ {
1069
+ "cell_type": "code",
1070
+ "execution_count": null,
1071
+ "metadata": {
1072
+ "id": "b3cd2a50"
1073
+ },
1074
+ "outputs": [],
1075
+ "source": [
1076
+ "synthetic_reviews_by_sentiment = {\n",
1077
+ " \"positive\": [\n",
1078
+ " \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
1079
+ " \"Brilliantly written! The characters were unforgettable and the plot was engaging.\",\n",
1080
+ " \"One of the best books I've read this year — inspiring and emotionally rich.\",\n",
1081
+ " ],\n",
1082
+ " \"neutral\": [\n",
1083
+ " \"An average book — not great, but not bad either.\",\n",
1084
+ " \"Some parts really stood out, others felt a bit flat.\",\n",
1085
+ " \"It was okay overall. A decent way to pass the time.\",\n",
1086
+ " ],\n",
1087
+ " \"negative\": [\n",
1088
+ " \"I struggled to get through this one — it just didn’t grab me.\",\n",
1089
+ " \"The plot was confusing and the characters felt underdeveloped.\",\n",
1090
+ " \"Disappointing. I had high hopes, but they weren't met.\",\n",
1091
+ " ]\n",
1092
+ "}"
1093
+ ]
1094
+ },
1095
+ {
1096
+ "cell_type": "code",
1097
+ "source": [
1098
+ "synthetic_reviews_by_sentiment = {\n",
1099
+ " \"positive\": [\n",
1100
+ " f\"This book was fantastic and completely engaging from start to finish. #{i}\"\n",
1101
+ " for i in range(1, 51)\n",
1102
+ " ],\n",
1103
+ "\n",
1104
+ " \"neutral\": [\n",
1105
+ " f\"This was an average read with some good and some weaker moments. #{i}\"\n",
1106
+ " for i in range(1, 51)\n",
1107
+ " ],\n",
1108
+ "\n",
1109
+ " \"negative\": [\n",
1110
+ " f\"I didn’t enjoy this book as much as I expected. It fell short for me. #{i}\"\n",
1111
+ " for i in range(1, 51)\n",
1112
+ " ]\n",
1113
+ "}"
1114
+ ],
1115
+ "metadata": {
1116
+ "id": "62KsYXYLs0Lz"
1117
+ },
1118
+ "execution_count": null,
1119
+ "outputs": []
1120
+ },
1121
+ {
1122
+ "cell_type": "markdown",
1123
+ "metadata": {
1124
+ "id": "fQhfVaDmuULT"
1125
+ },
1126
+ "source": [
1127
+ "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
1128
+ ]
1129
+ },
1130
+ {
1131
+ "cell_type": "code",
1132
+ "execution_count": null,
1133
+ "metadata": {
1134
+ "id": "l2SRc3PjuTGM"
1135
+ },
1136
+ "outputs": [],
1137
+ "source": [
1138
+ "review_rows = []\n",
1139
+ "for _, row in df_books.iterrows():\n",
1140
+ " title = row['title']\n",
1141
+ " sentiment_label = row['sentiment_label']\n",
1142
+ " review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
1143
+ " sampled_reviews = random.sample(review_pool, 10)\n",
1144
+ " for review_text in sampled_reviews:\n",
1145
+ " review_rows.append({\n",
1146
+ " \"title\": title,\n",
1147
+ " \"sentiment_label\": sentiment_label,\n",
1148
+ " \"review_text\": review_text,\n",
1149
+ " \"rating\": row['rating'],\n",
1150
+ " \"popularity_score\": row['popularity_score']\n",
1151
+ " })"
1152
+ ]
1153
+ },
1154
+ {
1155
+ "cell_type": "markdown",
1156
+ "metadata": {
1157
+ "id": "bmJMXF-Bukdm"
1158
+ },
1159
+ "source": [
1160
+ "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
1161
+ ]
1162
+ },
1163
+ {
1164
+ "cell_type": "code",
1165
+ "execution_count": null,
1166
+ "metadata": {
1167
+ "id": "ZUKUqZsuumsp"
1168
+ },
1169
+ "outputs": [],
1170
+ "source": [
1171
+ "df_reviews = pd.DataFrame(review_rows)\n",
1172
+ "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
1173
+ ]
1174
+ },
1175
+ {
1176
+ "cell_type": "markdown",
1177
+ "source": [
1178
+ "### *c. inputs for R*"
1179
+ ],
1180
+ "metadata": {
1181
+ "id": "_602pYUS3gY5"
1182
+ }
1183
+ },
1184
+ {
1185
+ "cell_type": "code",
1186
+ "execution_count": null,
1187
+ "metadata": {
1188
+ "colab": {
1189
+ "base_uri": "https://localhost:8080/"
1190
+ },
1191
+ "id": "3946e521",
1192
+ "outputId": "f32f807b-7b2a-4637-de12-81aa3b5104d8"
1193
+ },
1194
+ "outputs": [
1195
+ {
1196
+ "output_type": "stream",
1197
+ "name": "stdout",
1198
+ "text": [
1199
+ "✅ Wrote synthetic_title_level_features.csv\n",
1200
+ "✅ Wrote synthetic_monthly_revenue_series.csv\n"
1201
+ ]
1202
+ }
1203
+ ],
1204
+ "source": [
1205
+ "import numpy as np\n",
1206
+ "\n",
1207
+ "def _safe_num(s):\n",
1208
+ " return pd.to_numeric(\n",
1209
+ " pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
1210
+ " errors=\"coerce\"\n",
1211
+ " )\n",
1212
+ "\n",
1213
+ "# --- Clean book metadata (price/rating) ---\n",
1214
+ "df_books_r = df_books.copy()\n",
1215
+ "if \"price\" in df_books_r.columns:\n",
1216
+ " df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
1217
+ "if \"rating\" in df_books_r.columns:\n",
1218
+ " df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
1219
+ "\n",
1220
+ "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
1221
+ "\n",
1222
+ "# --- Clean sales ---\n",
1223
+ "df_sales_r = df_sales.copy()\n",
1224
+ "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
1225
+ "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
1226
+ "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
1227
+ "\n",
1228
+ "# --- Clean reviews ---\n",
1229
+ "df_reviews_r = df_reviews.copy()\n",
1230
+ "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
1231
+ "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
1232
+ "if \"rating\" in df_reviews_r.columns:\n",
1233
+ " df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
1234
+ "if \"popularity_score\" in df_reviews_r.columns:\n",
1235
+ " df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
1236
+ "\n",
1237
+ "# --- Sentiment shares per title (from reviews) ---\n",
1238
+ "sent_counts = (\n",
1239
+ " df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
1240
+ " .size()\n",
1241
+ " .unstack(fill_value=0)\n",
1242
+ ")\n",
1243
+ "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
1244
+ " if lab not in sent_counts.columns:\n",
1245
+ " sent_counts[lab] = 0\n",
1246
+ "\n",
1247
+ "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
1248
+ "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
1249
+ "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
1250
+ "sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
1251
+ "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
1252
+ "sent_counts = sent_counts.reset_index()\n",
1253
+ "\n",
1254
+ "# --- Sales aggregation per title ---\n",
1255
+ "sales_by_title = (\n",
1256
+ " df_sales_r.dropna(subset=[\"title\"])\n",
1257
+ " .groupby(\"title\", as_index=False)\n",
1258
+ " .agg(\n",
1259
+ " months_observed=(\"month\", \"nunique\"),\n",
1260
+ " avg_units_sold=(\"units_sold\", \"mean\"),\n",
1261
+ " total_units_sold=(\"units_sold\", \"sum\"),\n",
1262
+ " )\n",
1263
+ ")\n",
1264
+ "\n",
1265
+ "# --- Title-level features (join sales + books + sentiment) ---\n",
1266
+ "df_title = (\n",
1267
+ " sales_by_title\n",
1268
+ " .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
1269
+ " .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
1270
+ " on=\"title\", how=\"left\")\n",
1271
+ ")\n",
1272
+ "\n",
1273
+ "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
1274
+ "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
1275
+ "\n",
1276
+ "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
1277
+ "print(\"✅ Wrote synthetic_title_level_features.csv\")\n",
1278
+ "\n",
1279
+ "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
1280
+ "monthly_rev = (\n",
1281
+ " df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
1282
+ ")\n",
1283
+ "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
1284
+ "\n",
1285
+ "df_monthly = (\n",
1286
+ " monthly_rev.dropna(subset=[\"month\"])\n",
1287
+ " .groupby(\"month\", as_index=False)[\"revenue\"]\n",
1288
+ " .sum()\n",
1289
+ " .rename(columns={\"revenue\": \"total_revenue\"})\n",
1290
+ " .sort_values(\"month\")\n",
1291
+ ")\n",
1292
+ "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
1293
+ "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
1294
+ " df_monthly = (\n",
1295
+ " df_sales_r.dropna(subset=[\"month\"])\n",
1296
+ " .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
1297
+ " .sum()\n",
1298
+ " .rename(columns={\"units_sold\": \"total_revenue\"})\n",
1299
+ " .sort_values(\"month\")\n",
1300
+ " )\n",
1301
+ "\n",
1302
+ "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
1303
+ "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
1304
+ "print(\"✅ Wrote synthetic_monthly_revenue_series.csv\")\n"
1305
+ ]
1306
+ },
1307
+ {
1308
+ "cell_type": "markdown",
1309
+ "metadata": {
1310
+ "id": "RYvGyVfXuo54"
1311
+ },
1312
+ "source": [
1313
+ "### *d. ✋🏻🛑⛔️ View the first few lines*"
1314
+ ]
1315
+ },
1316
+ {
1317
+ "cell_type": "code",
1318
+ "execution_count": null,
1319
+ "metadata": {
1320
+ "colab": {
1321
+ "base_uri": "https://localhost:8080/"
1322
+ },
1323
+ "id": "xfE8NMqOurKo",
1324
+ "outputId": "8e39c853-9f33-4725-8418-899e78820d42"
1325
+ },
1326
+ "outputs": [
1327
+ {
1328
+ "output_type": "stream",
1329
+ "name": "stdout",
1330
+ "text": [
1331
+ " title sentiment_label \\\n",
1332
+ "0 A Light in the Attic neutral \n",
1333
+ "1 A Light in the Attic neutral \n",
1334
+ "2 A Light in the Attic neutral \n",
1335
+ "3 A Light in the Attic neutral \n",
1336
+ "4 A Light in the Attic neutral \n",
1337
+ "\n",
1338
+ " review_text rating popularity_score \n",
1339
+ "0 This was an average read with some good and so... Three 3 \n",
1340
+ "1 This was an average read with some good and so... Three 3 \n",
1341
+ "2 This was an average read with some good and so... Three 3 \n",
1342
+ "3 This was an average read with some good and so... Three 3 \n",
1343
+ "4 This was an average read with some good and so... Three 3 \n",
1344
+ "\n",
1345
+ "Shape: (10000, 5)\n",
1346
+ "\n",
1347
+ "Columns: ['title', 'sentiment_label', 'review_text', 'rating', 'popularity_score']\n"
1348
+ ]
1349
+ }
1350
+ ],
1351
+ "source": [
1352
+ "print(df_reviews.head())\n",
1353
+ "print(\"\\nShape:\", df_reviews.shape)\n",
1354
+ "print(\"\\nColumns:\", df_reviews.columns.tolist())"
1355
+ ]
1356
+ }
1357
+ ],
1358
+ "metadata": {
1359
+ "colab": {
1360
+ "collapsed_sections": [
1361
+ "jpASMyIQMaAq",
1362
+ "lquNYCbfL9IM",
1363
+ "0IWuNpxxYDJF",
1364
+ "oCdTsin2Yfp3",
1365
+ "T0TOeRC4Yrnn",
1366
+ "duI5dv3CZYvF",
1367
+ "qMjRKMBQZlJi",
1368
+ "p-1Pr2szaqLk",
1369
+ "SIaJUGIpaH4V",
1370
+ "pY4yCoIuaQqp",
1371
+ "n4-TaNTFgPak",
1372
+ "HnngRNTgacYt",
1373
+ "HF9F9HIzgT7Z",
1374
+ "T8AdKkmASq9a",
1375
+ "OhXbdGD5fH0c",
1376
+ "L2ak1HlcgoTe",
1377
+ "4IXZKcCSgxnq",
1378
+ "EhIjz9WohAmZ",
1379
+ "Gi4y9M9KuDWx",
1380
+ "fQhfVaDmuULT",
1381
+ "bmJMXF-Bukdm",
1382
+ "RYvGyVfXuo54"
1383
+ ],
1384
+ "provenance": []
1385
+ },
1386
+ "kernelspec": {
1387
+ "display_name": "Python 3",
1388
+ "name": "python3"
1389
+ },
1390
+ "language_info": {
1391
+ "name": "python"
1392
+ }
1393
+ },
1394
+ "nbformat": 4,
1395
+ "nbformat_minor": 0
1396
+ }
2a_Python_Analysis_Sacchetti.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
R analysis.ipynb ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": null,
26
+ "id": "d40cd131",
27
+ "metadata": {
28
+ "id": "d40cd131"
29
+ },
30
+ "outputs": [],
31
+ "source": [
32
+ "\n",
33
+ "# Uncomment the next line once:\n",
34
+ "install.packages(c(\"readr\",\"dplyr\",\"stringr\",\"tidyr\",\"lubridate\",\"ggplot2\",\"forecast\",\"broom\",\"jsonlite\"), repos=\"https://cloud.r-project.org\")\n",
35
+ "\n",
36
+ "suppressPackageStartupMessages({\n",
37
+ " library(readr)\n",
38
+ " library(dplyr)\n",
39
+ " library(stringr)\n",
40
+ " library(tidyr)\n",
41
+ " library(lubridate)\n",
42
+ " library(ggplot2)\n",
43
+ " library(forecast)\n",
44
+ " library(broom)\n",
45
+ " library(jsonlite)\n",
46
+ "})"
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "markdown",
51
+ "id": "f01d02e7",
52
+ "metadata": {
53
+ "id": "f01d02e7"
54
+ },
55
+ "source": [
56
+ "## **2.** ✅️ Load & inspect inputs"
57
+ ]
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "execution_count": null,
62
+ "id": "29e8f6ce",
63
+ "metadata": {
64
+ "colab": {
65
+ "base_uri": "https://localhost:8080/"
66
+ },
67
+ "id": "29e8f6ce",
68
+ "outputId": "5a1bda1c-c58d-43d0-c85e-db5041c8bc49"
69
+ },
70
+ "outputs": [
71
+ {
72
+ "output_type": "stream",
73
+ "name": "stdout",
74
+ "text": [
75
+ "Loaded: 1000 rows (title-level), 18 rows (monthly)\n"
76
+ ]
77
+ }
78
+ ],
79
+ "source": [
80
+ "\n",
81
+ "must_exist <- function(path, label) {\n",
82
+ " if (!file.exists(path)) stop(paste0(\"Missing \", label, \": \", path))\n",
83
+ "}\n",
84
+ "\n",
85
+ "TITLE_PATH <- \"synthetic_title_level_features.csv\"\n",
86
+ "MONTH_PATH <- \"synthetic_monthly_revenue_series.csv\"\n",
87
+ "\n",
88
+ "must_exist(TITLE_PATH, \"TITLE_PATH\")\n",
89
+ "must_exist(MONTH_PATH, \"MONTH_PATH\")\n",
90
+ "\n",
91
+ "df_title <- read_csv(TITLE_PATH, show_col_types = FALSE)\n",
92
+ "df_month <- read_csv(MONTH_PATH, show_col_types = FALSE)\n",
93
+ "\n",
94
+ "cat(\"Loaded:\", nrow(df_title), \"rows (title-level),\", nrow(df_month), \"rows (monthly)\n",
95
+ "\")"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": null,
101
+ "id": "9fd04262",
102
+ "metadata": {
103
+ "colab": {
104
+ "base_uri": "https://localhost:8080/"
105
+ },
106
+ "id": "9fd04262",
107
+ "outputId": "5f031538-96be-4758-904d-9201ec3c3ea7"
108
+ },
109
+ "outputs": [
110
+ {
111
+ "output_type": "stream",
112
+ "name": "stdout",
113
+ "text": [
114
+ "\u001b[90m# A tibble: 1 × 6\u001b[39m\n",
115
+ " n na_avg_revenue na_price na_rating na_share_pos na_share_neg\n",
116
+ " \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",
117
+ "\u001b[90m1\u001b[39m \u001b[4m1\u001b[24m000 0 0 \u001b[4m1\u001b[24m000 0 0\n",
118
+ "Monthly rows after parsing: 18 \n"
119
+ ]
120
+ }
121
+ ],
122
+ "source": [
123
+ "\n",
124
+ "# ---------- helpers ----------\n",
125
+ "safe_num <- function(x) {\n",
126
+ " # strips anything that is not digit or dot\n",
127
+ " suppressWarnings(as.numeric(str_replace_all(as.character(x), \"[^0-9.]\", \"\")))\n",
128
+ "}\n",
129
+ "\n",
130
+ "parse_rating <- function(x) {\n",
131
+ " # Accept: 4, \"4\", \"4.0\", \"4/5\", \"4 out of 5\", \"⭐⭐⭐⭐\", etc.\n",
132
+ " x <- as.character(x)\n",
133
+ " x <- str_replace_all(x, \"⭐\", \"\")\n",
134
+ " x <- str_to_lower(x)\n",
135
+ " x <- str_replace_all(x, \"stars?\", \"\")\n",
136
+ " x <- str_replace_all(x, \"out of\", \"/\")\n",
137
+ " x <- str_replace_all(x, \"\\\\s+\", \"\")\n",
138
+ " x <- str_replace_all(x, \"[^0-9./]\", \"\")\n",
139
+ " suppressWarnings(as.numeric(str_extract(x, \"^[0-9.]+\")))\n",
140
+ "}\n",
141
+ "\n",
142
+ "parse_month <- function(x) {\n",
143
+ " x <- as.character(x)\n",
144
+ " # try YYYY-MM-DD, then YYYY-MM\n",
145
+ " out <- suppressWarnings(ymd(x))\n",
146
+ " if (mean(is.na(out)) > 0.5) out <- suppressWarnings(ymd(paste0(x, \"-01\")))\n",
147
+ " na_idx <- which(is.na(out))\n",
148
+ " if (length(na_idx) > 0) out[na_idx] <- suppressWarnings(ymd(paste0(x[na_idx], \"-01\")))\n",
149
+ " out\n",
150
+ "}\n",
151
+ "\n",
152
+ "# ---------- normalize keys ----------\n",
153
+ "df_title <- df_title %>% mutate(title = str_squish(as.character(title)))\n",
154
+ "df_month <- df_month %>% mutate(month = as.character(month))\n",
155
+ "\n",
156
+ "# ---------- parse numeric columns defensively ----------\n",
157
+ "need_cols_title <- c(\"title\",\"avg_revenue\",\"total_revenue\",\"price\",\"rating\",\"share_positive\",\"share_negative\",\"share_neutral\")\n",
158
+ "missing_title <- setdiff(need_cols_title, names(df_title))\n",
159
+ "if (length(missing_title) > 0) stop(paste0(\"df_title missing columns: \", paste(missing_title, collapse=\", \")))\n",
160
+ "\n",
161
+ "df_title <- df_title %>%\n",
162
+ " mutate(\n",
163
+ " avg_revenue = safe_num(avg_revenue),\n",
164
+ " total_revenue = safe_num(total_revenue),\n",
165
+ " price = safe_num(price),\n",
166
+ " rating = parse_rating(rating),\n",
167
+ " share_positive = safe_num(share_positive),\n",
168
+ " share_negative = safe_num(share_negative),\n",
169
+ " share_neutral = safe_num(share_neutral)\n",
170
+ " )\n",
171
+ "\n",
172
+ "# basic sanity stats\n",
173
+ "hyg <- df_title %>%\n",
174
+ " summarise(\n",
175
+ " n = n(),\n",
176
+ " na_avg_revenue = sum(is.na(avg_revenue)),\n",
177
+ " na_price = sum(is.na(price)),\n",
178
+ " na_rating = sum(is.na(rating)),\n",
179
+ " na_share_pos = sum(is.na(share_positive)),\n",
180
+ " na_share_neg = sum(is.na(share_negative))\n",
181
+ " )\n",
182
+ "\n",
183
+ "print(hyg)\n",
184
+ "\n",
185
+ "# monthly parsing\n",
186
+ "need_cols_month <- c(\"month\",\"total_revenue\")\n",
187
+ "missing_month <- setdiff(need_cols_month, names(df_month))\n",
188
+ "if (length(missing_month) > 0) stop(paste0(\"df_month missing columns: \", paste(missing_month, collapse=\", \")))\n",
189
+ "\n",
190
+ "df_month2 <- df_month %>%\n",
191
+ " mutate(\n",
192
+ " month = parse_month(month),\n",
193
+ " total_revenue = safe_num(total_revenue)\n",
194
+ " ) %>%\n",
195
+ " filter(!is.na(month)) %>%\n",
196
+ " arrange(month)\n",
197
+ "\n",
198
+ "cat(\"Monthly rows after parsing:\", nrow(df_month2), \"\\n\")"
199
+ ]
200
+ },
201
+ {
202
+ "cell_type": "markdown",
203
+ "id": "b8971bc4",
204
+ "metadata": {
205
+ "id": "b8971bc4"
206
+ },
207
+ "source": [
208
+ "## **3.** 💾 Folder for R outputs for Hugging Face"
209
+ ]
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "execution_count": null,
214
+ "id": "dfaa06b1",
215
+ "metadata": {
216
+ "colab": {
217
+ "base_uri": "https://localhost:8080/"
218
+ },
219
+ "id": "dfaa06b1",
220
+ "outputId": "73f6437a-39f4-4968-f88a-99f10a3fd8ae"
221
+ },
222
+ "outputs": [
223
+ {
224
+ "output_type": "stream",
225
+ "name": "stdout",
226
+ "text": [
227
+ "R outputs will be written to: /content/artifacts/r \n"
228
+ ]
229
+ }
230
+ ],
231
+ "source": [
232
+ "\n",
233
+ "ART_DIR <- \"artifacts\"\n",
234
+ "R_FIG_DIR <- file.path(ART_DIR, \"r\", \"figures\")\n",
235
+ "R_TAB_DIR <- file.path(ART_DIR, \"r\", \"tables\")\n",
236
+ "\n",
237
+ "dir.create(R_FIG_DIR, recursive = TRUE, showWarnings = FALSE)\n",
238
+ "dir.create(R_TAB_DIR, recursive = TRUE, showWarnings = FALSE)\n",
239
+ "\n",
240
+ "cat(\"R outputs will be written to:\", normalizePath(file.path(ART_DIR, \"r\"), winslash = \"/\"), \"\n",
241
+ "\")"
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "markdown",
246
+ "id": "f880c72d",
247
+ "metadata": {
248
+ "id": "f880c72d"
249
+ },
250
+ "source": [
251
+ "## **4.** 🔮 Forecast book sales benchmarking with `accuracy()`"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "markdown",
256
+ "source": [
257
+ "We benchmark **three** models on a holdout window (last *h* months):\n",
258
+ "- ARIMA + Fourier (seasonality upgrade)\n",
259
+ "- ETS\n",
260
+ "- Naive baseline\n",
261
+ "\n",
262
+ "Then we export:\n",
263
+ "- `accuracy_table.csv`\n",
264
+ "- `forecast_compare.png`\n",
265
+ "- `rmse_comparison.png`"
266
+ ],
267
+ "metadata": {
268
+ "id": "R0JZlzKegmzW"
269
+ },
270
+ "id": "R0JZlzKegmzW"
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "execution_count": null,
275
+ "id": "62e87992",
276
+ "metadata": {
277
+ "colab": {
278
+ "base_uri": "https://localhost:8080/"
279
+ },
280
+ "id": "62e87992",
281
+ "outputId": "73b36487-a25d-4bb9-cf80-8d5a654a2f0d"
282
+ },
283
+ "outputs": [
284
+ {
285
+ "output_type": "stream",
286
+ "name": "stdout",
287
+ "text": [
288
+ "✅ Saved: artifacts/r/tables/accuracy_table.csv\n",
289
+ "✅ Saved: artifacts/r/figures/rmse_comparison.png\n"
290
+ ]
291
+ },
292
+ {
293
+ "output_type": "display_data",
294
+ "data": {
295
+ "text/html": [
296
+ "<strong>agg_record_872216040:</strong> 2"
297
+ ],
298
+ "text/markdown": "**agg_record_872216040:** 2",
299
+ "text/latex": "\\textbf{agg\\textbackslash{}\\_record\\textbackslash{}\\_872216040:} 2",
300
+ "text/plain": [
301
+ "agg_record_872216040 \n",
302
+ " 2 "
303
+ ]
304
+ },
305
+ "metadata": {}
306
+ },
307
+ {
308
+ "output_type": "stream",
309
+ "name": "stdout",
310
+ "text": [
311
+ "✅ Saved: artifacts/r/figures/forecast_compare.png\n"
312
+ ]
313
+ }
314
+ ],
315
+ "source": [
316
+ "\n",
317
+ "# Build monthly ts\n",
318
+ "start_year <- year(min(df_month2$month, na.rm = TRUE))\n",
319
+ "start_mon <- month(min(df_month2$month, na.rm = TRUE))\n",
320
+ "\n",
321
+ "y <- ts(df_month2$total_revenue, frequency = 12, start = c(start_year, start_mon))\n",
322
+ "\n",
323
+ "# holdout size: min(6, 20% of series), at least 1\n",
324
+ "h_test <- min(6, max(1, floor(length(y) / 5)))\n",
325
+ "train_ts <- head(y, length(y) - h_test)\n",
326
+ "test_ts <- tail(y, h_test)\n",
327
+ "\n",
328
+ "# Model A: ARIMA + Fourier\n",
329
+ "K <- 2\n",
330
+ "xreg_train <- fourier(train_ts, K = K)\n",
331
+ "fit_arima <- auto.arima(train_ts, xreg = xreg_train)\n",
332
+ "xreg_future <- fourier(train_ts, K = K, h = h_test)\n",
333
+ "fc_arima <- forecast(fit_arima, xreg = xreg_future, h = h_test)\n",
334
+ "\n",
335
+ "# Model B: ETS\n",
336
+ "fit_ets <- ets(train_ts)\n",
337
+ "fc_ets <- forecast(fit_ets, h = h_test)\n",
338
+ "\n",
339
+ "# Model C: Naive baseline\n",
340
+ "fc_naive <- naive(train_ts, h = h_test)\n",
341
+ "\n",
342
+ "# accuracy() tables\n",
343
+ "acc_arima <- as.data.frame(accuracy(fc_arima, test_ts))\n",
344
+ "acc_ets <- as.data.frame(accuracy(fc_ets, test_ts))\n",
345
+ "acc_naive <- as.data.frame(accuracy(fc_naive, test_ts))\n",
346
+ "\n",
347
+ "accuracy_tbl <- bind_rows(\n",
348
+ " acc_arima %>% mutate(model = \"ARIMA+Fourier\"),\n",
349
+ " acc_ets %>% mutate(model = \"ETS\"),\n",
350
+ " acc_naive %>% mutate(model = \"Naive\")\n",
351
+ ") %>% relocate(model)\n",
352
+ "\n",
353
+ "write_csv(accuracy_tbl, file.path(R_TAB_DIR, \"accuracy_table.csv\"))\n",
354
+ "cat(\"✅ Saved: artifacts/r/tables/accuracy_table.csv\\n\")\n",
355
+ "\n",
356
+ "# RMSE bar chart\n",
357
+ "p_rmse <- ggplot(accuracy_tbl, aes(x = reorder(model, RMSE), y = RMSE)) +\n",
358
+ " geom_col() +\n",
359
+ " coord_flip() +\n",
360
+ " labs(title = \"Forecast model comparison (RMSE on holdout)\", x = \"\", y = \"RMSE\") +\n",
361
+ " theme_minimal()\n",
362
+ "\n",
363
+ "ggsave(file.path(R_FIG_DIR, \"rmse_comparison.png\"), p_rmse, width = 8, height = 4, dpi = 160)\n",
364
+ "cat(\"✅ Saved: artifacts/r/figures/rmse_comparison.png\\n\")\n",
365
+ "\n",
366
+ "# Side-by-side forecast plots (simple, no extra deps)\n",
367
+ "png(file.path(R_FIG_DIR, \"forecast_compare.png\"), width = 1200, height = 500)\n",
368
+ "par(mfrow = c(1, 3))\n",
369
+ "plot(fc_arima, main = \"ARIMA + Fourier\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
370
+ "plot(fc_ets, main = \"ETS\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
371
+ "plot(fc_naive, main = \"Naive\", xlab = \"Time\", ylab = \"Total revenue\"); lines(test_ts, col = \"black\")\n",
372
+ "dev.off()\n",
373
+ "cat(\"✅ Saved: artifacts/r/figures/forecast_compare.png\\n\")"
374
+ ]
375
+ },
376
+ {
377
+ "cell_type": "markdown",
378
+ "id": "30bc017b",
379
+ "metadata": {
380
+ "id": "30bc017b"
381
+ },
382
+ "source": [
383
+ "## **5.** 💾 Some R metadata for Hugging Face"
384
+ ]
385
+ },
386
+ {
387
+ "cell_type": "code",
388
+ "execution_count": null,
389
+ "id": "645cb12b",
390
+ "metadata": {
391
+ "colab": {
392
+ "base_uri": "https://localhost:8080/"
393
+ },
394
+ "id": "645cb12b",
395
+ "outputId": "c00c26da-7d27-4c78-a296-aa33807495d4"
396
+ },
397
+ "outputs": [
398
+ {
399
+ "output_type": "stream",
400
+ "name": "stdout",
401
+ "text": [
402
+ "✅ Saved: artifacts/r/tables/r_meta.json\n",
403
+ "DONE. R artifacts written to: artifacts/r \n"
404
+ ]
405
+ }
406
+ ],
407
+ "source": [
408
+ "# =========================================================\n",
409
+ "# Metadata export (aligned with current notebook objects)\n",
410
+ "# =========================================================\n",
411
+ "\n",
412
+ "meta <- list(\n",
413
+ "\n",
414
+ " # ---------------------------\n",
415
+ " # Dataset footprint\n",
416
+ " # ---------------------------\n",
417
+ " n_titles = nrow(df_title),\n",
418
+ " n_months = nrow(df_month2),\n",
419
+ "\n",
420
+ " # ---------------------------\n",
421
+ " # Forecasting info\n",
422
+ " # (only if these objects exist in your forecasting section)\n",
423
+ " # ---------------------------\n",
424
+ " forecasting = list(\n",
425
+ " holdout_h = h_test,\n",
426
+ " arima_order = forecast::arimaorder(fit_arima),\n",
427
+ " ets_method = fit_ets$method\n",
428
+ " )\n",
429
+ ")\n",
430
+ "\n",
431
+ "jsonlite::write_json(\n",
432
+ " meta,\n",
433
+ " path = file.path(R_TAB_DIR, \"r_meta.json\"),\n",
434
+ " pretty = TRUE,\n",
435
+ " auto_unbox = TRUE\n",
436
+ ")\n",
437
+ "\n",
438
+ "cat(\"✅ Saved: artifacts/r/tables/r_meta.json\\n\")\n",
439
+ "cat(\"DONE. R artifacts written to:\", file.path(ART_DIR, \"r\"), \"\\n\")\n"
440
+ ]
441
+ }
442
+ ],
443
+ "metadata": {
444
+ "colab": {
445
+ "provenance": [],
446
+ "collapsed_sections": [
447
+ "f01d02e7",
448
+ "b8971bc4",
449
+ "f880c72d",
450
+ "30bc017b"
451
+ ]
452
+ },
453
+ "kernelspec": {
454
+ "name": "ir",
455
+ "display_name": "R"
456
+ },
457
+ "language_info": {
458
+ "name": "R"
459
+ }
460
+ },
461
+ "nbformat": 4,
462
+ "nbformat_minor": 5
463
+ }