├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── big-data
└── streaming
│ ├── anomaly_detection.ipynb
│ ├── nlp.ipynb
│ └── online_stats.ipynb
├── data-mining
├── clustering
│ ├── affinity-propagation.ipynb
│ ├── hierarchical.ipynb
│ ├── k-means.ipynb
│ └── lab.ipynb
├── data-viz
│ ├── altair.ipynb
│ ├── lab.ipynb
│ └── table.html
├── feature-engineering
│ ├── basketball.ipynb
│ └── taxis.ipynb
├── finding-structure
│ ├── ca.ipynb
│ ├── lab.ipynb
│ ├── pca-anomaly-detection.ipynb
│ ├── pca-data-analysis.ipynb
│ ├── pca-faces.ipynb
│ └── skyline.ipynb
├── supervised-learning
│ └── lightgbm.ipynb
└── text-processing
│ ├── record-linkage.ipynb
│ ├── regex.ipynb
│ ├── shoes.ipynb
│ ├── spelling-correction.ipynb
│ └── tfidf.ipynb
├── data
├── .gitkeep
├── agribalyse-31-synthese.csv
├── bias-in-bios.zip
├── mens-machine-learning-competition-2019.zip
├── recipe_embeddings.csv
├── tents.csv
└── wowah.zip
├── deep-learning
├── backprop.ipynb
├── brad-pitt.jpg
├── cat.jpg
├── charseq.jpeg
├── complexity.png
├── cross-val.png
├── duck_rabbit.jpg
├── intro.ipynb
├── learning-rate.png
├── mini-batch.png
├── momentum.gif
├── nlp.ipynb
├── noisette-loo.jpg
├── skip-gram.png
├── stuff.ipynb
└── word2vec.png
├── house-prices-regression.ipynb
├── introduction-to-python
├── Introduction to Python.ipynb
├── my_package
│ ├── __init__.py
│ └── my_sequences.py
└── my_sequences.py
├── online-learning
└── river-workshop.ipynb
├── optimization
├── part-1.ipynb
├── part-2.ipynb
└── part-3.ipynb
└── project-assignments.ipynb
/.gitattributes:
--------------------------------------------------------------------------------
1 | data/wowah.zip filter=lfs diff=lfs merge=lfs -text
2 | data/mens-machine-learning-competition-2019.zip filter=lfs diff=lfs merge=lfs -text
3 | data/bias-in-bios.zip filter=lfs diff=lfs merge=lfs -text
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .ipynb_checkpoints/
2 | *.csv
3 | !data/*csv
4 | *.pyc
5 | introduction-to-python/*.txt
6 | introduction-to-python/*.json
7 | *.h5
8 | *.pkl
9 | .DS_Store
10 | *.txt
11 | *.json*
12 | *.db
13 | *.wal
14 | .env
15 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Attribution-NonCommercial-ShareAlike 4.0 International
2 |
3 | =======================================================================
4 |
5 | Creative Commons Corporation ("Creative Commons") is not a law firm and
6 | does not provide legal services or legal advice. Distribution of
7 | Creative Commons public licenses does not create a lawyer-client or
8 | other relationship. Creative Commons makes its licenses and related
9 | information available on an "as-is" basis. Creative Commons gives no
10 | warranties regarding its licenses, any material licensed under their
11 | terms and conditions, or any related information. Creative Commons
12 | disclaims all liability for damages resulting from their use to the
13 | fullest extent possible.
14 |
15 | Using Creative Commons Public Licenses
16 |
17 | Creative Commons public licenses provide a standard set of terms and
18 | conditions that creators and other rights holders may use to share
19 | original works of authorship and other material subject to copyright
20 | and certain other rights specified in the public license below. The
21 | following considerations are for informational purposes only, are not
22 | exhaustive, and do not form part of our licenses.
23 |
24 | Considerations for licensors: Our public licenses are
25 | intended for use by those authorized to give the public
26 | permission to use material in ways otherwise restricted by
27 | copyright and certain other rights. Our licenses are
28 | irrevocable. Licensors should read and understand the terms
29 | and conditions of the license they choose before applying it.
30 | Licensors should also secure all rights necessary before
31 | applying our licenses so that the public can reuse the
32 | material as expected. Licensors should clearly mark any
33 | material not subject to the license. This includes other CC-
34 | licensed material, or material used under an exception or
35 | limitation to copyright. More considerations for licensors:
36 | wiki.creativecommons.org/Considerations_for_licensors
37 |
38 | Considerations for the public: By using one of our public
39 | licenses, a licensor grants the public permission to use the
40 | licensed material under specified terms and conditions. If
41 | the licensor's permission is not necessary for any reason--for
42 | example, because of any applicable exception or limitation to
43 | copyright--then that use is not regulated by the license. Our
44 | licenses grant only permissions under copyright and certain
45 | other rights that a licensor has authority to grant. Use of
46 | the licensed material may still be restricted for other
47 | reasons, including because others have copyright or other
48 | rights in the material. A licensor may make special requests,
49 | such as asking that all changes be marked or described.
50 | Although not required by our licenses, you are encouraged to
51 | respect those requests where reasonable. More considerations
52 | for the public:
53 | wiki.creativecommons.org/Considerations_for_licensees
54 |
55 | =======================================================================
56 |
57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
58 | Public License
59 |
60 | By exercising the Licensed Rights (defined below), You accept and agree
61 | to be bound by the terms and conditions of this Creative Commons
62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License
63 | ("Public License"). To the extent this Public License may be
64 | interpreted as a contract, You are granted the Licensed Rights in
65 | consideration of Your acceptance of these terms and conditions, and the
66 | Licensor grants You such rights in consideration of benefits the
67 | Licensor receives from making the Licensed Material available under
68 | these terms and conditions.
69 |
70 |
71 | Section 1 -- Definitions.
72 |
73 | a. Adapted Material means material subject to Copyright and Similar
74 | Rights that is derived from or based upon the Licensed Material
75 | and in which the Licensed Material is translated, altered,
76 | arranged, transformed, or otherwise modified in a manner requiring
77 | permission under the Copyright and Similar Rights held by the
78 | Licensor. For purposes of this Public License, where the Licensed
79 | Material is a musical work, performance, or sound recording,
80 | Adapted Material is always produced where the Licensed Material is
81 | synched in timed relation with a moving image.
82 |
83 | b. Adapter's License means the license You apply to Your Copyright
84 | and Similar Rights in Your contributions to Adapted Material in
85 | accordance with the terms and conditions of this Public License.
86 |
87 | c. BY-NC-SA Compatible License means a license listed at
88 | creativecommons.org/compatiblelicenses, approved by Creative
89 | Commons as essentially the equivalent of this Public License.
90 |
91 | d. Copyright and Similar Rights means copyright and/or similar rights
92 | closely related to copyright including, without limitation,
93 | performance, broadcast, sound recording, and Sui Generis Database
94 | Rights, without regard to how the rights are labeled or
95 | categorized. For purposes of this Public License, the rights
96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar
97 | Rights.
98 |
99 | e. Effective Technological Measures means those measures that, in the
100 | absence of proper authority, may not be circumvented under laws
101 | fulfilling obligations under Article 11 of the WIPO Copyright
102 | Treaty adopted on December 20, 1996, and/or similar international
103 | agreements.
104 |
105 | f. Exceptions and Limitations means fair use, fair dealing, and/or
106 | any other exception or limitation to Copyright and Similar Rights
107 | that applies to Your use of the Licensed Material.
108 |
109 | g. License Elements means the license attributes listed in the name
110 | of a Creative Commons Public License. The License Elements of this
111 | Public License are Attribution, NonCommercial, and ShareAlike.
112 |
113 | h. Licensed Material means the artistic or literary work, database,
114 | or other material to which the Licensor applied this Public
115 | License.
116 |
117 | i. Licensed Rights means the rights granted to You subject to the
118 | terms and conditions of this Public License, which are limited to
119 | all Copyright and Similar Rights that apply to Your use of the
120 | Licensed Material and that the Licensor has authority to license.
121 |
122 | j. Licensor means the individual(s) or entity(ies) granting rights
123 | under this Public License.
124 |
125 | k. NonCommercial means not primarily intended for or directed towards
126 | commercial advantage or monetary compensation. For purposes of
127 | this Public License, the exchange of the Licensed Material for
128 | other material subject to Copyright and Similar Rights by digital
129 | file-sharing or similar means is NonCommercial provided there is
130 | no payment of monetary compensation in connection with the
131 | exchange.
132 |
133 | l. Share means to provide material to the public by any means or
134 | process that requires permission under the Licensed Rights, such
135 | as reproduction, public display, public performance, distribution,
136 | dissemination, communication, or importation, and to make material
137 | available to the public including in ways that members of the
138 | public may access the material from a place and at a time
139 | individually chosen by them.
140 |
141 | m. Sui Generis Database Rights means rights other than copyright
142 | resulting from Directive 96/9/EC of the European Parliament and of
143 | the Council of 11 March 1996 on the legal protection of databases,
144 | as amended and/or succeeded, as well as other essentially
145 | equivalent rights anywhere in the world.
146 |
147 | n. You means the individual or entity exercising the Licensed Rights
148 | under this Public License. Your has a corresponding meaning.
149 |
150 |
151 | Section 2 -- Scope.
152 |
153 | a. License grant.
154 |
155 | 1. Subject to the terms and conditions of this Public License,
156 | the Licensor hereby grants You a worldwide, royalty-free,
157 | non-sublicensable, non-exclusive, irrevocable license to
158 | exercise the Licensed Rights in the Licensed Material to:
159 |
160 | a. reproduce and Share the Licensed Material, in whole or
161 | in part, for NonCommercial purposes only; and
162 |
163 | b. produce, reproduce, and Share Adapted Material for
164 | NonCommercial purposes only.
165 |
166 | 2. Exceptions and Limitations. For the avoidance of doubt, where
167 | Exceptions and Limitations apply to Your use, this Public
168 | License does not apply, and You do not need to comply with
169 | its terms and conditions.
170 |
171 | 3. Term. The term of this Public License is specified in Section
172 | 6(a).
173 |
174 | 4. Media and formats; technical modifications allowed. The
175 | Licensor authorizes You to exercise the Licensed Rights in
176 | all media and formats whether now known or hereafter created,
177 | and to make technical modifications necessary to do so. The
178 | Licensor waives and/or agrees not to assert any right or
179 | authority to forbid You from making technical modifications
180 | necessary to exercise the Licensed Rights, including
181 | technical modifications necessary to circumvent Effective
182 | Technological Measures. For purposes of this Public License,
183 | simply making modifications authorized by this Section 2(a)
184 | (4) never produces Adapted Material.
185 |
186 | 5. Downstream recipients.
187 |
188 | a. Offer from the Licensor -- Licensed Material. Every
189 | recipient of the Licensed Material automatically
190 | receives an offer from the Licensor to exercise the
191 | Licensed Rights under the terms and conditions of this
192 | Public License.
193 |
194 | b. Additional offer from the Licensor -- Adapted Material.
195 | Every recipient of Adapted Material from You
196 | automatically receives an offer from the Licensor to
197 | exercise the Licensed Rights in the Adapted Material
198 | under the conditions of the Adapter's License You apply.
199 |
200 | c. No downstream restrictions. You may not offer or impose
201 | any additional or different terms or conditions on, or
202 | apply any Effective Technological Measures to, the
203 | Licensed Material if doing so restricts exercise of the
204 | Licensed Rights by any recipient of the Licensed
205 | Material.
206 |
207 | 6. No endorsement. Nothing in this Public License constitutes or
208 | may be construed as permission to assert or imply that You
209 | are, or that Your use of the Licensed Material is, connected
210 | with, or sponsored, endorsed, or granted official status by,
211 | the Licensor or others designated to receive attribution as
212 | provided in Section 3(a)(1)(A)(i).
213 |
214 | b. Other rights.
215 |
216 | 1. Moral rights, such as the right of integrity, are not
217 | licensed under this Public License, nor are publicity,
218 | privacy, and/or other similar personality rights; however, to
219 | the extent possible, the Licensor waives and/or agrees not to
220 | assert any such rights held by the Licensor to the limited
221 | extent necessary to allow You to exercise the Licensed
222 | Rights, but not otherwise.
223 |
224 | 2. Patent and trademark rights are not licensed under this
225 | Public License.
226 |
227 | 3. To the extent possible, the Licensor waives any right to
228 | collect royalties from You for the exercise of the Licensed
229 | Rights, whether directly or through a collecting society
230 | under any voluntary or waivable statutory or compulsory
231 | licensing scheme. In all other cases the Licensor expressly
232 | reserves any right to collect such royalties, including when
233 | the Licensed Material is used other than for NonCommercial
234 | purposes.
235 |
236 |
237 | Section 3 -- License Conditions.
238 |
239 | Your exercise of the Licensed Rights is expressly made subject to the
240 | following conditions.
241 |
242 | a. Attribution.
243 |
244 | 1. If You Share the Licensed Material (including in modified
245 | form), You must:
246 |
247 | a. retain the following if it is supplied by the Licensor
248 | with the Licensed Material:
249 |
250 | i. identification of the creator(s) of the Licensed
251 | Material and any others designated to receive
252 | attribution, in any reasonable manner requested by
253 | the Licensor (including by pseudonym if
254 | designated);
255 |
256 | ii. a copyright notice;
257 |
258 | iii. a notice that refers to this Public License;
259 |
260 | iv. a notice that refers to the disclaimer of
261 | warranties;
262 |
263 | v. a URI or hyperlink to the Licensed Material to the
264 | extent reasonably practicable;
265 |
266 | b. indicate if You modified the Licensed Material and
267 | retain an indication of any previous modifications; and
268 |
269 | c. indicate the Licensed Material is licensed under this
270 | Public License, and include the text of, or the URI or
271 | hyperlink to, this Public License.
272 |
273 | 2. You may satisfy the conditions in Section 3(a)(1) in any
274 | reasonable manner based on the medium, means, and context in
275 | which You Share the Licensed Material. For example, it may be
276 | reasonable to satisfy the conditions by providing a URI or
277 | hyperlink to a resource that includes the required
278 | information.
279 | 3. If requested by the Licensor, You must remove any of the
280 | information required by Section 3(a)(1)(A) to the extent
281 | reasonably practicable.
282 |
283 | b. ShareAlike.
284 |
285 | In addition to the conditions in Section 3(a), if You Share
286 | Adapted Material You produce, the following conditions also apply.
287 |
288 | 1. The Adapter's License You apply must be a Creative Commons
289 | license with the same License Elements, this version or
290 | later, or a BY-NC-SA Compatible License.
291 |
292 | 2. You must include the text of, or the URI or hyperlink to, the
293 | Adapter's License You apply. You may satisfy this condition
294 | in any reasonable manner based on the medium, means, and
295 | context in which You Share Adapted Material.
296 |
297 | 3. You may not offer or impose any additional or different terms
298 | or conditions on, or apply any Effective Technological
299 | Measures to, Adapted Material that restrict exercise of the
300 | rights granted under the Adapter's License You apply.
301 |
302 |
303 | Section 4 -- Sui Generis Database Rights.
304 |
305 | Where the Licensed Rights include Sui Generis Database Rights that
306 | apply to Your use of the Licensed Material:
307 |
308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right
309 | to extract, reuse, reproduce, and Share all or a substantial
310 | portion of the contents of the database for NonCommercial purposes
311 | only;
312 |
313 | b. if You include all or a substantial portion of the database
314 | contents in a database in which You have Sui Generis Database
315 | Rights, then the database in which You have Sui Generis Database
316 | Rights (but not its individual contents) is Adapted Material,
317 | including for purposes of Section 3(b); and
318 |
319 | c. You must comply with the conditions in Section 3(a) if You Share
320 | all or a substantial portion of the contents of the database.
321 |
322 | For the avoidance of doubt, this Section 4 supplements and does not
323 | replace Your obligations under this Public License where the Licensed
324 | Rights include other Copyright and Similar Rights.
325 |
326 |
327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability.
328 |
329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
339 |
340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
349 |
350 | c. The disclaimer of warranties and limitation of liability provided
351 | above shall be interpreted in a manner that, to the extent
352 | possible, most closely approximates an absolute disclaimer and
353 | waiver of all liability.
354 |
355 |
356 | Section 6 -- Term and Termination.
357 |
358 | a. This Public License applies for the term of the Copyright and
359 | Similar Rights licensed here. However, if You fail to comply with
360 | this Public License, then Your rights under this Public License
361 | terminate automatically.
362 |
363 | b. Where Your right to use the Licensed Material has terminated under
364 | Section 6(a), it reinstates:
365 |
366 | 1. automatically as of the date the violation is cured, provided
367 | it is cured within 30 days of Your discovery of the
368 | violation; or
369 |
370 | 2. upon express reinstatement by the Licensor.
371 |
372 | For the avoidance of doubt, this Section 6(b) does not affect any
373 | right the Licensor may have to seek remedies for Your violations
374 | of this Public License.
375 |
376 | c. For the avoidance of doubt, the Licensor may also offer the
377 | Licensed Material under separate terms or conditions or stop
378 | distributing the Licensed Material at any time; however, doing so
379 | will not terminate this Public License.
380 |
381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
382 | License.
383 |
384 |
385 | Section 7 -- Other Terms and Conditions.
386 |
387 | a. The Licensor shall not be bound by any additional or different
388 | terms or conditions communicated by You unless expressly agreed.
389 |
390 | b. Any arrangements, understandings, or agreements regarding the
391 | Licensed Material not stated herein are separate from and
392 | independent of the terms and conditions of this Public License.
393 |
394 |
395 | Section 8 -- Interpretation.
396 |
397 | a. For the avoidance of doubt, this Public License does not, and
398 | shall not be interpreted to, reduce, limit, restrict, or impose
399 | conditions on any use of the Licensed Material that could lawfully
400 | be made without permission under this Public License.
401 |
402 | b. To the extent possible, if any provision of this Public License is
403 | deemed unenforceable, it shall be automatically reformed to the
404 | minimum extent necessary to make it enforceable. If the provision
405 | cannot be reformed, it shall be severed from this Public License
406 | without affecting the enforceability of the remaining terms and
407 | conditions.
408 |
409 | c. No term or condition of this Public License will be waived and no
410 | failure to comply consented to unless expressly agreed to by the
411 | Licensor.
412 |
413 | d. Nothing in this Public License constitutes or may be interpreted
414 | as a limitation upon, or waiver of, any privileges and immunities
415 | that apply to the Licensor or You, including from the legal
416 | processes of any jurisdiction or authority.
417 |
418 | =======================================================================
419 |
420 | Creative Commons is not a party to its public
421 | licenses. Notwithstanding, Creative Commons may elect to apply one of
422 | its public licenses to material it publishes and in those instances
423 | will be considered the “Licensor.” The text of the Creative Commons
424 | public licenses is dedicated to the public domain under the CC0 Public
425 | Domain Dedication. Except for the limited purpose of indicating that
426 | material is shared under a Creative Commons public license or as
427 | otherwise permitted by the Creative Commons policies published at
428 | creativecommons.org/policies, Creative Commons does not authorize the
429 | use of the trademark "Creative Commons" or any other trademark or logo
430 | of Creative Commons without its prior written consent including,
431 | without limitation, in connection with any unauthorized modifications
432 | to any of its public licenses or any other arrangements,
433 | understandings, or agreements concerning use of licensed material. For
434 | the avoidance of doubt, this paragraph does not form part of the
435 | public licenses.
436 |
437 | Creative Commons may be contacted at creativecommons.org.
438 |
439 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
2 |
--------------------------------------------------------------------------------
/big-data/streaming/anomaly_detection.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "attachments": {},
5 | "cell_type": "markdown",
6 | "metadata": {},
7 | "source": [
8 | "# Streaming anomaly detection"
9 | ]
10 | },
11 | {
12 | "attachments": {},
13 | "cell_type": "markdown",
14 | "metadata": {},
15 | "source": [
16 | "Anomaly detection is a very common ML task. Here we will consider streaming tabular data.\n",
17 | "\n",
18 | "## Streaming a dataset\n",
19 | "\n",
20 | "As an example, we'll use a credit card transactions dataset."
21 | ]
22 | },
23 | {
24 | "cell_type": "code",
25 | "execution_count": 1,
26 | "metadata": {},
27 | "outputs": [
28 | {
29 | "data": {
30 | "text/plain": [
31 | "Credit card frauds.\n",
32 | "\n",
33 | "The datasets contains transactions made by credit cards in September 2013 by european\n",
34 | "cardholders. This dataset presents transactions that occurred in two days, where we have 492\n",
35 | "frauds out of 284,807 transactions. The dataset is highly unbalanced, the positive class\n",
36 | "(frauds) account for 0.172% of all transactions.\n",
37 | "\n",
38 | "It contains only numerical input variables which are the result of a PCA transformation.\n",
39 | "Unfortunately, due to confidentiality issues, we cannot provide the original features and more\n",
40 | "background information about the data. Features V1, V2, ... V28 are the principal components\n",
41 | "obtained with PCA, the only features which have not been transformed with PCA are 'Time' and\n",
42 | "'Amount'. Feature 'Time' contains the seconds elapsed between each transaction and the first\n",
43 | "transaction in the dataset. The feature 'Amount' is the transaction Amount, this feature can be\n",
44 | "used for example-dependant cost-senstive learning. Feature 'Class' is the response variable and\n",
45 | "it takes value 1 in case of fraud and 0 otherwise.\n",
46 | "\n",
47 | " Name CreditCard \n",
48 | " Task Binary classification \n",
49 | " Samples 284,807 \n",
50 | " Features 30 \n",
51 | " Sparse False \n",
52 | " Path /Users/max/river_data/CreditCard/creditcard.csv \n",
53 | " URL https://maxhalford.github.io/files/datasets/creditcardfraud.zip\n",
54 | " Size 143.84 MB \n",
55 | "Downloaded True "
56 | ]
57 | },
58 | "execution_count": 1,
59 | "metadata": {},
60 | "output_type": "execute_result"
61 | }
62 | ],
63 | "source": [
64 | "from river import datasets\n",
65 | "\n",
66 | "dataset = datasets.CreditCard()\n",
67 | "dataset"
68 | ]
69 | },
70 | {
71 | "attachments": {},
72 | "cell_type": "markdown",
73 | "metadata": {},
74 | "source": [
75 | "**Question 🤔: in production, what would be the output of an anomaly detector on this dataset?**\n",
76 | "\n",
77 | "**Question 🤔: how would humans and the model interact with each other?**\n",
78 | "\n",
79 | "**Question 🤔: how could you exploit human feedback?**"
80 | ]
81 | },
82 | {
83 | "cell_type": "code",
84 | "execution_count": 14,
85 | "metadata": {},
86 | "outputs": [
87 | {
88 | "data": {
89 | "text/plain": [
90 | "river.datasets.credit_card.CreditCard"
91 | ]
92 | },
93 | "execution_count": 14,
94 | "metadata": {},
95 | "output_type": "execute_result"
96 | }
97 | ],
98 | "source": [
99 | "type(dataset)"
100 | ]
101 | },
102 | {
103 | "attachments": {},
104 | "cell_type": "markdown",
105 | "metadata": {},
106 | "source": [
107 | "The dataset is special in that it isn't loaded in memory. When you loop over it with `for`, it will stream the dataset from the disk, one row at a time."
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": 12,
113 | "metadata": {},
114 | "outputs": [
115 | {
116 | "data": {
117 | "text/plain": [
118 | "{'Time': 0.0,\n",
119 | " 'V1': -1.3598071336738,\n",
120 | " 'V2': -0.0727811733098497,\n",
121 | " 'V3': 2.53634673796914,\n",
122 | " 'V4': 1.37815522427443,\n",
123 | " 'V5': -0.338320769942518,\n",
124 | " 'V6': 0.462387777762292,\n",
125 | " 'V7': 0.239598554061257,\n",
126 | " 'V8': 0.0986979012610507,\n",
127 | " 'V9': 0.363786969611213,\n",
128 | " 'V10': 0.0907941719789316,\n",
129 | " 'V11': -0.551599533260813,\n",
130 | " 'V12': -0.617800855762348,\n",
131 | " 'V13': -0.991389847235408,\n",
132 | " 'V14': -0.311169353699879,\n",
133 | " 'V15': 1.46817697209427,\n",
134 | " 'V16': -0.470400525259478,\n",
135 | " 'V17': 0.207971241929242,\n",
136 | " 'V18': 0.0257905801985591,\n",
137 | " 'V19': 0.403992960255733,\n",
138 | " 'V20': 0.251412098239705,\n",
139 | " 'V21': -0.018306777944153,\n",
140 | " 'V22': 0.277837575558899,\n",
141 | " 'V23': -0.110473910188767,\n",
142 | " 'V24': 0.0669280749146731,\n",
143 | " 'V25': 0.128539358273528,\n",
144 | " 'V26': -0.189114843888824,\n",
145 | " 'V27': 0.133558376740387,\n",
146 | " 'V28': -0.0210530534538215,\n",
147 | " 'Amount': 149.62}"
148 | ]
149 | },
150 | "execution_count": 12,
151 | "metadata": {},
152 | "output_type": "execute_result"
153 | }
154 | ],
155 | "source": [
156 | "for transaction, is_fraud in dataset.take(1):\n",
157 | " ...\n",
158 | "\n",
159 | "transaction"
160 | ]
161 | },
162 | {
163 | "cell_type": "code",
164 | "execution_count": 13,
165 | "metadata": {},
166 | "outputs": [
167 | {
168 | "data": {
169 | "text/plain": [
170 | "0"
171 | ]
172 | },
173 | "execution_count": 13,
174 | "metadata": {},
175 | "output_type": "execute_result"
176 | }
177 | ],
178 | "source": [
179 | "is_fraud"
180 | ]
181 | },
182 | {
183 | "attachments": {},
184 | "cell_type": "markdown",
185 | "metadata": {},
186 | "source": [
187 | "**Question 🤔: what is the fraud rate?**"
188 | ]
189 | },
190 | {
191 | "attachments": {},
192 | "cell_type": "markdown",
193 | "metadata": {},
194 | "source": [
195 | "## Progressive validation"
196 | ]
197 | },
198 | {
199 | "cell_type": "code",
200 | "execution_count": 23,
201 | "metadata": {},
202 | "outputs": [
203 | {
204 | "data": {
205 | "text/plain": [
206 | "ROCAUC: 91.49%"
207 | ]
208 | },
209 | "execution_count": 23,
210 | "metadata": {},
211 | "output_type": "execute_result"
212 | }
213 | ],
214 | "source": [
215 | "from river import anomaly\n",
216 | "from river import compose\n",
217 | "from river import metrics\n",
218 | "from river import preprocessing\n",
219 | "\n",
220 | "model = compose.Pipeline(\n",
221 | " preprocessing.MinMaxScaler(),\n",
222 | " anomaly.HalfSpaceTrees(seed=42)\n",
223 | ")\n",
224 | "\n",
225 | "metric = metrics.ROCAUC()\n",
226 | "\n",
227 | "for x, y in dataset.take(100_000):\n",
228 | " score = model.score_one(x)\n",
229 | " model = model.learn_one(x)\n",
230 | " metric = metric.update(y, score)\n",
231 | "\n",
232 | "metric"
233 | ]
234 | },
235 | {
236 | "attachments": {},
237 | "cell_type": "markdown",
238 | "metadata": {},
239 | "source": [
240 | "**Question 🤔: what do you think of this way of evaluating a model?**"
241 | ]
242 | },
243 | {
244 | "attachments": {},
245 | "cell_type": "markdown",
246 | "metadata": {},
247 | "source": [
248 | "Normally, an anomaly detection task is tackled with an unsupervised model due to a lack of labels. Here, we have labels, which allows to evaluate the model's performance. However, we can also train a supervised model and see if it performs any better."
249 | ]
250 | },
251 | {
252 | "cell_type": "code",
253 | "execution_count": 24,
254 | "metadata": {},
255 | "outputs": [
256 | {
257 | "data": {
258 | "text/plain": [
259 | "ROCAUC: 89.20%"
260 | ]
261 | },
262 | "execution_count": 24,
263 | "metadata": {},
264 | "output_type": "execute_result"
265 | }
266 | ],
267 | "source": [
268 | "from river import linear_model\n",
269 | "from river import preprocessing\n",
270 | "\n",
271 | "model = compose.Pipeline(\n",
272 | " preprocessing.StandardScaler(),\n",
273 | " linear_model.LogisticRegression()\n",
274 | ")\n",
275 | "\n",
276 | "metric = metrics.ROCAUC()\n",
277 | "\n",
278 | "for x, y in dataset.take(100_000):\n",
279 | " score = model.predict_proba_one(x)[True]\n",
280 | " model = model.learn_one(x, y)\n",
281 | " metric = metric.update(y, score)\n",
282 | "\n",
283 | "metric"
284 | ]
285 | },
286 | {
287 | "attachments": {},
288 | "cell_type": "markdown",
289 | "metadata": {},
290 | "source": [
291 | "**Question 🤔: why do you think the performance is worse?**"
292 | ]
293 | },
294 | {
295 | "attachments": {},
296 | "cell_type": "markdown",
297 | "metadata": {},
298 | "source": [
299 | "River also has an `evaluate` module with a `progressive_val_score` function."
300 | ]
301 | },
302 | {
303 | "cell_type": "code",
304 | "execution_count": 25,
305 | "metadata": {},
306 | "outputs": [
307 | {
308 | "name": "stdout",
309 | "output_type": "stream",
310 | "text": [
311 | "[10,000] ROCAUC: 94.57% – 00:00:00 – 10.3 KB\n",
312 | "[20,000] ROCAUC: 89.21% – 00:00:01 – 10.3 KB\n",
313 | "[30,000] ROCAUC: 87.08% – 00:00:01 – 10.3 KB\n",
314 | "[40,000] ROCAUC: 87.39% – 00:00:02 – 10.3 KB\n",
315 | "[50,000] ROCAUC: 90.46% – 00:00:03 – 10.3 KB\n",
316 | "[60,000] ROCAUC: 89.19% – 00:00:03 – 10.3 KB\n",
317 | "[70,000] ROCAUC: 89.08% – 00:00:04 – 10.3 KB\n",
318 | "[80,000] ROCAUC: 89.23% – 00:00:05 – 10.3 KB\n",
319 | "[90,000] ROCAUC: 89.76% – 00:00:05 – 10.3 KB\n",
320 | "[100,000] ROCAUC: 89.20% – 00:00:06 – 10.3 KB\n"
321 | ]
322 | },
323 | {
324 | "data": {
325 | "text/plain": [
326 | "ROCAUC: 89.20%"
327 | ]
328 | },
329 | "execution_count": 25,
330 | "metadata": {},
331 | "output_type": "execute_result"
332 | }
333 | ],
334 | "source": [
335 | "from river import evaluate\n",
336 | "\n",
337 | "evaluate.progressive_val_score(\n",
338 | " dataset.take(100_000),\n",
339 | " model=compose.Pipeline(\n",
340 | " preprocessing.StandardScaler(),\n",
341 | " linear_model.LogisticRegression()\n",
342 | " ),\n",
343 | " metric=metrics.ROCAUC(),\n",
344 | " print_every=10_000,\n",
345 | " show_time=True,\n",
346 | " show_memory=True\n",
347 | ")"
348 | ]
349 | },
350 | {
351 | "attachments": {},
352 | "cell_type": "markdown",
353 | "metadata": {},
354 | "source": [
355 | "## Improving the supervised approach"
356 | ]
357 | },
358 | {
359 | "attachments": {},
360 | "cell_type": "markdown",
361 | "metadata": {},
362 | "source": [
363 | "In an anomaly detection task, the number of positive cases is usually much lower than the amount of negatives. This penalizes many supervised classification models, because many are based on the assumption that the data is somewhat balanced. In the case of logistic regression, it's possible to adjust the loss function to increase the importance of positive samples on the learning process."
364 | ]
365 | },
366 | {
367 | "cell_type": "code",
368 | "execution_count": 26,
369 | "metadata": {},
370 | "outputs": [
371 | {
372 | "name": "stdout",
373 | "output_type": "stream",
374 | "text": [
375 | "[10,000] ROCAUC: 95.90% – 00:00:00 – 10.26 KB\n",
376 | "[20,000] ROCAUC: 92.71% – 00:00:01 – 10.26 KB\n",
377 | "[30,000] ROCAUC: 91.84% – 00:00:01 – 10.26 KB\n",
378 | "[40,000] ROCAUC: 92.17% – 00:00:02 – 10.26 KB\n",
379 | "[50,000] ROCAUC: 94.16% – 00:00:03 – 10.26 KB\n",
380 | "[60,000] ROCAUC: 92.55% – 00:00:03 – 10.26 KB\n",
381 | "[70,000] ROCAUC: 92.21% – 00:00:04 – 10.26 KB\n",
382 | "[80,000] ROCAUC: 92.28% – 00:00:05 – 10.26 KB\n",
383 | "[90,000] ROCAUC: 92.59% – 00:00:06 – 10.26 KB\n",
384 | "[100,000] ROCAUC: 91.87% – 00:00:06 – 10.26 KB\n"
385 | ]
386 | },
387 | {
388 | "data": {
389 | "text/plain": [
390 | "ROCAUC: 91.87%"
391 | ]
392 | },
393 | "execution_count": 26,
394 | "metadata": {},
395 | "output_type": "execute_result"
396 | }
397 | ],
398 | "source": [
399 | "from river import optim\n",
400 | "\n",
401 | "evaluate.progressive_val_score(\n",
402 | " dataset.take(100_000),\n",
403 | " model=compose.Pipeline(\n",
404 | " preprocessing.StandardScaler(),\n",
405 | " linear_model.LogisticRegression(\n",
406 | " loss=optim.losses.Log(weight_pos=5)\n",
407 | " )\n",
408 | " ),\n",
409 | " metric=metrics.ROCAUC(),\n",
410 | " print_every=10_000,\n",
411 | " show_time=True,\n",
412 | " show_memory=True\n",
413 | ")"
414 | ]
415 | },
416 | {
417 | "attachments": {},
418 | "cell_type": "markdown",
419 | "metadata": {},
420 | "source": [
421 | "An alternative is to under-sample the majority class. The idea is that the model is being drowned with negative examples. Adjusting the class distribution can help a model. Note that one could also over-sample the minority class. However, the advantage of under-sampling is that it reduces the processing time, because less data has to be processed."
422 | ]
423 | },
424 | {
425 | "cell_type": "code",
426 | "execution_count": 27,
427 | "metadata": {},
428 | "outputs": [
429 | {
430 | "name": "stdout",
431 | "output_type": "stream",
432 | "text": [
433 | "[10,000] ROCAUC: 94.55% – 00:00:00 – 14.33 KB\n",
434 | "[20,000] ROCAUC: 95.59% – 00:00:01 – 14.33 KB\n",
435 | "[30,000] ROCAUC: 95.40% – 00:00:01 – 14.33 KB\n",
436 | "[40,000] ROCAUC: 95.34% – 00:00:02 – 14.33 KB\n",
437 | "[50,000] ROCAUC: 96.72% – 00:00:02 – 14.33 KB\n",
438 | "[60,000] ROCAUC: 95.42% – 00:00:03 – 14.33 KB\n",
439 | "[70,000] ROCAUC: 95.14% – 00:00:03 – 14.33 KB\n",
440 | "[80,000] ROCAUC: 95.38% – 00:00:04 – 14.33 KB\n",
441 | "[90,000] ROCAUC: 95.72% – 00:00:05 – 14.33 KB\n",
442 | "[100,000] ROCAUC: 95.26% – 00:00:05 – 14.33 KB\n"
443 | ]
444 | },
445 | {
446 | "data": {
447 | "text/plain": [
448 | "ROCAUC: 95.26%"
449 | ]
450 | },
451 | "execution_count": 27,
452 | "metadata": {},
453 | "output_type": "execute_result"
454 | }
455 | ],
456 | "source": [
457 | "from river import imblearn\n",
458 | "\n",
459 | "evaluate.progressive_val_score(\n",
460 | " dataset.take(100_000),\n",
461 | " model=compose.Pipeline(\n",
462 | " preprocessing.StandardScaler(),\n",
463 | " imblearn.RandomUnderSampler(\n",
464 | " classifier=linear_model.LogisticRegression(),\n",
465 | " desired_dist={0: .8, 1: .2},\n",
466 | " seed=42\n",
467 | " )\n",
468 | " ),\n",
469 | " metric=metrics.ROCAUC(),\n",
470 | " print_every=10_000,\n",
471 | " show_time=True,\n",
472 | " show_memory=True\n",
473 | ")"
474 | ]
475 | },
476 | {
477 | "attachments": {},
478 | "cell_type": "markdown",
479 | "metadata": {},
480 | "source": [
481 | "Nothing prevents us from combining the two approaches."
482 | ]
483 | },
484 | {
485 | "cell_type": "code",
486 | "execution_count": 28,
487 | "metadata": {},
488 | "outputs": [
489 | {
490 | "name": "stdout",
491 | "output_type": "stream",
492 | "text": [
493 | "[10,000] ROCAUC: 94.23% – 00:00:00 – 14.28 KB\n",
494 | "[20,000] ROCAUC: 96.77% – 00:00:01 – 14.28 KB\n",
495 | "[30,000] ROCAUC: 96.86% – 00:00:01 – 14.28 KB\n",
496 | "[40,000] ROCAUC: 96.54% – 00:00:02 – 14.28 KB\n",
497 | "[50,000] ROCAUC: 97.54% – 00:00:02 – 14.28 KB\n",
498 | "[60,000] ROCAUC: 97.15% – 00:00:03 – 14.28 KB\n",
499 | "[70,000] ROCAUC: 96.83% – 00:00:03 – 14.28 KB\n",
500 | "[80,000] ROCAUC: 96.77% – 00:00:04 – 14.28 KB\n",
501 | "[90,000] ROCAUC: 96.97% – 00:00:05 – 14.28 KB\n",
502 | "[100,000] ROCAUC: 96.49% – 00:00:05 – 14.28 KB\n"
503 | ]
504 | },
505 | {
506 | "data": {
507 | "text/plain": [
508 | "ROCAUC: 96.49%"
509 | ]
510 | },
511 | "execution_count": 28,
512 | "metadata": {},
513 | "output_type": "execute_result"
514 | }
515 | ],
516 | "source": [
517 | "from river import imblearn\n",
518 | "\n",
519 | "evaluate.progressive_val_score(\n",
520 | " dataset.take(100_000),\n",
521 | " model=compose.Pipeline(\n",
522 | " preprocessing.StandardScaler(),\n",
523 | " imblearn.RandomUnderSampler(\n",
524 | " classifier=linear_model.LogisticRegression(\n",
525 | " loss=optim.losses.Log(weight_pos=5)\n",
526 | " ),\n",
527 | " desired_dist={0: .8, 1: .2},\n",
528 | " seed=42\n",
529 | " )\n",
530 | " ),\n",
531 | " metric=metrics.ROCAUC(),\n",
532 | " print_every=10_000,\n",
533 | " show_time=True,\n",
534 | " show_memory=True\n",
535 | ")"
536 | ]
537 | },
538 | {
539 | "attachments": {},
540 | "cell_type": "markdown",
541 | "metadata": {},
542 | "source": [
543 | "## Going further: active learning\n",
544 | "\n",
545 | "We started off with an unsupervised approach. We did so because we assumed we had no labels to train a supervised model. Next, we trained a supervised model, which performed with some tuning. In a real setup, labels wouldn't be available at first. One way to proceed would be to have both models running alongside. \n",
546 | "\n",
547 | "The first model would be unsupervised and rank samples according to their anomaly score. Humans would label the samples according to this ranking. These labels would then feed into the second model. A great way to prioritize this labelling effort is to use active learning. See a demo [here](https://next.databutton.com/v/13lkg6b6), with explanations [here](https://maxhalford.github.io/blog/online-active-learning-river-databutton/).\n",
548 | "\n",
549 | "**Question 🤔: if there are two models running alongside, how to determine which one's outputs should be used?**"
550 | ]
551 | }
552 | ],
553 | "metadata": {
554 | "kernelspec": {
555 | "display_name": "Python 3",
556 | "language": "python",
557 | "name": "python3"
558 | },
559 | "language_info": {
560 | "codemirror_mode": {
561 | "name": "ipython",
562 | "version": 3
563 | },
564 | "file_extension": ".py",
565 | "mimetype": "text/x-python",
566 | "name": "python",
567 | "nbconvert_exporter": "python",
568 | "pygments_lexer": "ipython3",
569 | "version": "3.11.0"
570 | },
571 | "orig_nbformat": 4,
572 | "vscode": {
573 | "interpreter": {
574 | "hash": "55fbbcf542e06cc59ad76a1e0d5dc36ee204d6d2b704491656ee6b3487310122"
575 | }
576 | }
577 | },
578 | "nbformat": 4,
579 | "nbformat_minor": 2
580 | }
581 |
--------------------------------------------------------------------------------
/big-data/streaming/nlp.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "attachments": {},
5 | "cell_type": "markdown",
6 | "metadata": {},
7 | "source": [
8 | "# NLP on streaming data"
9 | ]
10 | },
11 | {
12 | "cell_type": "code",
13 | "execution_count": 57,
14 | "metadata": {},
15 | "outputs": [
16 | {
17 | "data": {
18 | "text/plain": [
19 | "3387"
20 | ]
21 | },
22 | "execution_count": 57,
23 | "metadata": {},
24 | "output_type": "execute_result"
25 | }
26 | ],
27 | "source": [
28 | "from sklearn import datasets\n",
29 | "\n",
30 | "categories = ['alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space']\n",
31 | "newsgroups = datasets.fetch_20newsgroups(\n",
32 | " subset='all',\n",
33 | " remove=['headers', 'footers', 'quotes'],\n",
34 | " categories=categories\n",
35 | ")\n",
36 | "stream = list(zip(\n",
37 | " newsgroups.data,\n",
38 | " (newsgroups.target_names[i] for i in newsgroups.target)\n",
39 | "))\n",
40 | "len(stream)"
41 | ]
42 | },
43 | {
44 | "cell_type": "code",
45 | "execution_count": 7,
46 | "metadata": {},
47 | "outputs": [
48 | {
49 | "name": "stdout",
50 | "output_type": "stream",
51 | "text": [
52 | "My point is that you set up your views as the only way to believe. Saying \n",
53 | "that all eveil in this world is caused by atheism is ridiculous and \n",
54 | "counterproductive to dialogue in this newsgroups. I see in your posts a \n",
55 | "spirit of condemnation of the atheists in this newsgroup bacause they don'\n",
56 | "t believe exactly as you do. If you're here to try to convert the atheists \n",
57 | "here, you're failing miserably. Who wants to be in position of constantly \n",
58 | "defending themselves agaist insulting attacks, like you seem to like to do?!\n",
59 | "I'm sorry you're so blind that you didn't get the messgae in the quote, \n",
60 | "everyone else has seemed to.\n",
61 | "alt.atheism\n"
62 | ]
63 | }
64 | ],
65 | "source": [
66 | "text, label = stream[0]\n",
67 | "print(text)\n",
68 | "print(label)"
69 | ]
70 | },
71 | {
72 | "attachments": {},
73 | "cell_type": "markdown",
74 | "metadata": {},
75 | "source": [
76 | "**Question 🤔: compared to the [anomaly detection notebook](anomaly_detection.ipynb), what is the practical difference with this dataset?**"
77 | ]
78 | },
79 | {
80 | "attachments": {},
81 | "cell_type": "markdown",
82 | "metadata": {},
83 | "source": [
84 | "## Bag of words extraction"
85 | ]
86 | },
87 | {
88 | "cell_type": "code",
89 | "execution_count": 8,
90 | "metadata": {},
91 | "outputs": [
92 | {
93 | "data": {
94 | "text/plain": [
95 | "{'my': 1,\n",
96 | " 'point': 1,\n",
97 | " 'is': 3,\n",
98 | " 'that': 3,\n",
99 | " 'you': 7,\n",
100 | " 'set': 1,\n",
101 | " 'up': 1,\n",
102 | " 'your': 2,\n",
103 | " 'views': 1,\n",
104 | " 'as': 2,\n",
105 | " 'the': 5,\n",
106 | " 'only': 1,\n",
107 | " 'way': 1,\n",
108 | " 'to': 8,\n",
109 | " 'believe': 2,\n",
110 | " 'saying': 1,\n",
111 | " 'all': 1,\n",
112 | " 'eveil': 1,\n",
113 | " 'in': 6,\n",
114 | " 'this': 3,\n",
115 | " 'world': 1,\n",
116 | " 'caused': 1,\n",
117 | " 'by': 1,\n",
118 | " 'atheism': 1,\n",
119 | " 'ridiculous': 1,\n",
120 | " 'and': 1,\n",
121 | " 'counterproductive': 1,\n",
122 | " 'dialogue': 1,\n",
123 | " 'newsgroups': 1,\n",
124 | " 'see': 1,\n",
125 | " 'posts': 1,\n",
126 | " 'spirit': 1,\n",
127 | " 'of': 3,\n",
128 | " 'condemnation': 1,\n",
129 | " 'atheists': 2,\n",
130 | " 'newsgroup': 1,\n",
131 | " 'bacause': 1,\n",
132 | " 'they': 1,\n",
133 | " 'don': 1,\n",
134 | " 'exactly': 1,\n",
135 | " 'do': 2,\n",
136 | " 'if': 1,\n",
137 | " 're': 3,\n",
138 | " 'here': 2,\n",
139 | " 'try': 1,\n",
140 | " 'convert': 1,\n",
141 | " 'failing': 1,\n",
142 | " 'miserably': 1,\n",
143 | " 'who': 1,\n",
144 | " 'wants': 1,\n",
145 | " 'be': 1,\n",
146 | " 'position': 1,\n",
147 | " 'constantly': 1,\n",
148 | " 'defending': 1,\n",
149 | " 'themselves': 1,\n",
150 | " 'agaist': 1,\n",
151 | " 'insulting': 1,\n",
152 | " 'attacks': 1,\n",
153 | " 'like': 2,\n",
154 | " 'seem': 1,\n",
155 | " 'sorry': 1,\n",
156 | " 'so': 1,\n",
157 | " 'blind': 1,\n",
158 | " 'didn': 1,\n",
159 | " 'get': 1,\n",
160 | " 'messgae': 1,\n",
161 | " 'quote': 1,\n",
162 | " 'everyone': 1,\n",
163 | " 'else': 1,\n",
164 | " 'has': 1,\n",
165 | " 'seemed': 1}"
166 | ]
167 | },
168 | "execution_count": 8,
169 | "metadata": {},
170 | "output_type": "execute_result"
171 | }
172 | ],
173 | "source": [
174 | "from river import feature_extraction\n",
175 | "\n",
176 | "vectorizer = feature_extraction.BagOfWords()\n",
177 | "\n",
178 | "for text, label in stream:\n",
179 | " vectorizer = vectorizer.learn_one(text)\n",
180 | " vector = vectorizer.transform_one(text)\n",
181 | " break\n",
182 | "\n",
183 | "vector"
184 | ]
185 | },
186 | {
187 | "attachments": {},
188 | "cell_type": "markdown",
189 | "metadata": {},
190 | "source": [
191 | "**Question 🤔: what do you notice about these tokens?**"
192 | ]
193 | },
194 | {
195 | "attachments": {},
196 | "cell_type": "markdown",
197 | "metadata": {},
198 | "source": [
199 | "## TF-IDF"
200 | ]
201 | },
202 | {
203 | "cell_type": "code",
204 | "execution_count": 9,
205 | "metadata": {},
206 | "outputs": [
207 | {
208 | "data": {
209 | "text/plain": [
210 | "{'my': 0.05754353376484363,\n",
211 | " 'point': 0.05754353376484363,\n",
212 | " 'is': 0.1726306012945309,\n",
213 | " 'that': 0.1726306012945309,\n",
214 | " 'you': 0.4028047363539054,\n",
215 | " 'set': 0.05754353376484363,\n",
216 | " 'up': 0.05754353376484363,\n",
217 | " 'your': 0.11508706752968725,\n",
218 | " 'views': 0.05754353376484363,\n",
219 | " 'as': 0.11508706752968725,\n",
220 | " 'the': 0.2877176688242182,\n",
221 | " 'only': 0.05754353376484363,\n",
222 | " 'way': 0.05754353376484363,\n",
223 | " 'to': 0.460348270118749,\n",
224 | " 'believe': 0.11508706752968725,\n",
225 | " 'saying': 0.05754353376484363,\n",
226 | " 'all': 0.05754353376484363,\n",
227 | " 'eveil': 0.05754353376484363,\n",
228 | " 'in': 0.3452612025890618,\n",
229 | " 'this': 0.1726306012945309,\n",
230 | " 'world': 0.05754353376484363,\n",
231 | " 'caused': 0.05754353376484363,\n",
232 | " 'by': 0.05754353376484363,\n",
233 | " 'atheism': 0.05754353376484363,\n",
234 | " 'ridiculous': 0.05754353376484363,\n",
235 | " 'and': 0.05754353376484363,\n",
236 | " 'counterproductive': 0.05754353376484363,\n",
237 | " 'dialogue': 0.05754353376484363,\n",
238 | " 'newsgroups': 0.05754353376484363,\n",
239 | " 'see': 0.05754353376484363,\n",
240 | " 'posts': 0.05754353376484363,\n",
241 | " 'spirit': 0.05754353376484363,\n",
242 | " 'of': 0.1726306012945309,\n",
243 | " 'condemnation': 0.05754353376484363,\n",
244 | " 'atheists': 0.11508706752968725,\n",
245 | " 'newsgroup': 0.05754353376484363,\n",
246 | " 'bacause': 0.05754353376484363,\n",
247 | " 'they': 0.05754353376484363,\n",
248 | " 'don': 0.05754353376484363,\n",
249 | " 'exactly': 0.05754353376484363,\n",
250 | " 'do': 0.11508706752968725,\n",
251 | " 'if': 0.05754353376484363,\n",
252 | " 're': 0.1726306012945309,\n",
253 | " 'here': 0.11508706752968725,\n",
254 | " 'try': 0.05754353376484363,\n",
255 | " 'convert': 0.05754353376484363,\n",
256 | " 'failing': 0.05754353376484363,\n",
257 | " 'miserably': 0.05754353376484363,\n",
258 | " 'who': 0.05754353376484363,\n",
259 | " 'wants': 0.05754353376484363,\n",
260 | " 'be': 0.05754353376484363,\n",
261 | " 'position': 0.05754353376484363,\n",
262 | " 'constantly': 0.05754353376484363,\n",
263 | " 'defending': 0.05754353376484363,\n",
264 | " 'themselves': 0.05754353376484363,\n",
265 | " 'agaist': 0.05754353376484363,\n",
266 | " 'insulting': 0.05754353376484363,\n",
267 | " 'attacks': 0.05754353376484363,\n",
268 | " 'like': 0.11508706752968725,\n",
269 | " 'seem': 0.05754353376484363,\n",
270 | " 'sorry': 0.05754353376484363,\n",
271 | " 'so': 0.05754353376484363,\n",
272 | " 'blind': 0.05754353376484363,\n",
273 | " 'didn': 0.05754353376484363,\n",
274 | " 'get': 0.05754353376484363,\n",
275 | " 'messgae': 0.05754353376484363,\n",
276 | " 'quote': 0.05754353376484363,\n",
277 | " 'everyone': 0.05754353376484363,\n",
278 | " 'else': 0.05754353376484363,\n",
279 | " 'has': 0.05754353376484363,\n",
280 | " 'seemed': 0.05754353376484363}"
281 | ]
282 | },
283 | "execution_count": 9,
284 | "metadata": {},
285 | "output_type": "execute_result"
286 | }
287 | ],
288 | "source": [
289 | "from river import feature_extraction\n",
290 | "\n",
291 | "vectorizer = feature_extraction.TFIDF()\n",
292 | "\n",
293 | "for text, label in stream:\n",
294 | " vectorizer = vectorizer.learn_one(text)\n",
295 | " vector = vectorizer.transform_one(text)\n",
296 | " break\n",
297 | "\n",
298 | "vector"
299 | ]
300 | },
301 | {
302 | "attachments": {},
303 | "cell_type": "markdown",
304 | "metadata": {},
305 | "source": [
306 | "**Question 🤔: knowing how TF-IDF works, what difference does its online variant have?**"
307 | ]
308 | },
309 | {
310 | "attachments": {},
311 | "cell_type": "markdown",
312 | "metadata": {},
313 | "source": [
314 | "## Progressive validation"
315 | ]
316 | },
317 | {
318 | "cell_type": "code",
319 | "execution_count": 10,
320 | "metadata": {},
321 | "outputs": [
322 | {
323 | "name": "stdout",
324 | "output_type": "stream",
325 | "text": [
326 | "[1,000] Accuracy: 68.47%, MacroF1: 67.29%\n",
327 | "[2,000] Accuracy: 72.49%, MacroF1: 71.03%\n",
328 | "[3,000] Accuracy: 74.66%, MacroF1: 73.16%\n",
329 | "[3,387] Accuracy: 74.96%, MacroF1: 73.49%\n"
330 | ]
331 | },
332 | {
333 | "data": {
334 | "text/plain": [
335 | "Accuracy: 74.96%, MacroF1: 73.49%"
336 | ]
337 | },
338 | "execution_count": 10,
339 | "metadata": {},
340 | "output_type": "execute_result"
341 | }
342 | ],
343 | "source": [
344 | "from river import evaluate\n",
345 | "from river import metrics\n",
346 | "from river import naive_bayes\n",
347 | "\n",
348 | "model = (\n",
349 | " feature_extraction.BagOfWords() |\n",
350 | " naive_bayes.MultinomialNB()\n",
351 | ")\n",
352 | "\n",
353 | "metric = metrics.Accuracy() + metrics.MacroF1()\n",
354 | "\n",
355 | "evaluate.progressive_val_score(stream, model, metric, print_every=1000)"
356 | ]
357 | },
358 | {
359 | "attachments": {},
360 | "cell_type": "markdown",
361 | "metadata": {},
362 | "source": [
363 | "**Question 🤔: what makes the comparison with a batch approach difficult?**"
364 | ]
365 | },
366 | {
367 | "attachments": {},
368 | "cell_type": "markdown",
369 | "metadata": {},
370 | "source": [
371 | "## Mini-batching"
372 | ]
373 | },
374 | {
375 | "cell_type": "code",
376 | "execution_count": 53,
377 | "metadata": {},
378 | "outputs": [
379 | {
380 | "name": "stdout",
381 | "output_type": "stream",
382 | "text": [
383 | "1000\n",
384 | "1000\n",
385 | "1000\n",
386 | "387\n"
387 | ]
388 | }
389 | ],
390 | "source": [
391 | "def batch(stream, size):\n",
392 | " batch = []\n",
393 | " for x, y in stream:\n",
394 | " batch.append((x, y))\n",
395 | " if len(batch) == size:\n",
396 | " yield batch\n",
397 | " batch = []\n",
398 | " if batch:\n",
399 | " yield batch\n",
400 | "\n",
401 | "for mini_batch in batch(stream, size=1000):\n",
402 | " print(len(mini_batch))"
403 | ]
404 | },
405 | {
406 | "cell_type": "code",
407 | "execution_count": 74,
408 | "metadata": {},
409 | "outputs": [
410 | {
411 | "ename": "ValueError",
412 | "evalue": "X has 17444 features, but GaussianNB is expecting 19939 features as input.",
413 | "output_type": "error",
414 | "traceback": [
415 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
416 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
417 | "Cell \u001b[0;32mIn [74], line 10\u001b[0m\n\u001b[1;32m 8\u001b[0m X, y \u001b[39m=\u001b[39m \u001b[39mzip\u001b[39m(\u001b[39m*\u001b[39mmini_batch)\n\u001b[1;32m 9\u001b[0m X \u001b[39m=\u001b[39m vectorizer\u001b[39m.\u001b[39mfit_transform(X)\u001b[39m.\u001b[39mtoarray()\n\u001b[0;32m---> 10\u001b[0m model\u001b[39m.\u001b[39;49mpartial_fit(X, y, classes\u001b[39m=\u001b[39;49mcategories)\n",
418 | "File \u001b[0;32m~/.pyenv/versions/3.11.0/lib/python3.11/site-packages/sklearn/naive_bayes.py:389\u001b[0m, in \u001b[0;36mGaussianNB.partial_fit\u001b[0;34m(self, X, y, classes, sample_weight)\u001b[0m\n\u001b[1;32m 348\u001b[0m \u001b[39m\"\"\"Incremental fit on a batch of samples.\u001b[39;00m\n\u001b[1;32m 349\u001b[0m \n\u001b[1;32m 350\u001b[0m \u001b[39mThis method is expected to be called several times consecutively\u001b[39;00m\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 385\u001b[0m \u001b[39m Returns the instance itself.\u001b[39;00m\n\u001b[1;32m 386\u001b[0m \u001b[39m\"\"\"\u001b[39;00m\n\u001b[1;32m 387\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39m_validate_params()\n\u001b[0;32m--> 389\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_partial_fit(\n\u001b[1;32m 390\u001b[0m X, y, classes, _refit\u001b[39m=\u001b[39;49m\u001b[39mFalse\u001b[39;49;00m, sample_weight\u001b[39m=\u001b[39;49msample_weight\n\u001b[1;32m 391\u001b[0m )\n",
419 | "File \u001b[0;32m~/.pyenv/versions/3.11.0/lib/python3.11/site-packages/sklearn/naive_bayes.py:426\u001b[0m, in \u001b[0;36mGaussianNB._partial_fit\u001b[0;34m(self, X, y, classes, _refit, sample_weight)\u001b[0m\n\u001b[1;32m 423\u001b[0m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mclasses_ \u001b[39m=\u001b[39m \u001b[39mNone\u001b[39;00m\n\u001b[1;32m 425\u001b[0m first_call \u001b[39m=\u001b[39m _check_partial_fit_first_call(\u001b[39mself\u001b[39m, classes)\n\u001b[0;32m--> 426\u001b[0m X, y \u001b[39m=\u001b[39m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_validate_data(X, y, reset\u001b[39m=\u001b[39;49mfirst_call)\n\u001b[1;32m 427\u001b[0m \u001b[39mif\u001b[39;00m sample_weight \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:\n\u001b[1;32m 428\u001b[0m sample_weight \u001b[39m=\u001b[39m _check_sample_weight(sample_weight, X)\n",
420 | "File \u001b[0;32m~/.pyenv/versions/3.11.0/lib/python3.11/site-packages/sklearn/base.py:558\u001b[0m, in \u001b[0;36mBaseEstimator._validate_data\u001b[0;34m(self, X, y, reset, validate_separately, **check_params)\u001b[0m\n\u001b[1;32m 555\u001b[0m out \u001b[39m=\u001b[39m X, y\n\u001b[1;32m 557\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m no_val_X \u001b[39mand\u001b[39;00m check_params\u001b[39m.\u001b[39mget(\u001b[39m\"\u001b[39m\u001b[39mensure_2d\u001b[39m\u001b[39m\"\u001b[39m, \u001b[39mTrue\u001b[39;00m):\n\u001b[0;32m--> 558\u001b[0m \u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49m_check_n_features(X, reset\u001b[39m=\u001b[39;49mreset)\n\u001b[1;32m 560\u001b[0m \u001b[39mreturn\u001b[39;00m out\n",
421 | "File \u001b[0;32m~/.pyenv/versions/3.11.0/lib/python3.11/site-packages/sklearn/base.py:359\u001b[0m, in \u001b[0;36mBaseEstimator._check_n_features\u001b[0;34m(self, X, reset)\u001b[0m\n\u001b[1;32m 356\u001b[0m \u001b[39mreturn\u001b[39;00m\n\u001b[1;32m 358\u001b[0m \u001b[39mif\u001b[39;00m n_features \u001b[39m!=\u001b[39m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mn_features_in_:\n\u001b[0;32m--> 359\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\n\u001b[1;32m 360\u001b[0m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mX has \u001b[39m\u001b[39m{\u001b[39;00mn_features\u001b[39m}\u001b[39;00m\u001b[39m features, but \u001b[39m\u001b[39m{\u001b[39;00m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39m\u001b[39m__class__\u001b[39m\u001b[39m.\u001b[39m\u001b[39m__name__\u001b[39m\u001b[39m}\u001b[39;00m\u001b[39m \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 361\u001b[0m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mis expecting \u001b[39m\u001b[39m{\u001b[39;00m\u001b[39mself\u001b[39m\u001b[39m.\u001b[39mn_features_in_\u001b[39m}\u001b[39;00m\u001b[39m features as input.\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m 362\u001b[0m )\n",
422 | "\u001b[0;31mValueError\u001b[0m: X has 17444 features, but GaussianNB is expecting 19939 features as input."
423 | ]
424 | }
425 | ],
426 | "source": [
427 | "from sklearn import feature_extraction\n",
428 | "from sklearn import naive_bayes\n",
429 | "\n",
430 | "vectorizer = feature_extraction.text.CountVectorizer()\n",
431 | "model = naive_bayes.GaussianNB()\n",
432 | "\n",
433 | "for mini_batch in batch(stream, size=1000):\n",
434 | " X, y = zip(*mini_batch)\n",
435 | " X = vectorizer.fit_transform(X).toarray()\n",
436 | " model.partial_fit(X, y, classes=categories)"
437 | ]
438 | },
439 | {
440 | "attachments": {},
441 | "cell_type": "markdown",
442 | "metadata": {},
443 | "source": [
444 | "**Question 🤔: what is the issue?**"
445 | ]
446 | },
447 | {
448 | "attachments": {},
449 | "cell_type": "markdown",
450 | "metadata": {},
451 | "source": [
452 | "A common way of dealing with a varying number of features is called the [\"hashing trick\"](https://www.wikiwand.com/en/Feature_hashing). scikit-learn has a `HashingVectorizer`, which is a combination of [`CountVectorizer`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html) and [`FeatureHasher`](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.FeatureHasher.html)."
453 | ]
454 | },
455 | {
456 | "cell_type": "code",
457 | "execution_count": 73,
458 | "metadata": {},
459 | "outputs": [],
460 | "source": [
461 | "from sklearn import pipeline\n",
462 | "\n",
463 | "from sklearn import feature_extraction\n",
464 | "from sklearn import naive_bayes\n",
465 | "\n",
466 | "vectorizer = feature_extraction.text.HashingVectorizer(n_features=2000)\n",
467 | "model = naive_bayes.GaussianNB()\n",
468 | "\n",
469 | "for mini_batch in batch(stream, size=1000):\n",
470 | " X, y = zip(*mini_batch)\n",
471 | " X = vectorizer.fit_transform(X).toarray()\n",
472 | " model.partial_fit(X, y, classes=categories)"
473 | ]
474 | }
475 | ],
476 | "metadata": {
477 | "kernelspec": {
478 | "display_name": "Python 3",
479 | "language": "python",
480 | "name": "python3"
481 | },
482 | "language_info": {
483 | "codemirror_mode": {
484 | "name": "ipython",
485 | "version": 3
486 | },
487 | "file_extension": ".py",
488 | "mimetype": "text/x-python",
489 | "name": "python",
490 | "nbconvert_exporter": "python",
491 | "pygments_lexer": "ipython3",
492 | "version": "3.11.0"
493 | },
494 | "orig_nbformat": 4,
495 | "vscode": {
496 | "interpreter": {
497 | "hash": "55fbbcf542e06cc59ad76a1e0d5dc36ee204d6d2b704491656ee6b3487310122"
498 | }
499 | }
500 | },
501 | "nbformat": 4,
502 | "nbformat_minor": 2
503 | }
504 |
--------------------------------------------------------------------------------
/data-mining/clustering/lab.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Clustering lab"
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "!git lfs pull --include ../../data/wowah.zip\n"
17 | ]
18 | },
19 | {
20 | "cell_type": "code",
21 | "execution_count": 2,
22 | "metadata": {},
23 | "outputs": [
24 | {
25 | "data": {
26 | "text/html": [
27 | "
\n",
28 | "\n",
41 | "
\n",
42 | " \n",
43 | "
\n",
44 | "
\n",
45 | "
char
\n",
46 | "
level
\n",
47 | "
race
\n",
48 | "
charclass
\n",
49 | "
zone
\n",
50 | "
guild
\n",
51 | "
timestamp
\n",
52 | "
\n",
53 | " \n",
54 | " \n",
55 | "
\n",
56 | "
0
\n",
57 | "
59425
\n",
58 | "
1
\n",
59 | "
Orc
\n",
60 | "
Rogue
\n",
61 | "
Orgrimmar
\n",
62 | "
165
\n",
63 | "
01/01/08 00:02:04
\n",
64 | "
\n",
65 | "
\n",
66 | "
1
\n",
67 | "
65494
\n",
68 | "
9
\n",
69 | "
Orc
\n",
70 | "
Hunter
\n",
71 | "
Durotar
\n",
72 | "
-1
\n",
73 | "
01/01/08 00:02:04
\n",
74 | "
\n",
75 | "
\n",
76 | "
2
\n",
77 | "
65325
\n",
78 | "
14
\n",
79 | "
Orc
\n",
80 | "
Warrior
\n",
81 | "
Ghostlands
\n",
82 | "
-1
\n",
83 | "
01/01/08 00:02:04
\n",
84 | "
\n",
85 | "
\n",
86 | "
3
\n",
87 | "
65490
\n",
88 | "
18
\n",
89 | "
Orc
\n",
90 | "
Hunter
\n",
91 | "
Ghostlands
\n",
92 | "
-1
\n",
93 | "
01/01/08 00:02:04
\n",
94 | "
\n",
95 | "
\n",
96 | "
4
\n",
97 | "
2288
\n",
98 | "
60
\n",
99 | "
Orc
\n",
100 | "
Hunter
\n",
101 | "
Hellfire Peninsula
\n",
102 | "
-1
\n",
103 | "
01/01/08 00:02:09
\n",
104 | "
\n",
105 | "
\n",
106 | "
...
\n",
107 | "
...
\n",
108 | "
...
\n",
109 | "
...
\n",
110 | "
...
\n",
111 | "
...
\n",
112 | "
...
\n",
113 | "
...
\n",
114 | "
\n",
115 | "
\n",
116 | "
10826729
\n",
117 | "
86766
\n",
118 | "
80
\n",
119 | "
Blood Elf
\n",
120 | "
Death Knight
\n",
121 | "
Halls of Lightning
\n",
122 | "
101
\n",
123 | "
12/31/08 23:50:18
\n",
124 | "
\n",
125 | "
\n",
126 | "
10826730
\n",
127 | "
86497
\n",
128 | "
77
\n",
129 | "
Blood Elf
\n",
130 | "
Death Knight
\n",
131 | "
The Storm Peaks
\n",
132 | "
358
\n",
133 | "
12/31/08 23:50:18
\n",
134 | "
\n",
135 | "
\n",
136 | "
10826731
\n",
137 | "
34893
\n",
138 | "
80
\n",
139 | "
Blood Elf
\n",
140 | "
Death Knight
\n",
141 | "
The Storm Peaks
\n",
142 | "
189
\n",
143 | "
12/31/08 23:50:18
\n",
144 | "
\n",
145 | "
\n",
146 | "
10826732
\n",
147 | "
86881
\n",
148 | "
80
\n",
149 | "
Blood Elf
\n",
150 | "
Death Knight
\n",
151 | "
Dragonblight
\n",
152 | "
478
\n",
153 | "
12/31/08 23:50:18
\n",
154 | "
\n",
155 | "
\n",
156 | "
10826733
\n",
157 | "
86457
\n",
158 | "
80
\n",
159 | "
Blood Elf
\n",
160 | "
Death Knight
\n",
161 | "
Dragonblight
\n",
162 | "
204
\n",
163 | "
12/31/08 23:50:18
\n",
164 | "
\n",
165 | " \n",
166 | "
\n",
167 | "
10826734 rows × 7 columns
\n",
168 | "
"
169 | ],
170 | "text/plain": [
171 | " char level race charclass zone guild \\\n",
172 | "0 59425 1 Orc Rogue Orgrimmar 165 \n",
173 | "1 65494 9 Orc Hunter Durotar -1 \n",
174 | "2 65325 14 Orc Warrior Ghostlands -1 \n",
175 | "3 65490 18 Orc Hunter Ghostlands -1 \n",
176 | "4 2288 60 Orc Hunter Hellfire Peninsula -1 \n",
177 | "... ... ... ... ... ... ... \n",
178 | "10826729 86766 80 Blood Elf Death Knight Halls of Lightning 101 \n",
179 | "10826730 86497 77 Blood Elf Death Knight The Storm Peaks 358 \n",
180 | "10826731 34893 80 Blood Elf Death Knight The Storm Peaks 189 \n",
181 | "10826732 86881 80 Blood Elf Death Knight Dragonblight 478 \n",
182 | "10826733 86457 80 Blood Elf Death Knight Dragonblight 204 \n",
183 | "\n",
184 | " timestamp \n",
185 | "0 01/01/08 00:02:04 \n",
186 | "1 01/01/08 00:02:04 \n",
187 | "2 01/01/08 00:02:04 \n",
188 | "3 01/01/08 00:02:04 \n",
189 | "4 01/01/08 00:02:09 \n",
190 | "... ... \n",
191 | "10826729 12/31/08 23:50:18 \n",
192 | "10826730 12/31/08 23:50:18 \n",
193 | "10826731 12/31/08 23:50:18 \n",
194 | "10826732 12/31/08 23:50:18 \n",
195 | "10826733 12/31/08 23:50:18 \n",
196 | "\n",
197 | "[10826734 rows x 7 columns]"
198 | ]
199 | },
200 | "execution_count": 2,
201 | "metadata": {},
202 | "output_type": "execute_result"
203 | }
204 | ],
205 | "source": [
206 | "import zipfile\n",
207 | "import pandas as pd\n",
208 | "\n",
209 | "with zipfile.ZipFile('../../data/wowah.zip') as z:\n",
210 | " with z.open('wowah_data.csv') as f:\n",
211 | " wowah = pd.read_csv(f)\n",
212 | "wowah\n"
213 | ]
214 | },
215 | {
216 | "cell_type": "markdown",
217 | "metadata": {},
218 | "source": [
219 | "Instructions: be creative! Use the tools we've learned so far to explore the data and find interesting patterns. You can use the clustering methods we've learned so far, or any other methods you find in scikit-learn.\n",
220 | "\n",
221 | "You will likely have to process the data in some way to get it into a form that can be used by the clustering algorithms. Indeed, there are several samples per user, so you will have to find a way to aggregate the data. Here are a couple of suggestions:\n",
222 | "\n",
223 | "1. Look at the last sample per character, and try to cluster characters based on the basic available properties.\n",
224 | "2. Add some aggregate features: the total time played, the most common time of day, the speed at which the player levelled up, etc.\n",
225 | "3. Split the data into sessions, and try to cluster the sessions themselves. Transforming events into sessions is a good skill to have, as it is a common problem in data science: you have a log of events, and you want to identify meaningful sessions of activity."
226 | ]
227 | }
228 | ],
229 | "metadata": {
230 | "kernelspec": {
231 | "display_name": "Python 3",
232 | "language": "python",
233 | "name": "python3"
234 | },
235 | "language_info": {
236 | "codemirror_mode": {
237 | "name": "ipython",
238 | "version": 3
239 | },
240 | "file_extension": ".py",
241 | "mimetype": "text/x-python",
242 | "name": "python",
243 | "nbconvert_exporter": "python",
244 | "pygments_lexer": "ipython3",
245 | "version": "3.11.0"
246 | }
247 | },
248 | "nbformat": 4,
249 | "nbformat_minor": 2
250 | }
251 |
--------------------------------------------------------------------------------
/data-mining/data-viz/altair.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "https://github.com/datascience-course/2023-datascience-lectures/blob/main/12-practical-data-visualization/12-practical_visualization.ipynb\n"
10 | ]
11 | }
12 | ],
13 | "metadata": {
14 | "language_info": {
15 | "name": "python"
16 | }
17 | },
18 | "nbformat": 4,
19 | "nbformat_minor": 2
20 | }
21 |
--------------------------------------------------------------------------------
/data-mining/data-viz/lab.ipynb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MaxHalford/data-science-tutorials/73a731845de39b89b8852ba2dcc38b67c8f1e1e1/data-mining/data-viz/lab.ipynb
--------------------------------------------------------------------------------
/data-mining/data-viz/table.html:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MaxHalford/data-science-tutorials/73a731845de39b89b8852ba2dcc38b67c8f1e1e1/data-mining/data-viz/table.html
--------------------------------------------------------------------------------
/data-mining/finding-structure/lab.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Lab: analyzing tents data\n",
8 | "\n",
9 | "## Data extraction\n",
10 | "\n",
11 | "Let's fetch data from Decathlon. We'll do it in two phases. First, we'll make a list of all the tents they have. Then, we'll fetch the data for each tent.\n",
12 | "\n",
13 | "Let's start by listing the tents they have."
14 | ]
15 | },
16 | {
17 | "cell_type": "code",
18 | "execution_count": 3,
19 | "metadata": {},
20 | "outputs": [],
21 | "source": [
22 | "import json\n",
23 | "import re\n",
24 | "import bs4\n",
25 | "import requests\n",
26 | "\n",
27 | "url = 'https://www.decathlon.fr/tous-les-sports/camping-bivouac/tentes-et-abris'\n",
28 | "response = requests.get(url)\n",
29 | "soup = bs4.BeautifulSoup(response.content, 'html.parser')\n",
30 | "script_tag = soup.find('script', id='__dkt')\n",
31 | "raw_json = re.search(r'{(.+)}', script_tag.string).group(0)\n",
32 | "data = json.loads(raw_json)\n"
33 | ]
34 | },
35 | {
36 | "cell_type": "markdown",
37 | "metadata": {},
38 | "source": [
39 | "Here's a tool explore the JSON: https://jsonhero.io/j/VTrWj5vx53Ys\n",
40 | "\n",
41 | "The data is quite deeply nested, but it's not difficult to extract:"
42 | ]
43 | },
44 | {
45 | "cell_type": "code",
46 | "execution_count": 4,
47 | "metadata": {},
48 | "outputs": [],
49 | "source": [
50 | "# Note: if the following doesn't work, try modifying the index. It's possible that Decathlon has changed the structure of the page.\n",
51 | "idx = 6\n",
52 | "tents = {\n",
53 | " item['webLabel']: f\"https://www.decathlon.fr/{item['url']}\"\n",
54 | " for item in data['_ctx']['data'][idx]['data']['blocks']['items']\n",
55 | "}\n"
56 | ]
57 | },
58 | {
59 | "cell_type": "code",
60 | "execution_count": 5,
61 | "metadata": {},
62 | "outputs": [
63 | {
64 | "data": {
65 | "text/plain": [
66 | "{'Séjour à arceaux de camping - Arpenaz Base - 6 Personnes': 'https://www.decathlon.fr/p/sejour-a-arceaux-de-camping-arpenaz-base-6-personnes/_/R-p-157674',\n",
67 | " 'Tente de camping - 2 SECONDS - 2 places': 'https://www.decathlon.fr/p/tente-de-camping-2-seconds-2-places/_/R-p-340082',\n",
68 | " 'Tente dôme de trekking - 1 place - MT900': 'https://www.decathlon.fr/p/tente-dome-de-trekking-1-place-mt900/_/R-p-305777',\n",
69 | " 'Tente de camping - MH100 - 2 places': 'https://www.decathlon.fr/p/tente-de-camping-mh100-2-places/_/R-p-303295',\n",
70 | " 'Housse de compression de trekking imperméable - 20 Litres': 'https://www.decathlon.fr/p/housse-de-compression-de-trekking-impermeable-20-litres/_/R-p-311987',\n",
71 | " 'Lot de 2 housses de rangement de trekking - Demi-lune imperméables - 2x7L': 'https://www.decathlon.fr/p/lot-de-2-housses-de-rangement-de-trekking-demi-lune-impermeables-2x7l/_/R-p-309832',\n",
72 | " 'Tente dôme de trekking - 3 places - MT900': 'https://www.decathlon.fr/p/tente-dome-de-trekking-3-places-mt900/_/R-p-301559',\n",
73 | " 'Social Bivvy L Pêche de la carpe': 'https://www.decathlon.fr/p/social-bivvy-l-peche-de-la-carpe/_/R-p-327052',\n",
74 | " 'Lot de 2 housses de rangement de trekking - Demi-lune imperméables - 2x15L': 'https://www.decathlon.fr/p/lot-de-2-housses-de-rangement-de-trekking-demi-lune-impermeables-2x15l/_/R-p-309853',\n",
75 | " 'Tente de camping - 2 SECONDS XL - 3 places - Fresh & Black': 'https://www.decathlon.fr/p/tente-de-camping-2-seconds-xl-3-places-fresh-black/_/R-p-172537',\n",
76 | " 'Tente tarp de trekking - 1 place - MT900 Minimal Editions - Undyed': 'https://www.decathlon.fr/p/tente-tarp-de-trekking-1-place-mt900-minimal-editions-undyed/_/R-p-343262',\n",
77 | " 'Tente de camping - 2 SECONDS - 3 places - Fresh & Black': 'https://www.decathlon.fr/p/tente-de-camping-2-seconds-3-places-fresh-black/_/R-p-142651',\n",
78 | " 'Tente de camping - MH100 XL - 3 places - Fresh & Black': 'https://www.decathlon.fr/p/tente-de-camping-mh100-xl-3-places-fresh-black/_/R-p-331796',\n",
79 | " 'Abri de camping instantané 4 places - Base Easy 4P UltraFresh': 'https://www.decathlon.fr/p/abri-de-camping-instantane-4-places-base-easy-4p-ultrafresh/_/R-p-342385',\n",
80 | " 'Tente de camping - MH100 - 3 places - Fresh & Black': 'https://www.decathlon.fr/p/tente-de-camping-mh100-3-places-fresh-black/_/R-p-313085',\n",
81 | " 'Tente de camping - MH100 - 4 places': 'https://www.decathlon.fr/p/tente-de-camping-mh100-4-places/_/R-p-343524',\n",
82 | " 'Tente de camping - MH100 - 3 places': 'https://www.decathlon.fr/p/tente-de-camping-mh100-3-places/_/R-p-308317',\n",
83 | " 'TARP ABRI CAMPING MULTIFONCTION': 'https://www.decathlon.fr/p/tarp-abri-camping-multifonction/_/R-p-307422',\n",
84 | " '6 PIQUETS DE TENTE - SOLS DURS': 'https://www.decathlon.fr/p/6-piquets-de-tente-sols-durs/_/R-p-105665',\n",
85 | " 'Lot de 2 housses de rangement universelles - 2x10L': 'https://www.decathlon.fr/p/lot-de-2-housses-de-rangement-universelles-2x10l/_/R-p-191091',\n",
86 | " 'PELLE-PIOCHE PLIANTE POUR LE CAMPING': 'https://www.decathlon.fr/p/pelle-pioche-pliante-pour-le-camping/_/R-p-302835',\n",
87 | " 'MAILLET DE CAMPING': 'https://www.decathlon.fr/p/maillet-de-camping/_/R-p-147151',\n",
88 | " 'Abri à arceaux de camping - 1 place - Arpenaz 1P': 'https://www.decathlon.fr/p/abri-a-arceaux-de-camping-1-place-arpenaz-1p/_/R-p-336276',\n",
89 | " 'MAILLET DE CAMPING TERRAIN DUR': 'https://www.decathlon.fr/p/maillet-de-camping-terrain-dur/_/R-p-343552',\n",
90 | " 'KIT BALAI - PELLE POUR LE CAMPING': 'https://www.decathlon.fr/p/kit-balai-pelle-pour-le-camping/_/R-p-334078',\n",
91 | " '10 CORNIÈRES DE TENTE - SOLS MOUS OU MEUBLES': 'https://www.decathlon.fr/p/10-cornieres-de-tente-sols-mous-ou-meubles/_/R-p-3735',\n",
92 | " 'Piquets alu non-anodisés - MT500 - 15 g (x5)': 'https://www.decathlon.fr/p/piquets-alu-non-anodises-mt500-15-g-x5/_/R-p-311281',\n",
93 | " 'Tente bulle de camping - AirSeconds Skyview Polycoton - 2 Personnes - 1 Chambre': 'https://www.decathlon.fr/p/tente-bulle-de-camping-airseconds-skyview-polycoton-2-personnes-1-chambre/_/R-p-342404',\n",
94 | " 'TENTE DE TOIT MH500 FRESH & BLACK 2P': 'https://www.decathlon.fr/p/tente-de-toit-mh500-fresh-black-2p/_/R-p-331938',\n",
95 | " 'Tente dôme de trekking - 2 places - MT900': 'https://www.decathlon.fr/p/tente-dome-de-trekking-2-places-mt900/_/R-p-301558',\n",
96 | " 'TENTE DE TOIT GONFLABLE MH900 FRESH & BLACK 2 PERSONNES': 'https://www.decathlon.fr/p/tente-de-toit-gonflable-mh900-fresh-black-2-personnes/_/R-p-344868',\n",
97 | " 'Tente à arceaux de camping - Arpenaz 4.1 - 4 Personnes - 1 Chambre': 'https://www.decathlon.fr/p/tente-a-arceaux-de-camping-arpenaz-4-1-4-personnes-1-chambre/_/R-p-4123',\n",
98 | " 'Séjour à arceaux de camping - Arpenaz Base Fresh - 10 Personnes': 'https://www.decathlon.fr/p/sejour-a-arceaux-de-camping-arpenaz-base-fresh-10-personnes/_/R-p-308178',\n",
99 | " 'Tente dôme de trekking - 2 places - MT500 Fresh & Black': 'https://www.decathlon.fr/p/tente-dome-de-trekking-2-places-mt500-fresh-black/_/R-p-311346',\n",
100 | " 'Tente gonflable de camping - Air Seconds 6.3 F&B - 6 Personnes - 3 Chambres': 'https://www.decathlon.fr/p/tente-gonflable-de-camping-air-seconds-6-3-f-b-6-personnes-3-chambres/_/R-p-324957',\n",
101 | " 'Tente à arceaux de camping - Arpenaz 4 - 4 Personnes - 1 Chambre': 'https://www.decathlon.fr/p/tente-a-arceaux-de-camping-arpenaz-4-4-personnes-1-chambre/_/R-p-105650',\n",
102 | " 'Tente de camping - 2 SECONDS EASY - 2 places - Fresh & Black': 'https://www.decathlon.fr/p/tente-de-camping-2-seconds-easy-2-places-fresh-black/_/R-p-308355',\n",
103 | " 'Tente à arceaux de camping - Arpenaz 4.1 F&B - 4 Personnes - 1 Chambre': 'https://www.decathlon.fr/p/tente-a-arceaux-de-camping-arpenaz-4-1-f-b-4-personnes-1-chambre/_/R-p-177332',\n",
104 | " 'Tente gonflable de camping - Air Seconds 5.2 F&B - 5 Personnes - 2 Chambres': 'https://www.decathlon.fr/p/tente-gonflable-de-camping-air-seconds-5-2-f-b-5-personnes-2-chambres/_/R-p-324972',\n",
105 | " 'Tente gonflable de camping - Air Seconds 4.2 F&B - 4 Personnes - 2 Chambres': 'https://www.decathlon.fr/p/tente-gonflable-de-camping-air-seconds-4-2-f-b-4-personnes-2-chambres/_/R-p-157654'}"
106 | ]
107 | },
108 | "execution_count": 5,
109 | "metadata": {},
110 | "output_type": "execute_result"
111 | }
112 | ],
113 | "source": [
114 | "tents\n"
115 | ]
116 | },
117 | {
118 | "cell_type": "markdown",
119 | "metadata": {},
120 | "source": [
121 | "So now we have a URL for each tent. Let's grab some data for the first tent."
122 | ]
123 | },
124 | {
125 | "cell_type": "code",
126 | "execution_count": 9,
127 | "metadata": {},
128 | "outputs": [],
129 | "source": [
130 | "url = tents['Tente de camping - MH100 - 2 places']\n",
131 | "response = requests.get(url)\n",
132 | "soup = bs4.BeautifulSoup(response.content, 'html.parser')\n",
133 | "script_tag = soup.find('script', id='__dkt')\n",
134 | "raw_json = re.search(r'{(.+)}', script_tag.string).group(0)\n",
135 | "data = json.loads(raw_json)\n"
136 | ]
137 | },
138 | {
139 | "cell_type": "markdown",
140 | "metadata": {},
141 | "source": [
142 | "This JSON can be explored here: https://jsonhero.io/j/QeKMElLudiaA"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": 24,
148 | "metadata": {},
149 | "outputs": [
150 | {
151 | "data": {
152 | "text/plain": [
153 | "{'rating': 4.45,\n",
154 | " 'price': 30,\n",
155 | " 'weight': '2.6',\n",
156 | " 'composition': 'Tissu principal\\n75% Polyester, 25% Polyéthylène\\nArceau\\n100% Fibre de verre',\n",
157 | " 'packed_size': 'Dimensions de la housse : 58cm x 16cm x 16cm / 15 L. Poids : 2,6 kg',\n",
158 | " 'size': 'Chambre 130 X 210 cm. (2 couchages de 65cm) Hauteur max. utile : 107 cm'}"
159 | ]
160 | },
161 | "execution_count": 24,
162 | "metadata": {},
163 | "output_type": "execute_result"
164 | }
165 | ],
166 | "source": [
167 | "benefits = {\n",
168 | " b['label']: b\n",
169 | " for b in data['_ctx']['data'][10]['data']['benefits']\n",
170 | "}\n",
171 | "{\n",
172 | " 'rating': data['_ctx']['data'][4]['data']['reviews']['notation'],\n",
173 | " 'price': data['_ctx']['data'][4]['data']['models'][0]['price'],\n",
174 | " 'weight': data['_ctx']['data'][4]['data']['models'][0]['grossWeight'],\n",
175 | " 'composition': data['_ctx']['data'][4]['data']['models'][0]['composition'],\n",
176 | " 'packed_size': benefits['Facilité de transport']['value'],\n",
177 | " 'size': benefits['Habitabilité']['value']\n",
178 | "}\n"
179 | ]
180 | },
181 | {
182 | "cell_type": "markdown",
183 | "metadata": {},
184 | "source": [
185 | "Ok great, we can extract data for a single tent. Now let's do it for all of them!\n",
186 | "\n",
187 | "First, let's list all the tents."
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": 14,
193 | "metadata": {},
194 | "outputs": [
195 | {
196 | "name": "stderr",
197 | "output_type": "stream",
198 | "text": [
199 | " 0%| | 0/11 [00:00, ?it/s]"
200 | ]
201 | },
202 | {
203 | "name": "stderr",
204 | "output_type": "stream",
205 | "text": [
206 | "100%|██████████| 11/11 [00:14<00:00, 1.36s/it]"
207 | ]
208 | },
209 | {
210 | "name": "stdout",
211 | "output_type": "stream",
212 | "text": [
213 | "Number of tents: 378\n"
214 | ]
215 | },
216 | {
217 | "name": "stderr",
218 | "output_type": "stream",
219 | "text": [
220 | "\n"
221 | ]
222 | }
223 | ],
224 | "source": [
225 | "from tqdm import tqdm\n",
226 | "\n",
227 | "tents_urls = {}\n",
228 | "\n",
229 | "def get_page_content_from_decathlon_url(url):\n",
230 | " response = requests.get(url)\n",
231 | " soup = bs4.BeautifulSoup(response.content, 'html.parser')\n",
232 | " script_tag = soup.find('script', id='__dkt')\n",
233 | " raw_json = re.search(r'{(.+)}', script_tag.string).group(0)\n",
234 | " return json.loads(raw_json)\n",
235 | "\n",
236 | "for page in tqdm(range(11)):\n",
237 | " url = f'https://www.decathlon.fr/tous-les-sports/camping-bivouac/tentes-et-abris?from={40 * page}&size={40}'\n",
238 | " data = get_page_content_from_decathlon_url(url)\n",
239 | " tents_urls.update({\n",
240 | " item['webLabel']: f\"https://www.decathlon.fr/{item['url']}\"\n",
241 | " for item in data['_ctx']['data'][idx]['data']['blocks']['items']\n",
242 | " })\n",
243 | "\n",
244 | "print(f'Number of tents: {len(tents_urls)}')\n"
245 | ]
246 | },
247 | {
248 | "cell_type": "markdown",
249 | "metadata": {},
250 | "source": [
251 | "Now we can fetch the data for each tent. There's a lot of tents, so we'll speed things by applying concurrency. We'll use Python's `concurrent.futures` module to do this."
252 | ]
253 | },
254 | {
255 | "cell_type": "code",
256 | "execution_count": 29,
257 | "metadata": {},
258 | "outputs": [
259 | {
260 | "name": "stderr",
261 | "output_type": "stream",
262 | "text": [
263 | "100%|██████████| 379/379 [00:41<00:00, 9.24it/s]\n"
264 | ]
265 | },
266 | {
267 | "data": {
268 | "text/plain": [
269 | "379"
270 | ]
271 | },
272 | "execution_count": 29,
273 | "metadata": {},
274 | "output_type": "execute_result"
275 | }
276 | ],
277 | "source": [
278 | "from concurrent.futures import ThreadPoolExecutor, as_completed\n",
279 | "\n",
280 | "tents_raw_data = {}\n",
281 | "\n",
282 | "with ThreadPoolExecutor(max_workers=5) as executor:\n",
283 | " future_to_url = {\n",
284 | " executor.submit(requests.get, tent_url): tent_name\n",
285 | " for tent_name, tent_url in tents_urls.items()\n",
286 | " }\n",
287 | " for future in tqdm(as_completed(future_to_url), total=len(future_to_url)):\n",
288 | " tent_name = future_to_url[future]\n",
289 | " tents_raw_data[tent_name] = future.result()\n",
290 | "\n",
291 | "len(tents_raw_data)\n"
292 | ]
293 | },
294 | {
295 | "cell_type": "markdown",
296 | "metadata": {},
297 | "source": [
298 | "We now have the raw data. We can now extract the data we want. It's a good idea to split the data obtention and the data extraction into two separate steps. This way, if we make a mistake in the extraction, we don't have to re-fetch the data."
299 | ]
300 | },
301 | {
302 | "cell_type": "code",
303 | "execution_count": 30,
304 | "metadata": {},
305 | "outputs": [
306 | {
307 | "name": "stderr",
308 | "output_type": "stream",
309 | "text": [
310 | "100%|██████████| 379/379 [00:12<00:00, 30.43it/s]\n"
311 | ]
312 | },
313 | {
314 | "data": {
315 | "text/plain": [
316 | "378"
317 | ]
318 | },
319 | "execution_count": 30,
320 | "metadata": {},
321 | "output_type": "execute_result"
322 | }
323 | ],
324 | "source": [
325 | "tents_info = {}\n",
326 | "\n",
327 | "for tent_name, response in tqdm(tents_raw_data.items()):\n",
328 | "\n",
329 | " soup = bs4.BeautifulSoup(response.content, 'html.parser')\n",
330 | " script_tag = soup.find('script', id='__dkt')\n",
331 | " try:\n",
332 | " raw_json = re.search(r'{(.+)}', script_tag.string).group(0)\n",
333 | " except AttributeError:\n",
334 | " continue\n",
335 | " data = json.loads(raw_json)\n",
336 | "\n",
337 | " benefits_block = next(filter(\n",
338 | " lambda b: b['type'] == 'ProductBenefits',\n",
339 | " data['_ctx']['data']\n",
340 | " ), {})\n",
341 | " details_block = next(filter(\n",
342 | " lambda b: b['type'] == 'Supermodel',\n",
343 | " data['_ctx']['data']\n",
344 | " ))\n",
345 | " benefits = {\n",
346 | " b['label']: b\n",
347 | " for b in benefits_block.get('data', {}).get('benefits', [])\n",
348 | " }\n",
349 | " tents_info[tent_name] = {\n",
350 | " 'rating': details_block['data'].get('reviews', {}).get('notation'),\n",
351 | " 'price': details_block['data']['models'][0]['price'],\n",
352 | " 'weight': details_block['data']['models'][0].get('grossWeight'),\n",
353 | " 'composition': details_block['data']['models'][0].get('composition'),\n",
354 | " 'packed_size': benefits.get('Facilité de transport', {}).get('value'),\n",
355 | " 'size': benefits.get('Habitabilité', {}).get('value')\n",
356 | " }\n",
357 | "\n",
358 | "len(tents_info)\n"
359 | ]
360 | },
361 | {
362 | "cell_type": "code",
363 | "execution_count": 15,
364 | "metadata": {},
365 | "outputs": [
366 | {
367 | "ename": "NameError",
368 | "evalue": "name 'tents_info' is not defined",
369 | "output_type": "error",
370 | "traceback": [
371 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
372 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
373 | "\u001b[1;32m/Users/max/projects/data-science-tutorials/data-mining/finding-structure/lab.ipynb Cell 16\u001b[0m line \u001b[0;36m1\n\u001b[0;32m----> 1\u001b[0m tents_df \u001b[39m=\u001b[39m pd\u001b[39m.\u001b[39mDataFrame\u001b[39m.\u001b[39mfrom_dict(tents_info, orient\u001b[39m=\u001b[39m\u001b[39m'\u001b[39m\u001b[39mindex\u001b[39m\u001b[39m'\u001b[39m)\n\u001b[1;32m 2\u001b[0m tents_df\u001b[39m.\u001b[39misnull()\u001b[39m.\u001b[39msum()\n",
374 | "\u001b[0;31mNameError\u001b[0m: name 'tents_info' is not defined"
375 | ]
376 | }
377 | ],
378 | "source": [
379 | "tents_df = pd.DataFrame.from_dict(tents_info, orient='index')\n",
380 | "tents_df.isnull().sum()\n"
381 | ]
382 | },
383 | {
384 | "cell_type": "code",
385 | "execution_count": 35,
386 | "metadata": {},
387 | "outputs": [
388 | {
389 | "data": {
390 | "text/plain": [
391 | "68"
392 | ]
393 | },
394 | "execution_count": 35,
395 | "metadata": {},
396 | "output_type": "execute_result"
397 | }
398 | ],
399 | "source": [
400 | "len(tents_df[~tents_df.isnull().any(axis=1)])\n"
401 | ]
402 | },
403 | {
404 | "cell_type": "code",
405 | "execution_count": 78,
406 | "metadata": {},
407 | "outputs": [
408 | {
409 | "data": {
410 | "text/html": [
411 | "
\n",
412 | "\n",
425 | "
\n",
426 | " \n",
427 | "
\n",
428 | "
\n",
429 | "
rating
\n",
430 | "
price
\n",
431 | "
weight
\n",
432 | "
composition
\n",
433 | "
packed_size
\n",
434 | "
size
\n",
435 | "
\n",
436 | " \n",
437 | " \n",
438 | "
\n",
439 | "
Tente à arceaux de camping - Arpenaz 4.1 - 4 Personnes - 1 Chambre
"
88 | ],
89 | "text/plain": [
90 | " description gender job\n",
91 | "Id \n",
92 | "0 She is also a Ronald D. Asmus Policy Entrepre... F professor\n",
93 | "1 He is a member of the AICPA and WICPA. Brent ... M accountant\n",
94 | "2 Dr. Aster has held teaching and research posi... M professor\n",
95 | "3 He runs a boutique design studio attending cl... M architect\n",
96 | "4 He focuses on cloud security, identity and ac... M architect"
97 | ]
98 | },
99 | "execution_count": 1,
100 | "metadata": {},
101 | "output_type": "execute_result"
102 | }
103 | ],
104 | "source": [
105 | "import pathlib\n",
106 | "import zipfile\n",
107 | "import pandas as pd\n",
108 | "\n",
109 | "data_dir = pathlib.Path('../../data/bias-in-bios.zip')\n",
110 | "\n",
111 | "with zipfile.ZipFile(data_dir, 'r') as z:\n",
112 | " with z.open('train.json') as f:\n",
113 | " train = pd.read_json(f).set_index('Id')\n",
114 | " with z.open('categories_string.csv') as f:\n",
115 | " names = pd.read_csv(f)['0'].to_dict()\n",
116 | " with z.open('train_label.csv') as f:\n",
117 | " jobs = pd.read_csv(f, index_col='Id')['Category']\n",
118 | " jobs = jobs.map(names)\n",
119 | " jobs = jobs.rename('job')\n",
120 | " train['job'] = jobs\n",
121 | "\n",
122 | "train.head()\n"
123 | ]
124 | },
125 | {
126 | "cell_type": "code",
127 | "execution_count": 2,
128 | "metadata": {},
129 | "outputs": [
130 | {
131 | "data": {
132 | "text/plain": [
133 | "'217,197'"
134 | ]
135 | },
136 | "execution_count": 2,
137 | "metadata": {},
138 | "output_type": "execute_result"
139 | }
140 | ],
141 | "source": [
142 | "f\"{len(train):,d}\"\n"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": 3,
148 | "metadata": {},
149 | "outputs": [
150 | {
151 | "data": {
152 | "text/plain": [
153 | "professor 70016\n",
154 | "attorney 18820\n",
155 | "photographer 14646\n",
156 | "nurse 12622\n",
157 | "journalist 12295\n",
158 | "physician 11607\n",
159 | "psychologist 10391\n",
160 | "teacher 9145\n",
161 | "surgeon 6616\n",
162 | "architect 5841\n",
163 | "dentist 5450\n",
164 | "painter 4621\n",
165 | "poet 4292\n",
166 | "filmmaker 4124\n",
167 | "model 4115\n",
168 | "software_engineer 4060\n",
169 | "composer 3395\n",
170 | "accountant 3121\n",
171 | "dietitian 2288\n",
172 | "comedian 1639\n",
173 | "pastor 1497\n",
174 | "chiropractor 1406\n",
175 | "paralegal 967\n",
176 | "yoga_teacher 944\n",
177 | "interior_designer 858\n",
178 | "dj 831\n",
179 | "personal_trainer 807\n",
180 | "rapper 783\n",
181 | "Name: job, dtype: int64"
182 | ]
183 | },
184 | "execution_count": 3,
185 | "metadata": {},
186 | "output_type": "execute_result"
187 | }
188 | ],
189 | "source": [
190 | "train['job'].value_counts()\n"
191 | ]
192 | },
193 | {
194 | "cell_type": "markdown",
195 | "metadata": {},
196 | "source": [
197 | "No machine learning model takes as input text directly. The text always has to be transformed. In particular, for text, the act of transforming text into a vector of numbers is called **vectorization**. There are many ways to vectorize text, but the most common one is called **TF-IDF**. Before we go into that, let's first look at a simpler method called **Bag of Words**."
198 | ]
199 | },
200 | {
201 | "cell_type": "code",
202 | "execution_count": 4,
203 | "metadata": {},
204 | "outputs": [],
205 | "source": [
206 | "from sklearn.feature_extraction.text import CountVectorizer\n",
207 | "\n",
208 | "vectorizer = CountVectorizer()\n"
209 | ]
210 | },
211 | {
212 | "cell_type": "markdown",
213 | "metadata": {},
214 | "source": [
215 | "A vectorizer does two things. First it normalizes the text:"
216 | ]
217 | },
218 | {
219 | "cell_type": "code",
220 | "execution_count": 5,
221 | "metadata": {},
222 | "outputs": [
223 | {
224 | "data": {
225 | "text/plain": [
226 | "' she is also a ronald d. asmus policy entrepreneur fellow with the german marshall fund and is a visiting fellow at the centre for international studies (cis) at the university of oxford. this commentary first appeared at sada, an online journal published by the carnegie endowment for international peace.'"
227 | ]
228 | },
229 | "execution_count": 5,
230 | "metadata": {},
231 | "output_type": "execute_result"
232 | }
233 | ],
234 | "source": [
235 | "clean = vectorizer.build_preprocessor()(train['description'][0])\n",
236 | "clean\n"
237 | ]
238 | },
239 | {
240 | "cell_type": "markdown",
241 | "metadata": {},
242 | "source": [
243 | "Next, it splits the text into tokens:"
244 | ]
245 | },
246 | {
247 | "cell_type": "code",
248 | "execution_count": 6,
249 | "metadata": {},
250 | "outputs": [
251 | {
252 | "data": {
253 | "text/plain": [
254 | "['she',\n",
255 | " 'is',\n",
256 | " 'also',\n",
257 | " 'ronald',\n",
258 | " 'asmus',\n",
259 | " 'policy',\n",
260 | " 'entrepreneur',\n",
261 | " 'fellow',\n",
262 | " 'with',\n",
263 | " 'the']"
264 | ]
265 | },
266 | "execution_count": 6,
267 | "metadata": {},
268 | "output_type": "execute_result"
269 | }
270 | ],
271 | "source": [
272 | "tokens = vectorizer.build_tokenizer()(clean)\n",
273 | "tokens[:10]\n"
274 | ]
275 | },
276 | {
277 | "cell_type": "markdown",
278 | "metadata": {},
279 | "source": [
280 | "The idea is then to build a matrix where each row corresponds to a document and each column corresponds to a token. The value of each cell is the number of times the token appears in the document. This is called a **Bag of Words** representation because we lose the order of the words in the text. We only keep track of the number of times each word appears in the text."
281 | ]
282 | },
283 | {
284 | "cell_type": "code",
285 | "execution_count": 7,
286 | "metadata": {},
287 | "outputs": [
288 | {
289 | "data": {
290 | "text/plain": [
291 | "<217197x230368 sparse matrix of type ''\n",
292 | "\twith 9851657 stored elements in Compressed Sparse Row format>"
293 | ]
294 | },
295 | "execution_count": 7,
296 | "metadata": {},
297 | "output_type": "execute_result"
298 | }
299 | ],
300 | "source": [
301 | "counts = vectorizer.fit_transform(raw_documents=train['description'])\n",
302 | "counts\n"
303 | ]
304 | },
305 | {
306 | "cell_type": "markdown",
307 | "metadata": {},
308 | "source": [
309 | "This is a sparse matrix, because that's a data structure which makes sense in this case: most documents will only contain a small subset of the tokens, so it's a waste of memory to store all the zeros. Sparse matrices are very common in text processing, so some machine learning algorithms are optimized to work with them.\n",
310 | "\n",
311 | "It's important to think about the data in terms of a sparse matrix. For instance, regular standard scaling should be avoided. Indeed, if you subtract the mean of a sparse matrix, you'll get a dense matrix, which will take a lot of memory. Instead, you should use a scaler which is aware of the sparse structure of the data, such as `MaxAbsScaler` or `MinMaxScaler`. Indeed, dividing each value by the maximum value of the row will keep the data sparse."
312 | ]
313 | },
314 | {
315 | "cell_type": "code",
316 | "execution_count": 8,
317 | "metadata": {},
318 | "outputs": [
319 | {
320 | "data": {
321 | "text/html": [
322 | "
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.