Files changed (3) hide show
  1. Data Creation.ipynb +1460 -0
  2. Python Analysis.ipynb +0 -0
  3. R analysis.ipynb +463 -0
Data Creation.ipynb ADDED
@@ -0,0 +1,1460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": "0a6f08ea-e057-4fae-9483-aad27ee8388e"
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": 10,
149
+ "metadata": {
150
+ "id": "l5FkkNhUYTHh"
151
+ },
152
+ "outputs": [],
153
+ "source": [
154
+ "import pandas as pd\n",
155
+ "\n",
156
+ "df_books = pd.DataFrame({\n",
157
+ " \"title\": titles,\n",
158
+ " \"price\": prices,\n",
159
+ " \"rating\": ratings\n",
160
+ "})\n"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "markdown",
165
+ "metadata": {
166
+ "id": "duI5dv3CZYvF"
167
+ },
168
+ "source": [
169
+ "### *d. Save web-scraped dataframe either as a CSV or Excel file*"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "execution_count": 8,
175
+ "metadata": {
176
+ "id": "lC1U_YHtZifh"
177
+ },
178
+ "outputs": [],
179
+ "source": [
180
+ "# 💾 Save to CSV\n",
181
+ "df_books.to_csv(\"books_data.csv\", index=False)\n",
182
+ "\n",
183
+ "# 💾 Or save to Excel\n",
184
+ "# df_books.to_excel(\"books_data.xlsx\", index=False)"
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "markdown",
189
+ "metadata": {
190
+ "id": "qMjRKMBQZlJi"
191
+ },
192
+ "source": [
193
+ "### *e. ✋🏻🛑⛔️ View first fiew lines*"
194
+ ]
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "execution_count": 9,
199
+ "metadata": {
200
+ "colab": {
201
+ "base_uri": "https://localhost:8080/",
202
+ "height": 206
203
+ },
204
+ "id": "O_wIvTxYZqCK",
205
+ "outputId": "fe674e7c-c410-4eb9-d4d6-1eddbed00698"
206
+ },
207
+ "outputs": [
208
+ {
209
+ "output_type": "execute_result",
210
+ "data": {
211
+ "text/plain": [
212
+ " title price rating\n",
213
+ "0 A Light in the Attic 51.77 Three\n",
214
+ "1 Tipping the Velvet 53.74 One\n",
215
+ "2 Soumission 50.10 One\n",
216
+ "3 Sharp Objects 47.82 Four\n",
217
+ "4 Sapiens: A Brief History of Humankind 54.23 Five"
218
+ ],
219
+ "text/html": [
220
+ "\n",
221
+ " <div id=\"df-6f4462a3-22fa-4894-89db-90bb2c335581\" class=\"colab-df-container\">\n",
222
+ " <div>\n",
223
+ "<style scoped>\n",
224
+ " .dataframe tbody tr th:only-of-type {\n",
225
+ " vertical-align: middle;\n",
226
+ " }\n",
227
+ "\n",
228
+ " .dataframe tbody tr th {\n",
229
+ " vertical-align: top;\n",
230
+ " }\n",
231
+ "\n",
232
+ " .dataframe thead th {\n",
233
+ " text-align: right;\n",
234
+ " }\n",
235
+ "</style>\n",
236
+ "<table border=\"1\" class=\"dataframe\">\n",
237
+ " <thead>\n",
238
+ " <tr style=\"text-align: right;\">\n",
239
+ " <th></th>\n",
240
+ " <th>title</th>\n",
241
+ " <th>price</th>\n",
242
+ " <th>rating</th>\n",
243
+ " </tr>\n",
244
+ " </thead>\n",
245
+ " <tbody>\n",
246
+ " <tr>\n",
247
+ " <th>0</th>\n",
248
+ " <td>A Light in the Attic</td>\n",
249
+ " <td>51.77</td>\n",
250
+ " <td>Three</td>\n",
251
+ " </tr>\n",
252
+ " <tr>\n",
253
+ " <th>1</th>\n",
254
+ " <td>Tipping the Velvet</td>\n",
255
+ " <td>53.74</td>\n",
256
+ " <td>One</td>\n",
257
+ " </tr>\n",
258
+ " <tr>\n",
259
+ " <th>2</th>\n",
260
+ " <td>Soumission</td>\n",
261
+ " <td>50.10</td>\n",
262
+ " <td>One</td>\n",
263
+ " </tr>\n",
264
+ " <tr>\n",
265
+ " <th>3</th>\n",
266
+ " <td>Sharp Objects</td>\n",
267
+ " <td>47.82</td>\n",
268
+ " <td>Four</td>\n",
269
+ " </tr>\n",
270
+ " <tr>\n",
271
+ " <th>4</th>\n",
272
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
273
+ " <td>54.23</td>\n",
274
+ " <td>Five</td>\n",
275
+ " </tr>\n",
276
+ " </tbody>\n",
277
+ "</table>\n",
278
+ "</div>\n",
279
+ " <div class=\"colab-df-buttons\">\n",
280
+ "\n",
281
+ " <div class=\"colab-df-container\">\n",
282
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-6f4462a3-22fa-4894-89db-90bb2c335581')\"\n",
283
+ " title=\"Convert this dataframe to an interactive table.\"\n",
284
+ " style=\"display:none;\">\n",
285
+ "\n",
286
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
287
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
288
+ " </svg>\n",
289
+ " </button>\n",
290
+ "\n",
291
+ " <style>\n",
292
+ " .colab-df-container {\n",
293
+ " display:flex;\n",
294
+ " gap: 12px;\n",
295
+ " }\n",
296
+ "\n",
297
+ " .colab-df-convert {\n",
298
+ " background-color: #E8F0FE;\n",
299
+ " border: none;\n",
300
+ " border-radius: 50%;\n",
301
+ " cursor: pointer;\n",
302
+ " display: none;\n",
303
+ " fill: #1967D2;\n",
304
+ " height: 32px;\n",
305
+ " padding: 0 0 0 0;\n",
306
+ " width: 32px;\n",
307
+ " }\n",
308
+ "\n",
309
+ " .colab-df-convert:hover {\n",
310
+ " background-color: #E2EBFA;\n",
311
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
312
+ " fill: #174EA6;\n",
313
+ " }\n",
314
+ "\n",
315
+ " .colab-df-buttons div {\n",
316
+ " margin-bottom: 4px;\n",
317
+ " }\n",
318
+ "\n",
319
+ " [theme=dark] .colab-df-convert {\n",
320
+ " background-color: #3B4455;\n",
321
+ " fill: #D2E3FC;\n",
322
+ " }\n",
323
+ "\n",
324
+ " [theme=dark] .colab-df-convert:hover {\n",
325
+ " background-color: #434B5C;\n",
326
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
327
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
328
+ " fill: #FFFFFF;\n",
329
+ " }\n",
330
+ " </style>\n",
331
+ "\n",
332
+ " <script>\n",
333
+ " const buttonEl =\n",
334
+ " document.querySelector('#df-6f4462a3-22fa-4894-89db-90bb2c335581 button.colab-df-convert');\n",
335
+ " buttonEl.style.display =\n",
336
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
337
+ "\n",
338
+ " async function convertToInteractive(key) {\n",
339
+ " const element = document.querySelector('#df-6f4462a3-22fa-4894-89db-90bb2c335581');\n",
340
+ " const dataTable =\n",
341
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
342
+ " [key], {});\n",
343
+ " if (!dataTable) return;\n",
344
+ "\n",
345
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
346
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
347
+ " + ' to learn more about interactive tables.';\n",
348
+ " element.innerHTML = '';\n",
349
+ " dataTable['output_type'] = 'display_data';\n",
350
+ " await google.colab.output.renderOutput(dataTable, element);\n",
351
+ " const docLink = document.createElement('div');\n",
352
+ " docLink.innerHTML = docLinkHtml;\n",
353
+ " element.appendChild(docLink);\n",
354
+ " }\n",
355
+ " </script>\n",
356
+ " </div>\n",
357
+ "\n",
358
+ "\n",
359
+ " </div>\n",
360
+ " </div>\n"
361
+ ],
362
+ "application/vnd.google.colaboratory.intrinsic+json": {
363
+ "type": "dataframe",
364
+ "variable_name": "df_books",
365
+ "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}"
366
+ }
367
+ },
368
+ "metadata": {},
369
+ "execution_count": 9
370
+ }
371
+ ],
372
+ "source": [
373
+ "df_books.head()"
374
+ ]
375
+ },
376
+ {
377
+ "cell_type": "markdown",
378
+ "metadata": {
379
+ "id": "p-1Pr2szaqLk"
380
+ },
381
+ "source": [
382
+ "## **3.** 🧩 Create a meaningful connection between real & synthetic datasets"
383
+ ]
384
+ },
385
+ {
386
+ "cell_type": "markdown",
387
+ "metadata": {
388
+ "id": "SIaJUGIpaH4V"
389
+ },
390
+ "source": [
391
+ "### *a. Initial setup*"
392
+ ]
393
+ },
394
+ {
395
+ "cell_type": "code",
396
+ "execution_count": 11,
397
+ "metadata": {
398
+ "id": "-gPXGcRPuV_9"
399
+ },
400
+ "outputs": [],
401
+ "source": [
402
+ "import numpy as np\n",
403
+ "import random\n",
404
+ "from datetime import datetime\n",
405
+ "import warnings\n",
406
+ "\n",
407
+ "warnings.filterwarnings(\"ignore\")\n",
408
+ "random.seed(2025)\n",
409
+ "np.random.seed(2025)"
410
+ ]
411
+ },
412
+ {
413
+ "cell_type": "markdown",
414
+ "metadata": {
415
+ "id": "pY4yCoIuaQqp"
416
+ },
417
+ "source": [
418
+ "### *b. Generate popularity scores based on rating (with some randomness) with a generate_popularity_score function*"
419
+ ]
420
+ },
421
+ {
422
+ "cell_type": "code",
423
+ "execution_count": 12,
424
+ "metadata": {
425
+ "id": "mnd5hdAbaNjz"
426
+ },
427
+ "outputs": [],
428
+ "source": [
429
+ "def generate_popularity_score(rating):\n",
430
+ " base = {\"One\": 2, \"Two\": 3, \"Three\": 3, \"Four\": 4, \"Five\": 4}.get(rating, 3)\n",
431
+ " trend_factor = random.choices([-1, 0, 1], weights=[1, 3, 2])[0]\n",
432
+ " return int(np.clip(base + trend_factor, 1, 5))"
433
+ ]
434
+ },
435
+ {
436
+ "cell_type": "markdown",
437
+ "metadata": {
438
+ "id": "n4-TaNTFgPak"
439
+ },
440
+ "source": [
441
+ "### *c. ✋🏻🛑⛔️ Run the function to create a \"popularity_score\" column from \"rating\"*"
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "code",
446
+ "execution_count": 13,
447
+ "metadata": {
448
+ "id": "V-G3OCUCgR07",
449
+ "colab": {
450
+ "base_uri": "https://localhost:8080/",
451
+ "height": 206
452
+ },
453
+ "outputId": "4e65abfc-0039-4801-b061-fb581f7e101d"
454
+ },
455
+ "outputs": [
456
+ {
457
+ "output_type": "execute_result",
458
+ "data": {
459
+ "text/plain": [
460
+ " title price rating popularity_score\n",
461
+ "0 A Light in the Attic 51.77 Three 3\n",
462
+ "1 Tipping the Velvet 53.74 One 2\n",
463
+ "2 Soumission 50.10 One 2\n",
464
+ "3 Sharp Objects 47.82 Four 4\n",
465
+ "4 Sapiens: A Brief History of Humankind 54.23 Five 3"
466
+ ],
467
+ "text/html": [
468
+ "\n",
469
+ " <div id=\"df-2812fe27-a316-4056-a71d-0eb3b7f29fa8\" class=\"colab-df-container\">\n",
470
+ " <div>\n",
471
+ "<style scoped>\n",
472
+ " .dataframe tbody tr th:only-of-type {\n",
473
+ " vertical-align: middle;\n",
474
+ " }\n",
475
+ "\n",
476
+ " .dataframe tbody tr th {\n",
477
+ " vertical-align: top;\n",
478
+ " }\n",
479
+ "\n",
480
+ " .dataframe thead th {\n",
481
+ " text-align: right;\n",
482
+ " }\n",
483
+ "</style>\n",
484
+ "<table border=\"1\" class=\"dataframe\">\n",
485
+ " <thead>\n",
486
+ " <tr style=\"text-align: right;\">\n",
487
+ " <th></th>\n",
488
+ " <th>title</th>\n",
489
+ " <th>price</th>\n",
490
+ " <th>rating</th>\n",
491
+ " <th>popularity_score</th>\n",
492
+ " </tr>\n",
493
+ " </thead>\n",
494
+ " <tbody>\n",
495
+ " <tr>\n",
496
+ " <th>0</th>\n",
497
+ " <td>A Light in the Attic</td>\n",
498
+ " <td>51.77</td>\n",
499
+ " <td>Three</td>\n",
500
+ " <td>3</td>\n",
501
+ " </tr>\n",
502
+ " <tr>\n",
503
+ " <th>1</th>\n",
504
+ " <td>Tipping the Velvet</td>\n",
505
+ " <td>53.74</td>\n",
506
+ " <td>One</td>\n",
507
+ " <td>2</td>\n",
508
+ " </tr>\n",
509
+ " <tr>\n",
510
+ " <th>2</th>\n",
511
+ " <td>Soumission</td>\n",
512
+ " <td>50.10</td>\n",
513
+ " <td>One</td>\n",
514
+ " <td>2</td>\n",
515
+ " </tr>\n",
516
+ " <tr>\n",
517
+ " <th>3</th>\n",
518
+ " <td>Sharp Objects</td>\n",
519
+ " <td>47.82</td>\n",
520
+ " <td>Four</td>\n",
521
+ " <td>4</td>\n",
522
+ " </tr>\n",
523
+ " <tr>\n",
524
+ " <th>4</th>\n",
525
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
526
+ " <td>54.23</td>\n",
527
+ " <td>Five</td>\n",
528
+ " <td>3</td>\n",
529
+ " </tr>\n",
530
+ " </tbody>\n",
531
+ "</table>\n",
532
+ "</div>\n",
533
+ " <div class=\"colab-df-buttons\">\n",
534
+ "\n",
535
+ " <div class=\"colab-df-container\">\n",
536
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-2812fe27-a316-4056-a71d-0eb3b7f29fa8')\"\n",
537
+ " title=\"Convert this dataframe to an interactive table.\"\n",
538
+ " style=\"display:none;\">\n",
539
+ "\n",
540
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
541
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
542
+ " </svg>\n",
543
+ " </button>\n",
544
+ "\n",
545
+ " <style>\n",
546
+ " .colab-df-container {\n",
547
+ " display:flex;\n",
548
+ " gap: 12px;\n",
549
+ " }\n",
550
+ "\n",
551
+ " .colab-df-convert {\n",
552
+ " background-color: #E8F0FE;\n",
553
+ " border: none;\n",
554
+ " border-radius: 50%;\n",
555
+ " cursor: pointer;\n",
556
+ " display: none;\n",
557
+ " fill: #1967D2;\n",
558
+ " height: 32px;\n",
559
+ " padding: 0 0 0 0;\n",
560
+ " width: 32px;\n",
561
+ " }\n",
562
+ "\n",
563
+ " .colab-df-convert:hover {\n",
564
+ " background-color: #E2EBFA;\n",
565
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
566
+ " fill: #174EA6;\n",
567
+ " }\n",
568
+ "\n",
569
+ " .colab-df-buttons div {\n",
570
+ " margin-bottom: 4px;\n",
571
+ " }\n",
572
+ "\n",
573
+ " [theme=dark] .colab-df-convert {\n",
574
+ " background-color: #3B4455;\n",
575
+ " fill: #D2E3FC;\n",
576
+ " }\n",
577
+ "\n",
578
+ " [theme=dark] .colab-df-convert:hover {\n",
579
+ " background-color: #434B5C;\n",
580
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
581
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
582
+ " fill: #FFFFFF;\n",
583
+ " }\n",
584
+ " </style>\n",
585
+ "\n",
586
+ " <script>\n",
587
+ " const buttonEl =\n",
588
+ " document.querySelector('#df-2812fe27-a316-4056-a71d-0eb3b7f29fa8 button.colab-df-convert');\n",
589
+ " buttonEl.style.display =\n",
590
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
591
+ "\n",
592
+ " async function convertToInteractive(key) {\n",
593
+ " const element = document.querySelector('#df-2812fe27-a316-4056-a71d-0eb3b7f29fa8');\n",
594
+ " const dataTable =\n",
595
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
596
+ " [key], {});\n",
597
+ " if (!dataTable) return;\n",
598
+ "\n",
599
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
600
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
601
+ " + ' to learn more about interactive tables.';\n",
602
+ " element.innerHTML = '';\n",
603
+ " dataTable['output_type'] = 'display_data';\n",
604
+ " await google.colab.output.renderOutput(dataTable, element);\n",
605
+ " const docLink = document.createElement('div');\n",
606
+ " docLink.innerHTML = docLinkHtml;\n",
607
+ " element.appendChild(docLink);\n",
608
+ " }\n",
609
+ " </script>\n",
610
+ " </div>\n",
611
+ "\n",
612
+ "\n",
613
+ " </div>\n",
614
+ " </div>\n"
615
+ ],
616
+ "application/vnd.google.colaboratory.intrinsic+json": {
617
+ "type": "dataframe",
618
+ "variable_name": "df_books",
619
+ "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}"
620
+ }
621
+ },
622
+ "metadata": {},
623
+ "execution_count": 13
624
+ }
625
+ ],
626
+ "source": [
627
+ "df_books[\"popularity_score\"] = df_books[\"rating\"].apply(generate_popularity_score)\n",
628
+ "\n",
629
+ "\n",
630
+ "df_books.head()\n"
631
+ ]
632
+ },
633
+ {
634
+ "cell_type": "markdown",
635
+ "metadata": {
636
+ "id": "HnngRNTgacYt"
637
+ },
638
+ "source": [
639
+ "### *d. Decide on the sentiment_label based on the popularity score with a get_sentiment function*"
640
+ ]
641
+ },
642
+ {
643
+ "cell_type": "code",
644
+ "execution_count": 14,
645
+ "metadata": {
646
+ "id": "kUtWmr8maZLZ"
647
+ },
648
+ "outputs": [],
649
+ "source": [
650
+ "def get_sentiment(popularity_score):\n",
651
+ " if popularity_score <= 2:\n",
652
+ " return \"negative\"\n",
653
+ " elif popularity_score == 3:\n",
654
+ " return \"neutral\"\n",
655
+ " else:\n",
656
+ " return \"positive\""
657
+ ]
658
+ },
659
+ {
660
+ "cell_type": "markdown",
661
+ "metadata": {
662
+ "id": "HF9F9HIzgT7Z"
663
+ },
664
+ "source": [
665
+ "### *e. ✋🏻🛑⛔️ Run the function to create a \"sentiment_label\" column from \"popularity_score\"*"
666
+ ]
667
+ },
668
+ {
669
+ "cell_type": "code",
670
+ "execution_count": 15,
671
+ "metadata": {
672
+ "id": "tafQj8_7gYCG",
673
+ "colab": {
674
+ "base_uri": "https://localhost:8080/",
675
+ "height": 206
676
+ },
677
+ "outputId": "07fc6456-60e3-405c-f87a-db8fd5535125"
678
+ },
679
+ "outputs": [
680
+ {
681
+ "output_type": "execute_result",
682
+ "data": {
683
+ "text/plain": [
684
+ " title price rating popularity_score \\\n",
685
+ "0 A Light in the Attic 51.77 Three 3 \n",
686
+ "1 Tipping the Velvet 53.74 One 2 \n",
687
+ "2 Soumission 50.10 One 2 \n",
688
+ "3 Sharp Objects 47.82 Four 4 \n",
689
+ "4 Sapiens: A Brief History of Humankind 54.23 Five 3 \n",
690
+ "\n",
691
+ " sentiment_label \n",
692
+ "0 neutral \n",
693
+ "1 negative \n",
694
+ "2 negative \n",
695
+ "3 positive \n",
696
+ "4 neutral "
697
+ ],
698
+ "text/html": [
699
+ "\n",
700
+ " <div id=\"df-9537d073-a849-4441-b0c6-1ee8dfe24ba5\" class=\"colab-df-container\">\n",
701
+ " <div>\n",
702
+ "<style scoped>\n",
703
+ " .dataframe tbody tr th:only-of-type {\n",
704
+ " vertical-align: middle;\n",
705
+ " }\n",
706
+ "\n",
707
+ " .dataframe tbody tr th {\n",
708
+ " vertical-align: top;\n",
709
+ " }\n",
710
+ "\n",
711
+ " .dataframe thead th {\n",
712
+ " text-align: right;\n",
713
+ " }\n",
714
+ "</style>\n",
715
+ "<table border=\"1\" class=\"dataframe\">\n",
716
+ " <thead>\n",
717
+ " <tr style=\"text-align: right;\">\n",
718
+ " <th></th>\n",
719
+ " <th>title</th>\n",
720
+ " <th>price</th>\n",
721
+ " <th>rating</th>\n",
722
+ " <th>popularity_score</th>\n",
723
+ " <th>sentiment_label</th>\n",
724
+ " </tr>\n",
725
+ " </thead>\n",
726
+ " <tbody>\n",
727
+ " <tr>\n",
728
+ " <th>0</th>\n",
729
+ " <td>A Light in the Attic</td>\n",
730
+ " <td>51.77</td>\n",
731
+ " <td>Three</td>\n",
732
+ " <td>3</td>\n",
733
+ " <td>neutral</td>\n",
734
+ " </tr>\n",
735
+ " <tr>\n",
736
+ " <th>1</th>\n",
737
+ " <td>Tipping the Velvet</td>\n",
738
+ " <td>53.74</td>\n",
739
+ " <td>One</td>\n",
740
+ " <td>2</td>\n",
741
+ " <td>negative</td>\n",
742
+ " </tr>\n",
743
+ " <tr>\n",
744
+ " <th>2</th>\n",
745
+ " <td>Soumission</td>\n",
746
+ " <td>50.10</td>\n",
747
+ " <td>One</td>\n",
748
+ " <td>2</td>\n",
749
+ " <td>negative</td>\n",
750
+ " </tr>\n",
751
+ " <tr>\n",
752
+ " <th>3</th>\n",
753
+ " <td>Sharp Objects</td>\n",
754
+ " <td>47.82</td>\n",
755
+ " <td>Four</td>\n",
756
+ " <td>4</td>\n",
757
+ " <td>positive</td>\n",
758
+ " </tr>\n",
759
+ " <tr>\n",
760
+ " <th>4</th>\n",
761
+ " <td>Sapiens: A Brief History of Humankind</td>\n",
762
+ " <td>54.23</td>\n",
763
+ " <td>Five</td>\n",
764
+ " <td>3</td>\n",
765
+ " <td>neutral</td>\n",
766
+ " </tr>\n",
767
+ " </tbody>\n",
768
+ "</table>\n",
769
+ "</div>\n",
770
+ " <div class=\"colab-df-buttons\">\n",
771
+ "\n",
772
+ " <div class=\"colab-df-container\">\n",
773
+ " <button class=\"colab-df-convert\" onclick=\"convertToInteractive('df-9537d073-a849-4441-b0c6-1ee8dfe24ba5')\"\n",
774
+ " title=\"Convert this dataframe to an interactive table.\"\n",
775
+ " style=\"display:none;\">\n",
776
+ "\n",
777
+ " <svg xmlns=\"http://www.w3.org/2000/svg\" height=\"24px\" viewBox=\"0 -960 960 960\">\n",
778
+ " <path d=\"M120-120v-720h720v720H120Zm60-500h600v-160H180v160Zm220 220h160v-160H400v160Zm0 220h160v-160H400v160ZM180-400h160v-160H180v160Zm440 0h160v-160H620v160ZM180-180h160v-160H180v160Zm440 0h160v-160H620v160Z\"/>\n",
779
+ " </svg>\n",
780
+ " </button>\n",
781
+ "\n",
782
+ " <style>\n",
783
+ " .colab-df-container {\n",
784
+ " display:flex;\n",
785
+ " gap: 12px;\n",
786
+ " }\n",
787
+ "\n",
788
+ " .colab-df-convert {\n",
789
+ " background-color: #E8F0FE;\n",
790
+ " border: none;\n",
791
+ " border-radius: 50%;\n",
792
+ " cursor: pointer;\n",
793
+ " display: none;\n",
794
+ " fill: #1967D2;\n",
795
+ " height: 32px;\n",
796
+ " padding: 0 0 0 0;\n",
797
+ " width: 32px;\n",
798
+ " }\n",
799
+ "\n",
800
+ " .colab-df-convert:hover {\n",
801
+ " background-color: #E2EBFA;\n",
802
+ " box-shadow: 0px 1px 2px rgba(60, 64, 67, 0.3), 0px 1px 3px 1px rgba(60, 64, 67, 0.15);\n",
803
+ " fill: #174EA6;\n",
804
+ " }\n",
805
+ "\n",
806
+ " .colab-df-buttons div {\n",
807
+ " margin-bottom: 4px;\n",
808
+ " }\n",
809
+ "\n",
810
+ " [theme=dark] .colab-df-convert {\n",
811
+ " background-color: #3B4455;\n",
812
+ " fill: #D2E3FC;\n",
813
+ " }\n",
814
+ "\n",
815
+ " [theme=dark] .colab-df-convert:hover {\n",
816
+ " background-color: #434B5C;\n",
817
+ " box-shadow: 0px 1px 3px 1px rgba(0, 0, 0, 0.15);\n",
818
+ " filter: drop-shadow(0px 1px 2px rgba(0, 0, 0, 0.3));\n",
819
+ " fill: #FFFFFF;\n",
820
+ " }\n",
821
+ " </style>\n",
822
+ "\n",
823
+ " <script>\n",
824
+ " const buttonEl =\n",
825
+ " document.querySelector('#df-9537d073-a849-4441-b0c6-1ee8dfe24ba5 button.colab-df-convert');\n",
826
+ " buttonEl.style.display =\n",
827
+ " google.colab.kernel.accessAllowed ? 'block' : 'none';\n",
828
+ "\n",
829
+ " async function convertToInteractive(key) {\n",
830
+ " const element = document.querySelector('#df-9537d073-a849-4441-b0c6-1ee8dfe24ba5');\n",
831
+ " const dataTable =\n",
832
+ " await google.colab.kernel.invokeFunction('convertToInteractive',\n",
833
+ " [key], {});\n",
834
+ " if (!dataTable) return;\n",
835
+ "\n",
836
+ " const docLinkHtml = 'Like what you see? Visit the ' +\n",
837
+ " '<a target=\"_blank\" href=https://colab.research.google.com/notebooks/data_table.ipynb>data table notebook</a>'\n",
838
+ " + ' to learn more about interactive tables.';\n",
839
+ " element.innerHTML = '';\n",
840
+ " dataTable['output_type'] = 'display_data';\n",
841
+ " await google.colab.output.renderOutput(dataTable, element);\n",
842
+ " const docLink = document.createElement('div');\n",
843
+ " docLink.innerHTML = docLinkHtml;\n",
844
+ " element.appendChild(docLink);\n",
845
+ " }\n",
846
+ " </script>\n",
847
+ " </div>\n",
848
+ "\n",
849
+ "\n",
850
+ " </div>\n",
851
+ " </div>\n"
852
+ ],
853
+ "application/vnd.google.colaboratory.intrinsic+json": {
854
+ "type": "dataframe",
855
+ "variable_name": "df_books",
856
+ "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}"
857
+ }
858
+ },
859
+ "metadata": {},
860
+ "execution_count": 15
861
+ }
862
+ ],
863
+ "source": [
864
+ "df_books[\"sentiment_label\"] = df_books[\"popularity_score\"].apply(get_sentiment)\n",
865
+ "\n",
866
+ "\n",
867
+ "df_books.head()\n"
868
+ ]
869
+ },
870
+ {
871
+ "cell_type": "markdown",
872
+ "metadata": {
873
+ "id": "T8AdKkmASq9a"
874
+ },
875
+ "source": [
876
+ "## **4.** 📈 Generate synthetic book sales data of 18 months"
877
+ ]
878
+ },
879
+ {
880
+ "cell_type": "markdown",
881
+ "metadata": {
882
+ "id": "OhXbdGD5fH0c"
883
+ },
884
+ "source": [
885
+ "### *a. Create a generate_sales_profit function that would generate sales patterns based on sentiment_label (with some randomness)*"
886
+ ]
887
+ },
888
+ {
889
+ "cell_type": "code",
890
+ "execution_count": 16,
891
+ "metadata": {
892
+ "id": "qkVhYPXGbgEn"
893
+ },
894
+ "outputs": [],
895
+ "source": [
896
+ "def generate_sales_profile(sentiment):\n",
897
+ " months = pd.date_range(end=datetime.today(), periods=18, freq=\"M\")\n",
898
+ "\n",
899
+ " if sentiment == \"positive\":\n",
900
+ " base = random.randint(200, 300)\n",
901
+ " trend = np.linspace(base, base + random.randint(20, 60), len(months))\n",
902
+ " elif sentiment == \"negative\":\n",
903
+ " base = random.randint(20, 80)\n",
904
+ " trend = np.linspace(base, base - random.randint(10, 30), len(months))\n",
905
+ " else: # neutral\n",
906
+ " base = random.randint(80, 160)\n",
907
+ " trend = np.full(len(months), base + random.randint(-10, 10))\n",
908
+ "\n",
909
+ " seasonality = 10 * np.sin(np.linspace(0, 3 * np.pi, len(months)))\n",
910
+ " noise = np.random.normal(0, 5, len(months))\n",
911
+ " monthly_sales = np.clip(trend + seasonality + noise, a_min=0, a_max=None).astype(int)\n",
912
+ "\n",
913
+ " return list(zip(months.strftime(\"%Y-%m\"), monthly_sales))"
914
+ ]
915
+ },
916
+ {
917
+ "cell_type": "markdown",
918
+ "metadata": {
919
+ "id": "L2ak1HlcgoTe"
920
+ },
921
+ "source": [
922
+ "### *b. Run the function as part of building sales_data*"
923
+ ]
924
+ },
925
+ {
926
+ "cell_type": "code",
927
+ "execution_count": 17,
928
+ "metadata": {
929
+ "id": "SlJ24AUafoDB"
930
+ },
931
+ "outputs": [],
932
+ "source": [
933
+ "sales_data = []\n",
934
+ "for _, row in df_books.iterrows():\n",
935
+ " records = generate_sales_profile(row[\"sentiment_label\"])\n",
936
+ " for month, units in records:\n",
937
+ " sales_data.append({\n",
938
+ " \"title\": row[\"title\"],\n",
939
+ " \"month\": month,\n",
940
+ " \"units_sold\": units,\n",
941
+ " \"sentiment_label\": row[\"sentiment_label\"]\n",
942
+ " })"
943
+ ]
944
+ },
945
+ {
946
+ "cell_type": "markdown",
947
+ "metadata": {
948
+ "id": "4IXZKcCSgxnq"
949
+ },
950
+ "source": [
951
+ "### *c. ✋🏻🛑⛔️ Create a df_sales DataFrame from sales_data*"
952
+ ]
953
+ },
954
+ {
955
+ "cell_type": "code",
956
+ "execution_count": 20,
957
+ "metadata": {
958
+ "id": "wcN6gtiZg-ws"
959
+ },
960
+ "outputs": [],
961
+ "source": [
962
+ "df_sales = pd.DataFrame(sales_data)\n",
963
+ "\n"
964
+ ]
965
+ },
966
+ {
967
+ "cell_type": "markdown",
968
+ "metadata": {
969
+ "id": "EhIjz9WohAmZ"
970
+ },
971
+ "source": [
972
+ "### *d. Save df_sales as synthetic_sales_data.csv & view first few lines*"
973
+ ]
974
+ },
975
+ {
976
+ "cell_type": "code",
977
+ "execution_count": 19,
978
+ "metadata": {
979
+ "colab": {
980
+ "base_uri": "https://localhost:8080/"
981
+ },
982
+ "id": "MzbZvLcAhGaH",
983
+ "outputId": "03e6d85a-f16a-4279-aa5e-50b62020e216"
984
+ },
985
+ "outputs": [
986
+ {
987
+ "output_type": "stream",
988
+ "name": "stdout",
989
+ "text": [
990
+ " title month units_sold sentiment_label\n",
991
+ "0 A Light in the Attic 2024-08 100 neutral\n",
992
+ "1 A Light in the Attic 2024-09 109 neutral\n",
993
+ "2 A Light in the Attic 2024-10 102 neutral\n",
994
+ "3 A Light in the Attic 2024-11 107 neutral\n",
995
+ "4 A Light in the Attic 2024-12 108 neutral\n"
996
+ ]
997
+ }
998
+ ],
999
+ "source": [
1000
+ "df_sales.to_csv(\"synthetic_sales_data.csv\", index=False)\n",
1001
+ "\n",
1002
+ "print(df_sales.head())"
1003
+ ]
1004
+ },
1005
+ {
1006
+ "cell_type": "markdown",
1007
+ "metadata": {
1008
+ "id": "7g9gqBgQMtJn"
1009
+ },
1010
+ "source": [
1011
+ "## **5.** 🎯 Generate synthetic customer reviews"
1012
+ ]
1013
+ },
1014
+ {
1015
+ "cell_type": "markdown",
1016
+ "metadata": {
1017
+ "id": "Gi4y9M9KuDWx"
1018
+ },
1019
+ "source": [
1020
+ "### *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*"
1021
+ ]
1022
+ },
1023
+ {
1024
+ "cell_type": "code",
1025
+ "execution_count": 21,
1026
+ "metadata": {
1027
+ "id": "b3cd2a50"
1028
+ },
1029
+ "outputs": [],
1030
+ "source": [
1031
+ "synthetic_reviews_by_sentiment = {\n",
1032
+ " \"positive\": [\n",
1033
+ " \"A compelling and heartwarming read that stayed with me long after I finished.\",\n",
1034
+ " \"Brilliantly written with unforgettable characters.\",\n",
1035
+ " \"An inspiring story that exceeded all my expectations.\",\n",
1036
+ " \"Beautiful prose and a deeply engaging plot.\",\n",
1037
+ " \"I couldn’t put it down — absolutely captivating.\",\n",
1038
+ " \"A masterpiece of storytelling from start to finish.\",\n",
1039
+ " \"Emotionally rich and wonderfully crafted.\",\n",
1040
+ " \"An uplifting and powerful narrative.\",\n",
1041
+ " \"The characters felt alive and relatable.\",\n",
1042
+ " \"An unforgettable literary experience.\",\n",
1043
+ " \"Smart, moving, and expertly written.\",\n",
1044
+ " \"A delightful surprise that kept me hooked.\",\n",
1045
+ " \"Full of depth, charm, and insight.\",\n",
1046
+ " \"An immersive world I didn’t want to leave.\",\n",
1047
+ " \"Thought-provoking and beautifully paced.\",\n",
1048
+ " \"An exceptional read with a satisfying ending.\",\n",
1049
+ " \"Creative, engaging, and emotionally resonant.\",\n",
1050
+ " \"A truly rewarding reading experience.\",\n",
1051
+ " \"The writing style was elegant and fluid.\",\n",
1052
+ " \"A fantastic journey from beginning to end.\",\n",
1053
+ " \"Deeply touching and well structured.\",\n",
1054
+ " \"A refreshing and original story.\",\n",
1055
+ " \"Rich in detail and wonderfully developed.\",\n",
1056
+ " \"An absolute joy to read.\",\n",
1057
+ " \"Compelling themes handled with care.\",\n",
1058
+ " \"A page-turner with heart.\",\n",
1059
+ " \"Inventive and emotionally satisfying.\",\n",
1060
+ " \"A gripping narrative with strong characters.\",\n",
1061
+ " \"Insightful and beautifully told.\",\n",
1062
+ " \"An inspiring and memorable book.\",\n",
1063
+ " \"The pacing was perfect throughout.\",\n",
1064
+ " \"A standout novel in its genre.\",\n",
1065
+ " \"Full of warmth and authenticity.\",\n",
1066
+ " \"A thoroughly enjoyable read.\",\n",
1067
+ " \"Strong storytelling and vivid imagery.\",\n",
1068
+ " \"A book that truly delivers.\",\n",
1069
+ " \"Moving, heartfelt, and sincere.\",\n",
1070
+ " \"An engaging and meaningful story.\",\n",
1071
+ " \"Expertly plotted and satisfying.\",\n",
1072
+ " \"A rich and immersive experience.\",\n",
1073
+ " \"Captivating from the very first page.\",\n",
1074
+ " \"A beautifully constructed narrative.\",\n",
1075
+ " \"Powerful themes explored thoughtfully.\",\n",
1076
+ " \"A must-read for fans of great fiction.\",\n",
1077
+ " \"Charming and emotionally impactful.\",\n",
1078
+ " \"An outstanding literary work.\",\n",
1079
+ " \"Skillfully written and engaging.\",\n",
1080
+ " \"An inspiring and uplifting novel.\",\n",
1081
+ " \"A deeply satisfying conclusion.\",\n",
1082
+ " \"Simply excellent in every way.\"\n",
1083
+ " ],\n",
1084
+ " \"neutral\": [\n",
1085
+ " \"An average book overall.\",\n",
1086
+ " \"Some moments were interesting, others less so.\",\n",
1087
+ " \"It was fine, but not particularly memorable.\",\n",
1088
+ " \"A decent read with a few strong sections.\",\n",
1089
+ " \"Neither impressive nor disappointing.\",\n",
1090
+ " \"It had potential but didn’t fully deliver.\",\n",
1091
+ " \"An okay story with mixed execution.\",\n",
1092
+ " \"Some characters stood out more than others.\",\n",
1093
+ " \"The pacing felt uneven at times.\",\n",
1094
+ " \"A fairly standard plot.\",\n",
1095
+ " \"It passed the time without much impact.\",\n",
1096
+ " \"Readable but not remarkable.\",\n",
1097
+ " \"A balanced mix of good and mediocre elements.\",\n",
1098
+ " \"Not bad, but not especially engaging.\",\n",
1099
+ " \"An ordinary reading experience.\",\n",
1100
+ " \"Some parts worked better than others.\",\n",
1101
+ " \"A moderately enjoyable book.\",\n",
1102
+ " \"The concept was interesting, execution average.\",\n",
1103
+ " \"It held my attention occasionally.\",\n",
1104
+ " \"Serviceable but not standout.\",\n",
1105
+ " \"A straightforward narrative.\",\n",
1106
+ " \"Nothing particularly new or surprising.\",\n",
1107
+ " \"An acceptable but forgettable read.\",\n",
1108
+ " \"It had its moments.\",\n",
1109
+ " \"Competently written but lacking spark.\",\n",
1110
+ " \"Fairly predictable storyline.\",\n",
1111
+ " \"A mild and easy read.\",\n",
1112
+ " \"Interesting premise, average delivery.\",\n",
1113
+ " \"Reasonably entertaining.\",\n",
1114
+ " \"A mixed bag overall.\",\n",
1115
+ " \"Not as engaging as I hoped.\",\n",
1116
+ " \"Pleasant but unremarkable.\",\n",
1117
+ " \"Some emotional depth, but limited impact.\",\n",
1118
+ " \"Solid but not special.\",\n",
1119
+ " \"A standard genre entry.\",\n",
1120
+ " \"Adequate storytelling.\",\n",
1121
+ " \"Good in parts, average in others.\",\n",
1122
+ " \"An okay way to spend a few hours.\",\n",
1123
+ " \"Moderately engaging throughout.\",\n",
1124
+ " \"Nothing particularly stood out.\",\n",
1125
+ " \"Balanced strengths and weaknesses.\",\n",
1126
+ " \"Fair pacing with occasional lulls.\",\n",
1127
+ " \"A serviceable book.\",\n",
1128
+ " \"It met expectations without exceeding them.\",\n",
1129
+ " \"Simple and straightforward.\",\n",
1130
+ " \"Somewhat engaging but inconsistent.\",\n",
1131
+ " \"A neutral overall impression.\",\n",
1132
+ " \"Competent but not exciting.\",\n",
1133
+ " \"An average addition to the shelf.\",\n",
1134
+ " \"Readable but easily forgotten.\"\n",
1135
+ " ],\n",
1136
+ " \"negative\": [\n",
1137
+ " \"I struggled to stay interested throughout.\",\n",
1138
+ " \"The plot felt confusing and disjointed.\",\n",
1139
+ " \"Disappointing and underwhelming.\",\n",
1140
+ " \"The characters lacked depth.\",\n",
1141
+ " \"It failed to hold my attention.\",\n",
1142
+ " \"Poor pacing made it hard to finish.\",\n",
1143
+ " \"The story felt flat and uninspired.\",\n",
1144
+ " \"Not what I was expecting at all.\",\n",
1145
+ " \"The writing felt forced at times.\",\n",
1146
+ " \"A forgettable and dull read.\",\n",
1147
+ " \"The narrative was hard to follow.\",\n",
1148
+ " \"Unconvincing character development.\",\n",
1149
+ " \"It lacked emotional impact.\",\n",
1150
+ " \"The ending was unsatisfying.\",\n",
1151
+ " \"Repetitive and predictable.\",\n",
1152
+ " \"I couldn’t connect with the story.\",\n",
1153
+ " \"Overly complicated without payoff.\",\n",
1154
+ " \"The dialogue felt unnatural.\",\n",
1155
+ " \"A disappointing experience overall.\",\n",
1156
+ " \"The premise had promise but fell apart.\",\n",
1157
+ " \"It felt rushed and incomplete.\",\n",
1158
+ " \"Hard to get through.\",\n",
1159
+ " \"Weak storytelling throughout.\",\n",
1160
+ " \"The plot holes were distracting.\",\n",
1161
+ " \"I expected much more from this book.\",\n",
1162
+ " \"The pacing dragged considerably.\",\n",
1163
+ " \"The characters were forgettable.\",\n",
1164
+ " \"It didn’t live up to the hype.\",\n",
1165
+ " \"A frustrating read.\",\n",
1166
+ " \"Lacked originality and depth.\",\n",
1167
+ " \"The themes were poorly explored.\",\n",
1168
+ " \"It just didn’t work for me.\",\n",
1169
+ " \"A bland and uninspired effort.\",\n",
1170
+ " \"The story felt incoherent.\",\n",
1171
+ " \"I found it quite boring.\",\n",
1172
+ " \"Too predictable to be engaging.\",\n",
1173
+ " \"The emotional moments felt forced.\",\n",
1174
+ " \"Underdeveloped and shallow.\",\n",
1175
+ " \"It failed to leave any impression.\",\n",
1176
+ " \"Difficult to recommend.\",\n",
1177
+ " \"The structure felt messy.\",\n",
1178
+ " \"An underwhelming narrative.\",\n",
1179
+ " \"It lacked focus and clarity.\",\n",
1180
+ " \"The execution was disappointing.\",\n",
1181
+ " \"Unengaging from start to finish.\",\n",
1182
+ " \"Not worth the time invested.\",\n",
1183
+ " \"The writing style didn’t appeal to me.\",\n",
1184
+ " \"A weak attempt at storytelling.\",\n",
1185
+ " \"Ultimately forgettable.\",\n",
1186
+ " \"A missed opportunity.\"\n",
1187
+ " ]\n",
1188
+ "}\n"
1189
+ ]
1190
+ },
1191
+ {
1192
+ "cell_type": "markdown",
1193
+ "metadata": {
1194
+ "id": "fQhfVaDmuULT"
1195
+ },
1196
+ "source": [
1197
+ "### *b. Generate 10 reviews per book using random sampling from the corresponding 50*"
1198
+ ]
1199
+ },
1200
+ {
1201
+ "cell_type": "code",
1202
+ "execution_count": 22,
1203
+ "metadata": {
1204
+ "id": "l2SRc3PjuTGM"
1205
+ },
1206
+ "outputs": [],
1207
+ "source": [
1208
+ "review_rows = []\n",
1209
+ "for _, row in df_books.iterrows():\n",
1210
+ " title = row['title']\n",
1211
+ " sentiment_label = row['sentiment_label']\n",
1212
+ " review_pool = synthetic_reviews_by_sentiment[sentiment_label]\n",
1213
+ " sampled_reviews = random.sample(review_pool, 10)\n",
1214
+ " for review_text in sampled_reviews:\n",
1215
+ " review_rows.append({\n",
1216
+ " \"title\": title,\n",
1217
+ " \"sentiment_label\": sentiment_label,\n",
1218
+ " \"review_text\": review_text,\n",
1219
+ " \"rating\": row['rating'],\n",
1220
+ " \"popularity_score\": row['popularity_score']\n",
1221
+ " })"
1222
+ ]
1223
+ },
1224
+ {
1225
+ "cell_type": "markdown",
1226
+ "metadata": {
1227
+ "id": "bmJMXF-Bukdm"
1228
+ },
1229
+ "source": [
1230
+ "### *c. Create the final dataframe df_reviews & save it as synthetic_book_reviews.csv*"
1231
+ ]
1232
+ },
1233
+ {
1234
+ "cell_type": "code",
1235
+ "execution_count": 23,
1236
+ "metadata": {
1237
+ "id": "ZUKUqZsuumsp"
1238
+ },
1239
+ "outputs": [],
1240
+ "source": [
1241
+ "df_reviews = pd.DataFrame(review_rows)\n",
1242
+ "df_reviews.to_csv(\"synthetic_book_reviews.csv\", index=False)"
1243
+ ]
1244
+ },
1245
+ {
1246
+ "cell_type": "markdown",
1247
+ "source": [
1248
+ "### *c. inputs for R*"
1249
+ ],
1250
+ "metadata": {
1251
+ "id": "_602pYUS3gY5"
1252
+ }
1253
+ },
1254
+ {
1255
+ "cell_type": "code",
1256
+ "execution_count": 24,
1257
+ "metadata": {
1258
+ "colab": {
1259
+ "base_uri": "https://localhost:8080/"
1260
+ },
1261
+ "id": "3946e521",
1262
+ "outputId": "40d48899-97bd-40ec-ffc7-f460900f8a5a"
1263
+ },
1264
+ "outputs": [
1265
+ {
1266
+ "output_type": "stream",
1267
+ "name": "stdout",
1268
+ "text": [
1269
+ "✅ Wrote synthetic_title_level_features.csv\n",
1270
+ "✅ Wrote synthetic_monthly_revenue_series.csv\n"
1271
+ ]
1272
+ }
1273
+ ],
1274
+ "source": [
1275
+ "import numpy as np\n",
1276
+ "\n",
1277
+ "def _safe_num(s):\n",
1278
+ " return pd.to_numeric(\n",
1279
+ " pd.Series(s).astype(str).str.replace(r\"[^0-9.]\", \"\", regex=True),\n",
1280
+ " errors=\"coerce\"\n",
1281
+ " )\n",
1282
+ "\n",
1283
+ "# --- Clean book metadata (price/rating) ---\n",
1284
+ "df_books_r = df_books.copy()\n",
1285
+ "if \"price\" in df_books_r.columns:\n",
1286
+ " df_books_r[\"price\"] = _safe_num(df_books_r[\"price\"])\n",
1287
+ "if \"rating\" in df_books_r.columns:\n",
1288
+ " df_books_r[\"rating\"] = _safe_num(df_books_r[\"rating\"])\n",
1289
+ "\n",
1290
+ "df_books_r[\"title\"] = df_books_r[\"title\"].astype(str).str.strip()\n",
1291
+ "\n",
1292
+ "# --- Clean sales ---\n",
1293
+ "df_sales_r = df_sales.copy()\n",
1294
+ "df_sales_r[\"title\"] = df_sales_r[\"title\"].astype(str).str.strip()\n",
1295
+ "df_sales_r[\"month\"] = pd.to_datetime(df_sales_r[\"month\"], errors=\"coerce\")\n",
1296
+ "df_sales_r[\"units_sold\"] = _safe_num(df_sales_r[\"units_sold\"])\n",
1297
+ "\n",
1298
+ "# --- Clean reviews ---\n",
1299
+ "df_reviews_r = df_reviews.copy()\n",
1300
+ "df_reviews_r[\"title\"] = df_reviews_r[\"title\"].astype(str).str.strip()\n",
1301
+ "df_reviews_r[\"sentiment_label\"] = df_reviews_r[\"sentiment_label\"].astype(str).str.lower().str.strip()\n",
1302
+ "if \"rating\" in df_reviews_r.columns:\n",
1303
+ " df_reviews_r[\"rating\"] = _safe_num(df_reviews_r[\"rating\"])\n",
1304
+ "if \"popularity_score\" in df_reviews_r.columns:\n",
1305
+ " df_reviews_r[\"popularity_score\"] = _safe_num(df_reviews_r[\"popularity_score\"])\n",
1306
+ "\n",
1307
+ "# --- Sentiment shares per title (from reviews) ---\n",
1308
+ "sent_counts = (\n",
1309
+ " df_reviews_r.groupby([\"title\", \"sentiment_label\"])\n",
1310
+ " .size()\n",
1311
+ " .unstack(fill_value=0)\n",
1312
+ ")\n",
1313
+ "for lab in [\"positive\", \"neutral\", \"negative\"]:\n",
1314
+ " if lab not in sent_counts.columns:\n",
1315
+ " sent_counts[lab] = 0\n",
1316
+ "\n",
1317
+ "sent_counts[\"total_reviews\"] = sent_counts[[\"positive\", \"neutral\", \"negative\"]].sum(axis=1)\n",
1318
+ "den = sent_counts[\"total_reviews\"].replace(0, np.nan)\n",
1319
+ "sent_counts[\"share_positive\"] = sent_counts[\"positive\"] / den\n",
1320
+ "sent_counts[\"share_neutral\"] = sent_counts[\"neutral\"] / den\n",
1321
+ "sent_counts[\"share_negative\"] = sent_counts[\"negative\"] / den\n",
1322
+ "sent_counts = sent_counts.reset_index()\n",
1323
+ "\n",
1324
+ "# --- Sales aggregation per title ---\n",
1325
+ "sales_by_title = (\n",
1326
+ " df_sales_r.dropna(subset=[\"title\"])\n",
1327
+ " .groupby(\"title\", as_index=False)\n",
1328
+ " .agg(\n",
1329
+ " months_observed=(\"month\", \"nunique\"),\n",
1330
+ " avg_units_sold=(\"units_sold\", \"mean\"),\n",
1331
+ " total_units_sold=(\"units_sold\", \"sum\"),\n",
1332
+ " )\n",
1333
+ ")\n",
1334
+ "\n",
1335
+ "# --- Title-level features (join sales + books + sentiment) ---\n",
1336
+ "df_title = (\n",
1337
+ " sales_by_title\n",
1338
+ " .merge(df_books_r[[\"title\", \"price\", \"rating\"]], on=\"title\", how=\"left\")\n",
1339
+ " .merge(sent_counts[[\"title\", \"share_positive\", \"share_neutral\", \"share_negative\", \"total_reviews\"]],\n",
1340
+ " on=\"title\", how=\"left\")\n",
1341
+ ")\n",
1342
+ "\n",
1343
+ "df_title[\"avg_revenue\"] = df_title[\"avg_units_sold\"] * df_title[\"price\"]\n",
1344
+ "df_title[\"total_revenue\"] = df_title[\"total_units_sold\"] * df_title[\"price\"]\n",
1345
+ "\n",
1346
+ "df_title.to_csv(\"synthetic_title_level_features.csv\", index=False)\n",
1347
+ "print(\"✅ Wrote synthetic_title_level_features.csv\")\n",
1348
+ "\n",
1349
+ "# --- Monthly revenue series (proxy: units_sold * price) ---\n",
1350
+ "monthly_rev = (\n",
1351
+ " df_sales_r.merge(df_books_r[[\"title\", \"price\"]], on=\"title\", how=\"left\")\n",
1352
+ ")\n",
1353
+ "monthly_rev[\"revenue\"] = monthly_rev[\"units_sold\"] * monthly_rev[\"price\"]\n",
1354
+ "\n",
1355
+ "df_monthly = (\n",
1356
+ " monthly_rev.dropna(subset=[\"month\"])\n",
1357
+ " .groupby(\"month\", as_index=False)[\"revenue\"]\n",
1358
+ " .sum()\n",
1359
+ " .rename(columns={\"revenue\": \"total_revenue\"})\n",
1360
+ " .sort_values(\"month\")\n",
1361
+ ")\n",
1362
+ "# if revenue is all NA (e.g., missing price), fallback to units_sold as a teaching proxy\n",
1363
+ "if df_monthly[\"total_revenue\"].notna().sum() == 0:\n",
1364
+ " df_monthly = (\n",
1365
+ " df_sales_r.dropna(subset=[\"month\"])\n",
1366
+ " .groupby(\"month\", as_index=False)[\"units_sold\"]\n",
1367
+ " .sum()\n",
1368
+ " .rename(columns={\"units_sold\": \"total_revenue\"})\n",
1369
+ " .sort_values(\"month\")\n",
1370
+ " )\n",
1371
+ "\n",
1372
+ "df_monthly[\"month\"] = pd.to_datetime(df_monthly[\"month\"], errors=\"coerce\").dt.strftime(\"%Y-%m-%d\")\n",
1373
+ "df_monthly.to_csv(\"synthetic_monthly_revenue_series.csv\", index=False)\n",
1374
+ "print(\"✅ Wrote synthetic_monthly_revenue_series.csv\")\n"
1375
+ ]
1376
+ },
1377
+ {
1378
+ "cell_type": "markdown",
1379
+ "metadata": {
1380
+ "id": "RYvGyVfXuo54"
1381
+ },
1382
+ "source": [
1383
+ "### *d. ✋🏻🛑⛔️ View the first few lines*"
1384
+ ]
1385
+ },
1386
+ {
1387
+ "cell_type": "code",
1388
+ "execution_count": 27,
1389
+ "metadata": {
1390
+ "colab": {
1391
+ "base_uri": "https://localhost:8080/"
1392
+ },
1393
+ "id": "xfE8NMqOurKo",
1394
+ "outputId": "c617658b-9daa-4c43-909b-165a34572587"
1395
+ },
1396
+ "outputs": [
1397
+ {
1398
+ "output_type": "stream",
1399
+ "name": "stdout",
1400
+ "text": [
1401
+ " month total_revenue\n",
1402
+ "0 2024-08-01 5631956.77\n",
1403
+ "1 2024-09-01 5856653.68\n",
1404
+ "2 2024-10-01 6006876.26\n",
1405
+ "3 2024-11-01 6061519.85\n",
1406
+ "4 2024-12-01 6014276.79\n",
1407
+ " title months_observed \\\n",
1408
+ "0 \"Most Blessed of the Patriarchs\": Thomas Jeffe... 18 \n",
1409
+ "1 #GIRLBOSS 18 \n",
1410
+ "2 #HigherSelfie: Wake Up Your Life. Free Your So... 18 \n",
1411
+ "3 'Salem's Lot 18 \n",
1412
+ "4 (Un)Qualified: How God Uses Broken People to D... 18 \n",
1413
+ "\n",
1414
+ " avg_units_sold total_units_sold price rating share_positive \\\n",
1415
+ "0 285.555556 5140 44.48 NaN 1.0 \n",
1416
+ "1 47.944444 863 50.96 NaN 0.0 \n",
1417
+ "2 226.777778 4082 23.11 NaN 1.0 \n",
1418
+ "3 246.055556 4429 49.56 NaN 1.0 \n",
1419
+ "4 294.444444 5300 54.00 NaN 1.0 \n",
1420
+ "\n",
1421
+ " share_neutral share_negative total_reviews avg_revenue total_revenue \n",
1422
+ "0 0.0 0.0 10 12701.511111 228627.20 \n",
1423
+ "1 0.0 1.0 10 2443.248889 43978.48 \n",
1424
+ "2 0.0 0.0 10 5240.834444 94335.02 \n",
1425
+ "3 0.0 0.0 10 12194.513333 219501.24 \n",
1426
+ "4 0.0 0.0 10 15900.000000 286200.00 \n",
1427
+ " title month units_sold sentiment_label\n",
1428
+ "0 A Light in the Attic 2024-08-01 100 neutral\n",
1429
+ "1 A Light in the Attic 2024-09-01 109 neutral\n",
1430
+ "2 A Light in the Attic 2024-10-01 102 neutral\n",
1431
+ "3 A Light in the Attic 2024-11-01 107 neutral\n",
1432
+ "4 A Light in the Attic 2024-12-01 108 neutral\n"
1433
+ ]
1434
+ }
1435
+ ],
1436
+ "source": [
1437
+ "print(df_monthly.head())\n",
1438
+ "print(df_title.head())\n",
1439
+ "print(df_sales_r.head())"
1440
+ ]
1441
+ }
1442
+ ],
1443
+ "metadata": {
1444
+ "colab": {
1445
+ "collapsed_sections": [
1446
+ "jpASMyIQMaAq"
1447
+ ],
1448
+ "provenance": []
1449
+ },
1450
+ "kernelspec": {
1451
+ "display_name": "Python 3",
1452
+ "name": "python3"
1453
+ },
1454
+ "language_info": {
1455
+ "name": "python"
1456
+ }
1457
+ },
1458
+ "nbformat": 4,
1459
+ "nbformat_minor": 0
1460
+ }
Python Analysis.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
+ }