@ -0,0 +1,109 @@
|
|||||||
|
# Introduction au machine learning
|
||||||
|
|
||||||
|
[](https://youtu.be/lTd9RSxS9ZE "ML, AI, deep learning - What's the difference?")
|
||||||
|
|
||||||
|
> 🎥 Cliquer sur l'image ci-dessus afin de regarder une vidéo expliquant la différence entre machine learning, AI et deep learning.
|
||||||
|
|
||||||
|
## [Quiz préalable](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/1?loc=fr)
|
||||||
|
|
||||||
|
### Introduction
|
||||||
|
|
||||||
|
Bienvenue à ce cours sur le machine learning classique pour débutant ! Que vous soyez complètement nouveau sur ce sujet ou que vous soyez un professionnel du ML expérimenté cherchant à peaufiner vos connaissances, nous sommes heureux de vous avoir avec nous ! Nous voulons créer un tremplin chaleureux pour vos études en ML et serions ravis d'évaluer, de répondre et d'apprendre de vos retours d'[expériences](https://github.com/microsoft/ML-For-Beginners/discussions).
|
||||||
|
|
||||||
|
[](https://youtu.be/h0e2HAPTGF4 "Introduction to ML")
|
||||||
|
|
||||||
|
> 🎥 Cliquer sur l'image ci-dessus afin de regarder une vidéo: John Guttag du MIT introduit le machine learning
|
||||||
|
### Débuter avec le machine learning
|
||||||
|
|
||||||
|
Avant de commencer avec ce cours, vous aurez besoin d'un ordinateur configuré et prêt à faire tourner des notebooks (jupyter) localement.
|
||||||
|
|
||||||
|
- **Configurer votre ordinateur avec ces vidéos**. Apprendre comment configurer votre ordinateur avec cette [série de vidéos](https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6).
|
||||||
|
- **Apprendre Python**. Il est aussi recommandé d'avoir une connaissance basique de [Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa), un langage de programmaton utile pour les data scientist que nous utilisons tout au long de ce cours.
|
||||||
|
- **Apprendre Node.js et Javascript**. Nous utilisons aussi Javascript par moment dans ce cours afin de construire des applications WEB, vous aurez donc besoin de [node](https://nodejs.org) et [npm](https://www.npmjs.com/) installé, ainsi que de [Visual Studio Code](https://code.visualstudio.com/) pour développer en Python et Javascript.
|
||||||
|
- **Créer un compte GitHub**. Comme vous nous avez trouvé sur [GitHub](https://github.com), vous y avez sûrement un compte, mais si non, créez en un et répliquez ce cours afin de l'utiliser à votre grés. (N'oublier pas de nous donner une étoile aussi 😊)
|
||||||
|
- **Explorer Scikit-learn**. Familiariser vous avec [Scikit-learn](https://scikit-learn.org/stable/user_guide.html), un ensemble de librairies ML que nous mentionnons dans nos leçons.
|
||||||
|
|
||||||
|
### Qu'est-ce que le machine learning
|
||||||
|
|
||||||
|
Le terme `machine learning` est un des mots les plus populaire et le plus utilisé ces derniers temps. Il y a une probabilité accrue que vous l'ayez entendu au moins une fois si vous avez une appétence pour la technologie indépendamment du domaine dans lequel vous travaillez. Le fonctionnement du machine learning, cependant, reste un mystère pour la plupart des personnes. Pour un débutant en machine learning, le sujet peut nous submerger. Ainsi, il est important de comprendre ce qu'est le machine learning et de l'apprendre petit à petit au travers d'exemples pratiques.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> Google Trends montre la récente 'courbe de popularité' pour le mot 'machine learning'
|
||||||
|
|
||||||
|
Nous vivons dans un univers rempli de mystères fascinants. De grands scientifiques comme Stephen Hawking, Albert Einstein et pleins d'autres ont dévoués leur vie à la recherche d'informations utiles afin de dévoiler les mystères qui nous entourent. C'est la condition humaine pour apprendre : un enfant apprend de nouvelles choses et découvre la structure du monde année après année jusqu'à qu'ils deviennent adultes.
|
||||||
|
|
||||||
|
Le cerveau d'un enfant et ses sens perçoivent l'environnement qui les entourent et apprennent graduellement des schémas non observés de la vie qui vont l'aider à fabriquer des règles logiques afin d'identifier les schémas appris. Le processus d'apprentissage du cerveau humain est ce que rend les hommes comme la créature la plus sophistiquée du monde vivant. Apprendre continuellement par la découverte de schémas non observés et ensuite innover sur ces schémas nous permet de nous améliorer tout au long de notre vie. Cette capacité d'apprendre et d'évoluer est liée au concept de [plasticité neuronale](https://www.simplypsychology.org/brain-plasticity.html), nous pouvons tirer quelques motivations similaires entre le processus d'apprentissage du cerveau humain et le concept de machine learning.
|
||||||
|
|
||||||
|
Le [cerveau humain](https://www.livescience.com/29365-human-brain.html) perçoit des choses du monde réel, assimile les informations perçues, fait des décisions rationnelles et entreprend certaines actions selon le contexte. C'est ce que l'on appelle se comporter intelligemment. Lorsque nous programmons une reproduction du processus de ce comportement à une machine, c'est ce que l'on appelle intelligence artificielle (IA).
|
||||||
|
|
||||||
|
Bien que le terme peut être confu, machine learning (ML) est un important sous-ensemble de l'intelligence artificielle. **ML se réfère à l'utilisation d'algorithmes spécialisés afin de découvrir des informations utiles et de trouver des schémas non observés depuis des données perçues pour corroborer un processus de décision rationnel**.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> Un diagramme montrant les relations entre AI, ML, deep learning et data science. Infographie par [Jen Looper](https://twitter.com/jenlooper) et inspiré par [ce graphique](https://softwareengineering.stackexchange.com/questions/366996/distinction-between-ai-ml-neural-networks-deep-learning-and-data-mining)
|
||||||
|
|
||||||
|
## Ce que vous allez apprendre dans ce cours
|
||||||
|
|
||||||
|
Dans ce cours, nous allons nous concentrer sur les concepts clés du machine learning qu'un débutant se doit de connaître. Nous parlerons de ce que l'on appelle le 'machine learning classique' en utilisant principalement Scikit-learn, une excellente librairie que beaucoup d'étudiants utilisent afin d'apprendre les bases. Afin de comprendre les concepts plus larges de l'intelligence artificielle ou du deep learning, une profonde connaissance en machine learning est indispensable, et c'est ce que nous aimerions fournir ici.
|
||||||
|
|
||||||
|
Dans ce cours, vous allez apprendre :
|
||||||
|
|
||||||
|
- Les concepts clés du machine learning
|
||||||
|
- L'histoire du ML
|
||||||
|
- ML et équité (fairness)
|
||||||
|
- Les techniques de régression ML
|
||||||
|
- Les techniques de classification ML
|
||||||
|
- Les techniques de regroupement (clustering) ML
|
||||||
|
- Les techniques du traitement automatique des langues (NLP) ML
|
||||||
|
- Les techniques de prédictions à partir de séries chronologiques ML
|
||||||
|
- Apprentissage renforcé
|
||||||
|
- D'applications réels du ML
|
||||||
|
|
||||||
|
## Ce que nous ne couvrirons pas
|
||||||
|
|
||||||
|
- Deep learning
|
||||||
|
- Neural networks
|
||||||
|
- IA
|
||||||
|
|
||||||
|
Afin d'avoir la meilleur expérience d'apprentissage, nous éviterons les complexités des réseaux neuronaux, du 'deep learning' (construire un modèle utilisant plusieurs couches de réseaux neuronaux) et IA, dont nous parlerons dans un cours différent. Nous offirons aussi un cours à venir sur la data science pour concentrer sur cet aspect de champs très large.
|
||||||
|
|
||||||
|
## Pourquoi etudier le machine learning ?
|
||||||
|
|
||||||
|
Le machine learning, depuis une perspective systémique, est défini comme la création de systèmes automatiques pouvant apprendre des schémas non observés depuis des données afin d'aider à prendre des décisions intelligentes.
|
||||||
|
|
||||||
|
Ce but est faiblement inspiré de la manière dont le cerveau humain apprend certaines choses depuis les données qu'il perçoit du monde extérieur.
|
||||||
|
|
||||||
|
✅ Penser une minute aux raisons qu'une entreprise aurait d'essayer d'utiliser des stratégies de machine learning au lieu de créer des règles codés en dur.
|
||||||
|
|
||||||
|
### Les applications du machine learning
|
||||||
|
|
||||||
|
Les applications du machine learning sont maintenant pratiquement partout, et sont aussi omniprésentes que les données qui circulent autour de notre société (générés par nos smartphones, appareils connectés ou autres systèmes). En prenant en considération l'immense potentiel des algorithmes dernier cri de machine learning, les chercheurs ont pu exploités leurs capacités afin de résoudre des problèmes multidimensionnels et interdisciplinaires de la vie avec d'important retours positifs
|
||||||
|
|
||||||
|
**Vous pouvez utiliser le machine learning de plusieurs manières** :
|
||||||
|
|
||||||
|
- Afin de prédire la possibilité d'avoir une maladie à partir des données médicales d'un patient.
|
||||||
|
- Pour tirer parti des données météorologiques afin de prédire les événements météorologiques.
|
||||||
|
- Afin de comprendre le sentiment d'un texte.
|
||||||
|
- Afin de détecter les fake news pour stopper la propagation de la propagande.
|
||||||
|
|
||||||
|
La finance, l'économie, les sciences de la terre, l'exploration spatiale, le génie biomédical, les sciences cognitives et même les domaines des sciences humaines ont adapté le machine learning pour résoudre les problèmes ardus et lourds de traitement des données dans leur domaine respectif.
|
||||||
|
|
||||||
|
Le machine learning automatise le processus de découverte de modèles en trouvant des informations significatives à partir de données réelles ou générées. Il s'est avéré très utile dans les applications commerciales, de santé et financières, entre autres.
|
||||||
|
|
||||||
|
Dans un avenir proche, comprendre les bases du machine learning sera indispensable pour les personnes de tous les domaines en raison de son adoption généralisée.
|
||||||
|
|
||||||
|
---
|
||||||
|
## 🚀 Challenge
|
||||||
|
|
||||||
|
Esquisser, sur papier ou à l'aide d'une application en ligne comme [Excalidraw](https://excalidraw.com/), votre compréhension des différences entre l'IA, le ML, le deep learning et la data science. Ajouter quelques idées de problèmes que chacune de ces techniques est bonne à résoudre.
|
||||||
|
|
||||||
|
## [Quiz de validation des connaissances](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/2?loc=fr)
|
||||||
|
|
||||||
|
## Révision et auto-apprentissage
|
||||||
|
|
||||||
|
Pour en savoir plus sur la façon dont vous pouvez utiliser les algorithmes de ML dans le cloud, suivez ce [Parcours d'apprentissage](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa).
|
||||||
|
|
||||||
|
## Devoir
|
||||||
|
|
||||||
|
[Être opérationnel](assignment.fr.md)
|
@ -0,0 +1,107 @@
|
|||||||
|
# Pengantar Machine Learning
|
||||||
|
|
||||||
|
[](https://youtu.be/lTd9RSxS9ZE "ML, AI, deep learning - Apa perbedaannya?")
|
||||||
|
|
||||||
|
> 🎥 Klik gambar diatas untuk menonton video yang mendiskusikan perbedaan antara Machine Learning, AI, dan Deep Learning.
|
||||||
|
|
||||||
|
## [Quiz Pra-Pelajaran](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/1/)
|
||||||
|
|
||||||
|
### Pengantar
|
||||||
|
|
||||||
|
Selamat datang di pelajaran Machine Learning klasik untuk pemula! Baik kamu yang masih benar-benar baru, atau seorang praktisi ML berpengalaman yang ingin meningkatkan kemampuan kamu, kami senang kamu ikut bersama kami! Kami ingin membuat sebuah titik mulai yang ramah untuk pembelajaran ML kamu dan akan sangat senang untuk mengevaluasi, merespon, dan memasukkan [umpan balik](https://github.com/microsoft/ML-For-Beginners/discussions) kamu.
|
||||||
|
|
||||||
|
[](https://youtu.be/h0e2HAPTGF4 "Pengantar Machine Learning")
|
||||||
|
|
||||||
|
> 🎥 Klik gambar diatas untuk menonton video: John Guttag dari MIT yang memberikan pengantar Machine Learning.
|
||||||
|
### Memulai Machine Learning
|
||||||
|
|
||||||
|
Sebelum memulai kurikulum ini, kamu perlu memastikan komputer kamu sudah dipersiapkan untuk menjalankan *notebook* secara lokal.
|
||||||
|
|
||||||
|
- **Konfigurasi komputer kamu dengan video ini**. Pelajari bagaimana menyiapkan komputer kamu dalam [video-video](https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6) ini.
|
||||||
|
- **Belajar Python**. Disarankan juga untuk memiliki pemahaman dasar dari [Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa), sebuah bahasa pemrograman yang digunakan oleh data scientist yang juga akan kita gunakan dalam pelajaran ini.
|
||||||
|
- **Belajar Node.js dan JavaScript**. Kita juga menggunakan JavaScript beberapa kali dalam pelajaran ini ketika membangun aplikasi web, jadi kamu perlu menginstal [node](https://nodejs.org) dan [npm](https://www.npmjs.com/), serta [Visual Studio Code](https://code.visualstudio.com/) yang tersedia untuk pengembangan Python dan JavaScript.
|
||||||
|
- **Buat akun GitHub**. Karena kamu menemukan kami di [GitHub](https://github.com), kamu mungkin sudah punya akun, tapi jika belum, silakan buat akun baru kemudian *fork* kurikulum ini untuk kamu pergunakan sendiri. (Jangan ragu untuk memberikan kami bintang juga 😊)
|
||||||
|
- **Jelajahi Scikit-learn**. Buat diri kamu familiar dengan [Scikit-learn]([https://scikit-learn.org/stable/user_guide.html), seperangkat *library* ML yang kita acu dalam pelajaran-pelajaran ini.
|
||||||
|
|
||||||
|
### Apa itu Machine Learning?
|
||||||
|
|
||||||
|
Istilah 'Machine Learning' merupakan salah satu istilah yang paling populer dan paling sering digunakan saat ini. Ada kemungkinan kamu pernah mendengar istilah ini paling tidak sekali jika kamu familiar dengan teknologi. Tetapi untuk mekanisme Machine Learning sendiri, merupakan sebuah misteri bagi sebagian besar orang. Karena itu, penting untuk memahami sebenarnya apa itu Machine Learning, dan mempelajarinya langkah demi langkah melalui contoh praktis.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> Google Trends memperlihatkan 'kurva tren' dari istilah 'Machine Learning' belakangan ini.
|
||||||
|
|
||||||
|
Kita hidup di sebuah alam semesta yang penuh dengan misteri yang menarik. Ilmuwan-ilmuwan besar seperti Stephen Hawking, Albert Einstein, dan banyak lagi telah mengabdikan hidup mereka untuk mencari informasi yang berarti yang mengungkap misteri dari dunia disekitar kita. Ini adalah kondisi belajar manusia: seorang anak manusia belajar hal-hal baru dan mengungkap struktur dari dunianya tahun demi tahun saat mereka tumbuh dewasa.
|
||||||
|
|
||||||
|
Otak dan indera seorang anak memahami fakta-fakta di sekitarnya dan secara bertahap mempelajari pola-pola kehidupan yang tersembunyi yang membantu anak untuk menyusun aturan-aturan logis untuk mengidentifikasi pola-pola yang dipelajari. Proses pembelajaran otak manusia ini menjadikan manusia sebagai makhluk hidup paling canggih di dunia ini. Belajar terus menerus dengan menemukan pola-pola tersembunyi dan kemudian berinovasi pada pola-pola itu memungkinkan kita untuk terus menjadikan diri kita lebih baik sepanjang hidup. Kapasitas belajar dan kemampuan berkembang ini terkait dengan konsep yang disebut dengan *[brain plasticity](https://www.simplypsychology.org/brain-plasticity.html)*. Secara sempit, kita dapat menarik beberapa kesamaan motivasi antara proses pembelajaran otak manusia dan konsep Machine Learning.
|
||||||
|
|
||||||
|
[Otak manusia](https://www.livescience.com/29365-human-brain.html) menerima banyak hal dari dunia nyata, memproses informasi yang diterima, membuat keputusan rasional, dan melakukan aksi-aksi tertentu berdasarkan keadaan. Inilah yang kita sebut dengan berperilaku cerdas. Ketika kita memprogram sebuah salinan dari proses perilaku cerdas ke sebuah mesin, ini dinamakan kecerdasan buatan atau Artificial Intelligence (AI).
|
||||||
|
|
||||||
|
Meskipun istilah-stilahnya bisa membingungkan, Machine Learning (ML) adalah bagian penting dari Artificial Intelligence. **ML berkaitan dengan menggunakan algoritma-algoritma terspesialisasi untuk mengungkap informasi yang berarti dan mencari pola-pola tersembunyi dari data yang diterima untuk mendukung proses pembuatan keputusan rasional**.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> Sebuah diagram yang memperlihatkan hubungan antara AI, ML, Deep Learning, dan Data Science. Infografis oleh [Jen Looper](https://twitter.com/jenlooper) terinspirasi dari [infografis ini](https://softwareengineering.stackexchange.com/questions/366996/distinction-between-ai-ml-neural-networks-deep-learning-and-data-mining)
|
||||||
|
|
||||||
|
## Apa yang akan kamu pelajari
|
||||||
|
|
||||||
|
Dalam kurikulum ini, kita hanya akan membahas konsep inti dari Machine Learning yang harus diketahui oleh seorang pemula. Kita membahas apa yang kami sebut sebagai 'Machine Learning klasik' utamanya menggunakan Scikit-learn, sebuah *library* luar biasa yang banyak digunakan para siswa untuk belajar dasarnya. Untuk memahami konsep Artificial Intelligence atau Deep Learning yang lebih luas, pengetahuan dasar yang kuat tentang Machine Learning sangat diperlukan, itulah yang ingin kami tawarkan di sini.
|
||||||
|
|
||||||
|
Kamu akan belajar:
|
||||||
|
|
||||||
|
- Konsep inti ML
|
||||||
|
- Sejarah dari ML
|
||||||
|
- Keadilan dan ML
|
||||||
|
- Teknik regresi ML
|
||||||
|
- Teknik klasifikasi ML
|
||||||
|
- Teknik *clustering* ML
|
||||||
|
- Teknik *natural language processing* ML
|
||||||
|
- Teknik *time series forecasting* ML
|
||||||
|
- *Reinforcement learning*
|
||||||
|
- Penerapan nyata dari ML
|
||||||
|
## Yang tidak akan kita bahas
|
||||||
|
|
||||||
|
- *deep learning*
|
||||||
|
- *neural networks*
|
||||||
|
- AI
|
||||||
|
|
||||||
|
Untuk membuat pengalaman belajar yang lebih baik, kita akan menghindari kerumitan dari *neural network*, *deep learning* - membangun *many-layered model* menggunakan *neural network* - dan AI, yang mana akan kita bahas dalam kurikulum yang berbeda. Kami juga akan menawarkan kurikulum *data science* yang berfokus pada aspek bidang tersebut.
|
||||||
|
## Kenapa belajar Machine Learning?
|
||||||
|
|
||||||
|
Machine Learning, dari perspektif sistem, didefinisikan sebagai pembuatan sistem otomatis yang dapat mempelajari pola-pola tersembunyi dari data untuk membantu membuat keputusan cerdas.
|
||||||
|
|
||||||
|
Motivasi ini secara bebas terinspirasi dari bagaimana otak manusia mempelajari hal-hal tertentu berdasarkan data yang diterimanya dari dunia luar.
|
||||||
|
|
||||||
|
✅ Pikirkan sejenak mengapa sebuah bisnis ingin mencoba menggunakan strategi Machine Learning dibandingkan membuat sebuah mesin berbasis aturan yang tertanam (*hard-coded*).
|
||||||
|
|
||||||
|
### Penerapan Machine Learning
|
||||||
|
|
||||||
|
Penerapan Machine Learning saat ini hampir ada di mana-mana, seperti data yang mengalir di sekitar kita, yang dihasilkan oleh ponsel pintar, perangkat yang terhubung, dan sistem lainnya. Mempertimbangkan potensi besar dari algoritma Machine Learning terkini, para peneliti telah mengeksplorasi kemampuan Machine Learning untuk memecahkan masalah kehidupan nyata multi-dimensi dan multi-disiplin dengan hasil positif yang luar biasa.
|
||||||
|
|
||||||
|
**Kamu bisa menggunakan Machine Learning dalam banyak hal**:
|
||||||
|
|
||||||
|
- Untuk memprediksi kemungkinan penyakit berdasarkan riwayat atau laporan medis pasien.
|
||||||
|
- Untuk memanfaatkan data cuaca untuk memprediksi peristiwa cuaca.
|
||||||
|
- Untuk memahami sentimen sebuah teks.
|
||||||
|
- Untuk mendeteksi berita palsu untuk menghentikan penyebaran propaganda.
|
||||||
|
|
||||||
|
Keuangan, ekonomi, geosains, eksplorasi ruang angkasa, teknik biomedis, ilmu kognitif, dan bahkan bidang humaniora telah mengadaptasi Machine Learning untuk memecahkan masalah sulit pemrosesan data di bidang mereka.
|
||||||
|
|
||||||
|
Machine Learning mengotomatiskan proses penemuan pola dengan menemukan wawasan yang berarti dari dunia nyata atau dari data yang dihasilkan. Machine Learning terbukti sangat berharga dalam penerapannya di berbagai bidang, diantaranya adalah bidang bisnis, kesehatan, dan keuangan.
|
||||||
|
|
||||||
|
Dalam waktu dekat, memahami dasar-dasar Machine Learning akan menjadi suatu keharusan bagi orang-orang dari bidang apa pun karena adopsinya yang luas.
|
||||||
|
|
||||||
|
---
|
||||||
|
## 🚀 Tantangan
|
||||||
|
|
||||||
|
Buat sketsa di atas kertas atau menggunakan aplikasi seperti [Excalidraw](https://excalidraw.com/), mengenai pemahaman kamu tentang perbedaan antara AI, ML, Deep Learning, dan Data Science. Tambahkan beberapa ide masalah yang cocok diselesaikan masing-masing teknik.
|
||||||
|
|
||||||
|
## [Quiz Pasca-Pelajaran](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/2/)
|
||||||
|
|
||||||
|
## Ulasan & Belajar Mandiri
|
||||||
|
|
||||||
|
Untuk mempelajari lebih lanjut tentang bagaimana kamu dapat menggunakan algoritma ML di cloud, ikuti [Jalur Belajar](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa) ini.
|
||||||
|
|
||||||
|
## Tugas
|
||||||
|
|
||||||
|
[Persiapan](assignment.id.md)
|
@ -0,0 +1,9 @@
|
|||||||
|
# Lévantate y corre
|
||||||
|
|
||||||
|
## Instrucciones
|
||||||
|
|
||||||
|
En esta tarea no calificada, debe repasar Python y hacer que su entorno esté en funcionamiento y sea capaz de ejecutar cuadernos.
|
||||||
|
|
||||||
|
Tome esta [Ruta de aprendizaje de Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa), y luego configure sus sistemas con estos videos introductorios:
|
||||||
|
|
||||||
|
https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6
|
@ -0,0 +1,10 @@
|
|||||||
|
# Être opérationnel
|
||||||
|
|
||||||
|
|
||||||
|
## Instructions
|
||||||
|
|
||||||
|
Dans ce devoir non noté, vous devez vous familiariser avec Python et rendre votre environnement opérationnel et capable d'exécuter des notebook.
|
||||||
|
|
||||||
|
Suivez ce [parcours d'apprentissage Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa), puis configurez votre système en parcourant ces vidéos introductives :
|
||||||
|
|
||||||
|
https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6
|
@ -0,0 +1,9 @@
|
|||||||
|
# Persiapan
|
||||||
|
|
||||||
|
## Instruksi
|
||||||
|
|
||||||
|
Dalam tugas yang tidak dinilai ini, kamu akan mempelajari Python dan mempersiapkan *environment* kamu sehingga dapat digunakan untuk menjalankan *notebook*.
|
||||||
|
|
||||||
|
Ambil [Jalur Belajar Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa) ini, kemudian persiapkan sistem kamu dengan menonton video-video pengantar ini:
|
||||||
|
|
||||||
|
https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6
|
@ -0,0 +1,116 @@
|
|||||||
|
# Sejarah Machine Learning
|
||||||
|
|
||||||
|

|
||||||
|
> Catatan sketsa oleh [Tomomi Imura](https://www.twitter.com/girlie_mac)
|
||||||
|
|
||||||
|
## [Quiz Pra-Pelajaran](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/3/)
|
||||||
|
|
||||||
|
Dalam pelajaran ini, kita akan membahas tonggak utama dalam sejarah Machine Learning dan Artificial Intelligence.
|
||||||
|
|
||||||
|
Sejarah Artifical Intelligence, AI, sebagai bidang terkait dengan sejarah Machine Learning, karena algoritma dan kemajuan komputasi yang mendukung ML dimasukkan ke dalam pengembangan AI. Penting untuk diingat bahwa, meski bidang-bidang ini sebagai bidang-bidang penelitian yang berbeda mulai terbentuk pada 1950-an, [algoritmik, statistik, matematik, komputasi dan penemuan teknis](https://wikipedia.org/wiki/Timeline_of_machine_learning) penting sudah ada sebelumnya, dan saling tumpang tindih di era ini. Faktanya, orang-orang telah memikirkan pertanyaan-pertanyaan ini selama [ratusan tahun](https://wikipedia.org/wiki/History_of_artificial_intelligence): artikel ini membahas dasar-dasar intelektual historis dari gagasan 'mesin yang berpikir'.
|
||||||
|
|
||||||
|
## Penemuan penting
|
||||||
|
|
||||||
|
- 1763, 1812 [Bayes Theorem](https://wikipedia.org/wiki/Bayes%27_theorem) dan para pendahulu. Teorema ini dan penerapannya mendasari inferensi, mendeskripsikan kemungkinan suatu peristiwa terjadi berdasarkan pengetahuan sebelumnya.
|
||||||
|
- 1805 [Least Square Theory](https://wikipedia.org/wiki/Least_squares) oleh matematikawan Perancis Adrien-Marie Legendre. Teori ini yang akan kamu pelajari di unit Regresi, ini membantu dalam *data fitting*.
|
||||||
|
- 1913 [Markov Chains](https://wikipedia.org/wiki/Markov_chain) dinamai dengan nama matematikawan Rusia, Andrey Markov, digunakan untuk mendeskripsikan sebuah urutan dari kejadian-kejadian yang mungkin terjadi berdasarkan kondisi sebelumnya.
|
||||||
|
- 1957 [Perceptron](https://wikipedia.org/wiki/Perceptron) adalah sebuah tipe dari *linear classifier* yang ditemukan oleh psikolog Amerika, Frank Rosenblatt, yang mendasari kemajuan dalam *Deep Learning*.
|
||||||
|
- 1967 [Nearest Neighbor](https://wikipedia.org/wiki/Nearest_neighbor) adalah sebuah algoritma yang pada awalnya didesain untuk memetakan rute. Dalam konteks ML, ini digunakan untuk mendeteksi berbagai pola.
|
||||||
|
- 1970 [Backpropagation](https://wikipedia.org/wiki/Backpropagation) digunakan untuk melatih [feedforward neural networks](https://wikipedia.org/wiki/Feedforward_neural_network).
|
||||||
|
- 1982 [Recurrent Neural Networks](https://wikipedia.org/wiki/Recurrent_neural_network) adalah *artificial neural networks* yang berasal dari *feedforward neural networks* yang membuat grafik sementara.
|
||||||
|
|
||||||
|
✅ Lakukan sebuah riset kecil. Tanggal berapa lagi yang merupakan tanggal penting dalam sejarah ML dan AI?
|
||||||
|
## 1950: Mesin yang berpikir
|
||||||
|
|
||||||
|
Alan Turing, merupakan orang luar biasa yang terpilih oleh [publik di tahun 2019](https://wikipedia.org/wiki/Icons:_The_Greatest_Person_of_the_20th_Century) sebagai ilmuwan terhebat di abad 20, diberikan penghargaan karena membantu membuat fondasi dari sebuah konsep 'mesin yang bisa berpikir', Dia berjuang menghadapi orang-orang yang menentangnya dan keperluannya sendiri untuk bukti empiris dari konsep ini dengan membuat [Turing Test](https://www.bbc.com/news/technology-18475646), yang mana akan kamu jelajahi di pelajaran NLP kami.
|
||||||
|
|
||||||
|
## 1956: Proyek Riset Musim Panas Dartmouth
|
||||||
|
|
||||||
|
"Proyek Riset Musim Panas Dartmouth pada *artificial intelligence* merupakan sebuah acara penemuan untuk *artificial intelligence* sebagai sebuah bidang," dan dari sinilah istilah '*artificial intelligence*' diciptakan ([sumber](https://250.dartmouth.edu/highlights/artificial-intelligence-ai-coined-dartmouth)).
|
||||||
|
|
||||||
|
> Setiap aspek pembelajaran atau fitur kecerdasan lainnya pada prinsipnya dapat dideskripsikan dengan sangat tepat sehingga sebuah mesin dapat dibuat untuk mensimulasikannya.
|
||||||
|
|
||||||
|
Ketua peneliti, profesor matematika John McCarthy, berharap "untuk meneruskan dasar dari dugaan bahwa setiap aspek pembelajaran atau fitur kecerdasan lainnya pada prinsipnya dapat dideskripsikan dengan sangat tepat sehingga mesin dapat dibuat untuk mensimulasikannya." Marvin Minsky, seorang tokoh terkenal di bidang ini juga termasuk sebagai peserta penelitian.
|
||||||
|
|
||||||
|
Workshop ini dipuji karena telah memprakarsai dan mendorong beberapa diskusi termasuk "munculnya metode simbolik, sistem yang berfokus pada domain terbatas (sistem pakar awal), dan sistem deduktif versus sistem induktif." ([sumber](https://wikipedia.org/wiki/Dartmouth_workshop)).
|
||||||
|
|
||||||
|
## 1956 - 1974: "Tahun-tahun Emas"
|
||||||
|
|
||||||
|
Dari tahun 1950-an hingga pertengahan 70-an, optimisme memuncak dengan harapan bahwa AI dapat memecahkan banyak masalah. Pada tahun 1967, Marvin Minsky dengan yakin menyatakan bahwa "Dalam satu generasi ... masalah menciptakan '*artificial intelligence*' akan terpecahkan secara substansial." (Minsky, Marvin (1967), Computation: Finite and Infinite Machines, Englewood Cliffs, N.J.: Prentice-Hall)
|
||||||
|
|
||||||
|
Penelitian *natural language processing* berkembang, pencarian disempurnakan dan dibuat lebih *powerful*, dan konsep '*micro-worlds*' diciptakan, di mana tugas-tugas sederhana diselesaikan menggunakan instruksi bahasa sederhana.
|
||||||
|
|
||||||
|
Penelitian didanai dengan baik oleh lembaga pemerintah, banyak kemajuan dibuat dalam komputasi dan algoritma, dan prototipe mesin cerdas dibangun. Beberapa mesin tersebut antara lain:
|
||||||
|
|
||||||
|
* [Shakey the robot](https://wikipedia.org/wiki/Shakey_the_robot), yang bisa bermanuver dan memutuskan bagaimana melakukan tugas-tugas secara 'cerdas'.
|
||||||
|
|
||||||
|

|
||||||
|
> Shakey pada 1972
|
||||||
|
|
||||||
|
* Eliza, sebuah 'chatterbot' awal, dapat mengobrol dengan orang-orang dan bertindak sebagai 'terapis' primitif. Kamu akan belajar lebih banyak tentang Eliza dalam pelajaran NLP.
|
||||||
|
|
||||||
|

|
||||||
|
> Sebuah versi dari Eliza, sebuah *chatbot*
|
||||||
|
|
||||||
|
* "Blocks world" adalah contoh sebuah *micro-world* dimana balok dapat ditumpuk dan diurutkan, dan pengujian eksperimen mesin pengajaran untuk membuat keputusan dapat dilakukan. Kemajuan yang dibuat dengan *library-library* seperti [SHRDLU](https://wikipedia.org/wiki/SHRDLU) membantu mendorong kemajuan pemrosesan bahasa.
|
||||||
|
|
||||||
|
[](https://www.youtube.com/watch?v=QAJz4YKUwqw "blocks world dengan SHRDLU")
|
||||||
|
|
||||||
|
> 🎥 Klik gambar diatas untuk menonton video: Blocks world with SHRDLU
|
||||||
|
|
||||||
|
## 1974 - 1980: "Musim Dingin AI"
|
||||||
|
|
||||||
|
Pada pertengahan 1970-an, semakin jelas bahwa kompleksitas pembuatan 'mesin cerdas' telah diremehkan dan janjinya, mengingat kekuatan komputasi yang tersedia, telah dilebih-lebihkan. Pendanaan telah habis dan kepercayaan dalam bidang ini menurun. Beberapa masalah yang memengaruhi kepercayaan diri termasuk:
|
||||||
|
|
||||||
|
- **Keterbatasan**. Kekuatan komputasi terlalu terbatas.
|
||||||
|
- **Ledakan kombinatorial**. Jumlah parameter yang perlu dilatih bertambah secara eksponensial karena lebih banyak hal yang diminta dari komputer, tanpa evolusi paralel dari kekuatan dan kemampuan komputasi.
|
||||||
|
- **Kekurangan data**. Adanya kekurangan data yang menghalangi proses pengujian, pengembangan, dan penyempurnaan algoritma.
|
||||||
|
- **Apakah kita menanyakan pertanyaan yang tepat?**. Pertanyaan-pertanyaan yang diajukan pun mulai dipertanyakan kembali. Para peneliti mulai melontarkan kritik tentang pendekatan mereka
|
||||||
|
- Tes Turing mulai dipertanyakan, di antara ide-ide lain, dari 'teori ruang Cina' yang mengemukakan bahwa, "memprogram komputer digital mungkin membuatnya tampak memahami bahasa tetapi tidak dapat menghasilkan pemahaman yang sebenarnya." ([sumber](https://plato.stanford.edu/entries/chinese-room/))
|
||||||
|
- Tantangan etika ketika memperkenalkan kecerdasan buatan seperti si "terapis" ELIZA ke dalam masyarakat.
|
||||||
|
|
||||||
|
Pada saat yang sama, berbagai aliran pemikiran AI mulai terbentuk. Sebuah dikotomi didirikan antara praktik ["scruffy" vs. "neat AI"](https://wikipedia.org/wiki/Neats_and_scruffies). Lab _Scruffy_ mengubah program selama berjam-jam sampai mendapat hasil yang diinginkan. Lab _Neat_ "berfokus pada logika dan penyelesaian masalah formal". ELIZA dan SHRDLU adalah sistem _scruffy_ yang terkenal. Pada tahun 1980-an, karena perkembangan permintaan untuk membuat sistem ML yang dapat direproduksi, pendekatan _neat_ secara bertahap menjadi yang terdepan karena hasilnya lebih dapat dijelaskan.
|
||||||
|
|
||||||
|
## 1980s Sistem Pakar
|
||||||
|
|
||||||
|
Seiring berkembangnya bidang ini, manfaatnya bagi bisnis menjadi lebih jelas, dan begitu pula dengan menjamurnya 'sistem pakar' pada tahun 1980-an. "Sistem pakar adalah salah satu bentuk perangkat lunak artificial intelligence (AI) pertama yang benar-benar sukses." ([sumber](https://wikipedia.org/wiki/Expert_system)).
|
||||||
|
|
||||||
|
Tipe sistem ini sebenarnya adalah _hybrid_, sebagian terdiri dari mesin aturan yang mendefinisikan kebutuhan bisnis, dan mesin inferensi yang memanfaatkan sistem aturan untuk menyimpulkan fakta baru.
|
||||||
|
|
||||||
|
Pada era ini juga terlihat adanya peningkatan perhatian pada jaringan saraf.
|
||||||
|
|
||||||
|
## 1987 - 1993: AI 'Chill'
|
||||||
|
|
||||||
|
Perkembangan perangkat keras sistem pakar terspesialisasi memiliki efek yang tidak menguntungkan karena menjadi terlalu terspesialiasasi. Munculnya komputer pribadi juga bersaing dengan sistem yang besar, terspesialisasi, dan terpusat ini. Demokratisasi komputasi telah dimulai, dan pada akhirnya membuka jalan untuk ledakan modern dari *big data*.
|
||||||
|
|
||||||
|
## 1993 - 2011
|
||||||
|
|
||||||
|
Pada zaman ini memperlihatkan era baru bagi ML dan AI untuk dapat menyelesaikan beberapa masalah yang sebelumnya disebabkan oleh kurangnya data dan daya komputasi. Jumlah data mulai meningkat dengan cepat dan tersedia secara luas, terlepas dari baik dan buruknya, terutama dengan munculnya *smartphone* sekitar tahun 2007. Daya komputasi berkembang secara eksponensial, dan algoritma juga berkembang saat itu. Bidang ini mulai mengalami kedewasaan karena hari-hari yang tidak beraturan di masa lalu mulai terbentuk menjadi disiplin yang sebenarnya.
|
||||||
|
|
||||||
|
## Sekarang
|
||||||
|
|
||||||
|
Saat ini, *machine learning* dan AI hampir ada di setiap bagian dari kehidupan kita. Era ini menuntut pemahaman yang cermat tentang risiko dan efek potensi dari berbagai algoritma yang ada pada kehidupan manusia. Seperti yang telah dinyatakan oleh Brad Smith dari Microsoft, "Teknologi informasi mengangkat isu-isu yang menjadi inti dari perlindungan hak asasi manusia yang mendasar seperti privasi dan kebebasan berekspresi. Masalah-masalah ini meningkatkan tanggung jawab bagi perusahaan teknologi yang menciptakan produk-produk ini. Dalam pandangan kami, mereka juga menyerukan peraturan pemerintah yang bijaksana dan untuk pengembangan norma-norma seputar penggunaan yang wajar" ([sumber](https://www.technologyreview.com/2019/12/18/102365/the-future-of-ais-impact-on-society/)).
|
||||||
|
|
||||||
|
Kita masih belum tahu apa yang akan terjadi di masa depan, tetapi penting untuk memahami sistem komputer dan perangkat lunak serta algoritma yang dijalankannya. Kami berharap kurikulum ini akan membantu kamu untuk mendapatkan pemahaman yang lebih baik sehingga kamu dapat memutuskan sendiri.
|
||||||
|
|
||||||
|
[](https://www.youtube.com/watch?v=mTtDfKgLm54 "Sejarah Deep Learning")
|
||||||
|
> 🎥 Klik gambar diatas untuk menonton video: Yann LeCun mendiskusikan sejarah dari Deep Learning dalam pelajaran ini
|
||||||
|
|
||||||
|
---
|
||||||
|
## 🚀Tantangan
|
||||||
|
|
||||||
|
Gali salah satu momen bersejarah ini dan pelajari lebih lanjut tentang orang-orang di baliknya. Ada karakter yang menarik, dan tidak ada penemuan ilmiah yang pernah dibuat dalam kekosongan budaya. Apa yang kamu temukan?
|
||||||
|
|
||||||
|
## [Quiz Pasca-Pelajaran](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/4/)
|
||||||
|
|
||||||
|
## Ulasan & Belajar Mandiri
|
||||||
|
|
||||||
|
Berikut adalah item untuk ditonton dan didengarkan:
|
||||||
|
|
||||||
|
[Podcast dimana Amy Boyd mendiskusikan evolusi dari AI](http://runasradio.com/Shows/Show/739)
|
||||||
|
|
||||||
|
[](https://www.youtube.com/watch?v=EJt3_bFYKss "Sejarah AI oleh Amy Boyd")
|
||||||
|
|
||||||
|
## Tugas
|
||||||
|
|
||||||
|
[Membuat sebuah *timeline*](assignment.id.md)
|
@ -0,0 +1,11 @@
|
|||||||
|
# Créer une frise chronologique
|
||||||
|
|
||||||
|
## Instructions
|
||||||
|
|
||||||
|
Utiliser [ce repo](https://github.com/Digital-Humanities-Toolkit/timeline-builder), créer une frise chronologique de certains aspects de l'histoire des algorithmes, des mathématiques, des statistiques, de l'IA ou du machine learning, ou une combinaison de ceux-ci. Vous pouvez vous concentrer sur une personne, une idée ou une longue période d'innovations. Assurez-vous d'ajouter des éléments multimédias.
|
||||||
|
|
||||||
|
## Rubrique
|
||||||
|
|
||||||
|
| Critères | Exemplaire | Adéquate | A améliorer |
|
||||||
|
| -------- | ---------------------------------------------------------------- | ------------------------------------ | ------------------------------------------------------------------ |
|
||||||
|
| | Une chronologie déployée est présentée sous forme de page GitHub | Le code est incomplet et non déployé | La chronologie est incomplète, pas bien recherchée et pas déployée |
|
@ -0,0 +1,11 @@
|
|||||||
|
# Membuat sebuah *timeline*
|
||||||
|
|
||||||
|
## Instruksi
|
||||||
|
|
||||||
|
Menggunakan [repo ini](https://github.com/Digital-Humanities-Toolkit/timeline-builder), buatlah sebuah *timeline* dari beberapa aspek sejarah algoritma, matematika, statistik, AI, atau ML, atau kombinasi dari semuanya. Kamu dapat fokus pada satu orang, satu ide, atau rentang waktu pemikiran yang panjang. Pastikan untuk menambahkan elemen multimedia.
|
||||||
|
|
||||||
|
## Rubrik
|
||||||
|
|
||||||
|
| Kriteria | Sangat Bagus | Cukup | Perlu Peningkatan |
|
||||||
|
| -------- | ------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------- |
|
||||||
|
| | *Timeline* yang dideploy disajikan sebagai halaman GitHub | Kode belum lengkap dan belum dideploy | *Timeline* belum lengkap, belum diriset dengan baik dan belum dideploy |
|
@ -0,0 +1,11 @@
|
|||||||
|
# 年表を作成する
|
||||||
|
|
||||||
|
## 指示
|
||||||
|
|
||||||
|
[このリポジトリ](https://github.com/Digital-Humanities-Toolkit/timeline-builder) を使って、アルゴリズム・数学・統計学・人工知能・機械学習、またはこれらの組み合わせに対して、歴史のひとつの側面に関する年表を作成してください。焦点を当てるのは、ひとりの人物・ひとつのアイディア・長期間にわたる思想のいずれのものでも構いません。マルチメディアの要素を必ず加えるようにしてください。
|
||||||
|
|
||||||
|
## 評価基準
|
||||||
|
|
||||||
|
| 基準 | 模範的 | 十分 | 要改善 |
|
||||||
|
| ---- | -------------------------------------- | ------------------------------------ | ------------------------------------------------------------ |
|
||||||
|
| | GitHub page に年表がデプロイされている | コードが未完成でデプロイされていない | 年表が未完成で、十分に調査されておらず、デプロイされていない |
|
@ -0,0 +1,11 @@
|
|||||||
|
# 建立一个时间轴
|
||||||
|
|
||||||
|
## 说明
|
||||||
|
|
||||||
|
使用这个 [仓库](https://github.com/Digital-Humanities-Toolkit/timeline-builder),创建一个关于算法、数学、统计学、人工智能、机器学习的某个方面或者可以综合多个以上学科来讲。你可以着重介绍某个人,某个想法,或者一个经久不衰的思想。请确保添加了多媒体元素在你的时间线中。
|
||||||
|
|
||||||
|
## 评判标准
|
||||||
|
|
||||||
|
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
|
||||||
|
| ------------ | ---------------------------------- | ---------------------- | ------------------------------------------ |
|
||||||
|
| | 有一个用 GitHub page 展示的 timeline | 代码还不完整并且没有部署 | 时间线不完整,没有经过充分的研究,并且没有部署 |
|
@ -0,0 +1,11 @@
|
|||||||
|
# Explore Fairlearn
|
||||||
|
|
||||||
|
## Instrucciones
|
||||||
|
|
||||||
|
En esta lección, aprendió sobre Fairlearn, un "proyecto open-source impulsado por la comunidad para ayudar a los científicos de datos a mejorar la equidad de los sistemas de AI." Para esta tarea, explore uno de los [cuadernos](https://fairlearn.org/v0.6.2/auto_examples/index.html) de Fairlearn e informe sus hallazgos en un documento o presentación.
|
||||||
|
|
||||||
|
## Rúbrica
|
||||||
|
|
||||||
|
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
|
||||||
|
| -------- | --------- | -------- | ----------------- |
|
||||||
|
| | Un documento o presentación powerpoint es presentado discutiendo los sistemas de Fairlearn, el cuadernos que fue ejecutado, y las conclusiones extraídas al ejecutarlo | Un documento es presentado sin conclusiones | No se presenta ningún documento |
|
@ -0,0 +1,11 @@
|
|||||||
|
# Jelajahi Fairlearn
|
||||||
|
|
||||||
|
## Instruksi
|
||||||
|
|
||||||
|
Dalam pelajaran ini kamu telah belajar mengenai Fairlearn, sebuah "proyek *open-source* berbasis komunitas untuk membantu para *data scientist* meningkatkan keadilan dari sistem AI." Untuk penugasan kali ini, jelajahi salah satu dari [notebook](https://fairlearn.org/v0.6.2/auto_examples/index.html) yang disediakan Fairlearn dan laporkan penemuanmu dalam sebuah paper atau presentasi.
|
||||||
|
|
||||||
|
## Rubrik
|
||||||
|
|
||||||
|
| Kriteria | Sangat Bagus | Cukup | Perlu Peningkatan |
|
||||||
|
| -------- | --------- | -------- | ----------------- |
|
||||||
|
| | Sebuah *paper* atau presentasi powerpoint yang membahas sistem Fairlearn, *notebook* yang dijalankan, dan kesimpulan yang diambil dari hasil menjalankannya | Sebuah paper yang dipresentasikan tanpa kesimpulan | Tidak ada paper yang dipresentasikan |
|
@ -0,0 +1,107 @@
|
|||||||
|
# Técnicas de Machine Learning
|
||||||
|
|
||||||
|
El proceso de creación, uso y mantenimiento de modelos de machine learning, y los datos que se utilizan, es un proceso muy diferente de muchos otros flujos de trabajo de desarrollo. En esta lección, demistificaremos el proceso, y describiremos las principales técnicas que necesita saber. Vas a:
|
||||||
|
|
||||||
|
- Comprender los procesos que sustentan el machine learning a un alto nivel.
|
||||||
|
- Explorar conceptos básicos como 'modelos', 'predicciones', y 'datos de entrenamiento'
|
||||||
|
|
||||||
|
|
||||||
|
## [Cuestionario previo a la conferencia](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/7/)
|
||||||
|
## Introducción
|
||||||
|
|
||||||
|
A un alto nivel, el arte de crear procesos de machine learning (ML) se compone de una serie de pasos:
|
||||||
|
|
||||||
|
1. **Decidir sobre la pregunta**. La mayoría de los procesos de ML, comienzan por hacer una pregunta que no puede ser respondida por un simple programa condicional o un motor basado en reglas. Esas preguntas a menudo giran en torno a predicciones basadas en una recopilación de datos.
|
||||||
|
2. **Recopile y prepare datos**. Para poder responder a su pregunta, necesita datos. La calidad y, a veces, cantidad de sus datos determinarán que tan bien puede responder a su pregunta inicial. La visualización de datos es un aspecto importante de esta fase. Esta fase también incluye dividir los datos en un grupo de entrenamiento y pruebas para construir un modelo.
|
||||||
|
3. **Elige un método de entrenamiento**. Dependiendo de su pregunta y la naturaleza de sus datos, debe elegir cómo desea entrenar un modelo para reflejar mejor sus datos y hacer predicciones precisas contra ellos. Esta es la parte de su proceso de ML que requiere experiencia específica y, a menudo, una cantidad considerable de experimetación.
|
||||||
|
4. **Entrena el model**. Usando sus datos de entrenamiento, usará varios algoritmos para entrenar un modelo para reconocer patrones en los datos. El modelo puede aprovechar las ponderaciones internas que se pueden ajustar para privilegiar ciertas partes de los datos sobre otras para construir un modelo mejor.
|
||||||
|
5. **Evaluar el modelo**. Utiliza datos nunca antes vistos (sus datos de prueba) de su conjunto recopilado para ver cómo se está desempeñando el modelo.
|
||||||
|
6. **Ajuste de parámetros**. Según el rendimiento de su modelo, puede rehacer el proceso utilizando diferentes parámetros, o variables, que controlan el comportamiento de los algoritmos utlizados para entrenarl el modelo.
|
||||||
|
7. **Predecir**. Utilice nuevas entradas para probar la precisión de su modelo.
|
||||||
|
|
||||||
|
## Que pregunta hacer
|
||||||
|
|
||||||
|
Las computadoras son particularmente hábiles para descubrir patrones ocultos en los datos. Esta utlidad es muy útil para los investigadores que tienen preguntas sobre un dominio determinado que no pueden responderse fácilmente mediante la creación de un motor de reglas basado en condicionales. Dada una tarea actuarial, por ejemplo, un científico de datos podría construir reglas artesanales sobre la mortalidad de los fumadores frente a los no fumadores.
|
||||||
|
|
||||||
|
Sin embargo, cuandos se incorporan muchas otras variables a la ecuación, un modelo de ML podría resultar más eficiente para predecir las tasas de mortalidad futuras en funciòn de los antecedentes de salud. Un ejemplo más alegre podría hacer predicciones meteorólogicas para el mes de abril en una ubicación determinada que incluya latitud, longitud, cambio climático, proximidad al océano, patrones de la corriente en chorro, y más.
|
||||||
|
|
||||||
|
✅ Esta [presentación de diapositivas](https://www2.cisl.ucar.edu/sites/default/files/0900%20June%2024%20Haupt_0.pdf) sobre modelos meteorológicos ofrece una perspectiva histórica del uso de ML en el análisis meteorológico.
|
||||||
|
|
||||||
|
## Tarea previas a la construcción
|
||||||
|
|
||||||
|
Antes de comenzar a construir su modelo, hay varias tareas que debe comletar. Para probar su pregunta y formar una hipótesis basada en las predicciones de su modelo, debe identificar y configurar varios elementos.
|
||||||
|
|
||||||
|
### Datos
|
||||||
|
|
||||||
|
Para poder responder su pregunta con cualquier tipo de certeza, necesita una buena cantidad de datos del tipo correcto.
|
||||||
|
Hay dos cosas que debe hacer en este punto:
|
||||||
|
|
||||||
|
- **Recolectar datos**. Teniendo en cuenta la lección anterior sobre la equidad en el análisis de datos, recopile sus datos con cuidado. Tenga en cuenta la fuente de estos datos, cualquier sesgo inherente que pueda tener y documente su origen.
|
||||||
|
- **Preparar datos**. Hay varios pasos en el proceso de preparación de datos. Podría necesitar recopilar datos y normalizarlos si provienen de diversas fuentes. Puede mejorar la calidad y cantidad de los datos mediante varios métodos, como convertir strings en números (como hacemos en [Clustering](../../5-Clustering/1-Visualize/README.md)). También puede generar nuevos datos, basados en los originales (como hacemos en [Clasificación](../../4-Classification/1-Introduction/README.md)). Puede limpiar y editar los datos (como lo haremos antes de la lección [Web App](../../3-Web-App/README.md)). Por último, es posible que también deba aleotizarlo y mezclarlo, según sus técnicas de entrenamiento.
|
||||||
|
|
||||||
|
✅ Despúes de recopilar y procesar sus datos, tómese un momento para ver si su forma le permitirá responder a su pregunta. ¡Puede ser que los datos no funcionen bien en su tarea dada, como descubriremos en nuestras lecciones de[Clustering](../../5-Clustering/1-Visualize/README.md)!
|
||||||
|
|
||||||
|
### Seleccionando su variable característica
|
||||||
|
|
||||||
|
Una [característica](https://www.datasciencecentral.com/profiles/blogs/an-introduction-to-variable-and-feature-selection) es una propiedad medible de sus datos. En muchos conjuntos de datos, se expresa como un encabezado de columna como 'fecha', 'tamaño' o 'color'. Su variable característica, generalmente representada como `y` en el código, representa la respuesta a la pregunta que está tratando de hacer a sus datos: en diciembre, ¿qué calabazas de **color** serán las más baratas?, en San Francisco, ¿que vecinadarios tendrán el mejor **precio** de bienes raíces?
|
||||||
|
|
||||||
|
🎓 **Selección y extracción de características** ¿ Cómo sabe que variable elegir al construir un modelo? Probablemente pasará por un proceso de selección o extracción de características para elegir las variables correctas para mayor un mayor rendimiento del modelo. Sin embargo, no son lo mismo: "La extracción de características crea nuevas características a partir de funciones de las características originales, mientras que la selección de características devuelve un subconjunto de las características." ([fuente](https://wikipedia.org/wiki/Feature_selection))
|
||||||
|
|
||||||
|
### Visualiza tus datos
|
||||||
|
|
||||||
|
Un aspecto importante del conjunto de herramientas del científico de datos es el poder de visualizar datos utilizando varias bibliotecas excelentes como Seaborn o MatPlotLib. Representar sus datos visualmente puede permitirle descubrir correlaciones ocultas que puede aprovechar. Sus visualizaciones también pueden ayudarlo a descubrir sesgos o datos desequilibrados. (como descubrimos en [Clasificación](../../4-Classification/2-Classifiers-1/README.md)).
|
||||||
|
|
||||||
|
### Divide tu conjunto de datos
|
||||||
|
|
||||||
|
Antes del entrenamiento, debe dividir su conjunto de datos en dos o más partes de tamaño desigual que aún represente bien los datos.
|
||||||
|
|
||||||
|
- **Entrenamiento**. Esta parte del conjunto de datos se ajusta a su modelo para entrenarlo. Este conjunto constituye la mayor parte del conjunto de datos original.
|
||||||
|
- **Pruebas**. Un conjunto de datos de pruebas es un grupo independiente de datos, a menudo recopilado a partir de los datos originales, que se utiliza para confirmar el rendimiento del modelo construido.
|
||||||
|
- **Validación**. Un conjunto de validación es un pequeño grupo independiente de ejemplos que se usa para ajustar los hiperparámetros o la arquitectura del modelo para mejorar el modelo. Dependiendo del tamaño de de su conjunto de datos y de la pregunta que se está haciendo, es posible que no necesite crear este tercer conjunto (como notamos en [Pronóstico se series de tiempo](../../7-TimeSeries/1-Introduction/README.md)).
|
||||||
|
|
||||||
|
## Contruye un modelo
|
||||||
|
|
||||||
|
Usando sus datos de entrenamiento, su objetivo es construir un modelo, o una representación estadística de sus datos, usando varios algoritmos para **entrenarlo**. El entrenamiento de un modelo lo expone a los datos y le permite hacer suposiciones sobre los patrones percibidos que descubre, valida y rechaza.
|
||||||
|
|
||||||
|
### Decide un método de entrenamiento
|
||||||
|
|
||||||
|
Dependiendo de su pregunta y la naturaleza de sus datos, elegirá un método para entrenarlos. Pasando por la [documentación de Scikit-learn ](https://scikit-learn.org/stable/user_guide.html) - que usamos en este curso - puede explorar muchas formas de entrenar un modelo. Dependiendo de su experiencia, es posible que deba probar varios métodos diferentes para construir el mejor modelo. Es probable que pase por un proceso en el que los científicos de datos evalúan el rendimiento de un modelo alimentándolo con datos no vistos anteriormente por el modelo, verificando la precisión, el sesgo, y otros problemas que degradan la calidad, y seleccionando el método de entrenamieto más apropiado para la tarea en custión.
|
||||||
|
### Entrena un modelo
|
||||||
|
|
||||||
|
Armado con sus datos de entrenamiento, está listo para 'fit'(ajustarlos/entrenarlos) para crear un modelo. Notará que en muchas bibliotecas de ML, encontrará el código 'model.fit' - es en este momento cuando envías sus datos como una matriz de valores (generalmente 'X') y una variable característica (generalmente 'Y').
|
||||||
|
### Evaluar el modelo
|
||||||
|
|
||||||
|
Una vez que se completa el proceso de entrenamiento (puede tomar muchas iteraciones, o 'épocas', entrenar un modelo de gran tamaño), podrá evaluar la calidad del modelo utilizando datos de prueba para medir su rendimiento. Estos datos son un subconjunto de los datos originales que el modelo no ha analizado previamente. Puede imprimir una tabla de métricas sobre la calidad de su modelo.
|
||||||
|
|
||||||
|
🎓 **Ajuste del modelo (Model fitting)**
|
||||||
|
|
||||||
|
En el contexto del machine learning, el ajuste del modelo se refiere a la precisión de la función subyacente del modelo cuando intenta analizar datos con los que no está familiarizado.
|
||||||
|
|
||||||
|
🎓 **Ajuste insuficiente (Underfitting)** y **sobreajuste (overfitting)** son problemas comunes que degradan la calidad del modelo, ya que el modelo no encaja suficientemente bien, o encaja demasiado bien. Esto hace que el modelo haga predicciones demasiado estrechamente alineadas o demasiado poco alineadas con sus datos de entrenamiento. Un modelo sobreajustadoo (overfitting) predice demasiado bien los datos de entrenamiento porque ha aprendido demasiado bien los detalles de los datos y el ruido. Un modelo insuficentemente ajustado (Underfitting) es es preciso, ya que ni puede analizar con precisión sus datos de entrenamiento ni los datos que aún no ha 'visto'.
|
||||||
|
|
||||||
|

|
||||||
|
> Infografía de [Jen Looper](https://twitter.com/jenlooper)
|
||||||
|
|
||||||
|
## Ajuste de parámetros
|
||||||
|
|
||||||
|
Una vez que haya completado su entrenamiento inicial, observe la calidad del modelo y considere mejorarlo ajustando sus 'hiperparámetros'. Lea más sobre el proceso [en la documentación](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters?WT.mc_id=academic-15963-cxa).
|
||||||
|
|
||||||
|
## Predicción
|
||||||
|
|
||||||
|
Este es el momento en el que puede usar datos completamente nuevos para probar la precisión de su modelo. En una configuración de ML aplicada, donde está creando activos web para usar el modelo en producción, este proceo puede implicar la recopilación de la entrada del usuario (presionar un botón, por ejemplo) para establecer una variable y enviarla al modelo para la inferencia, o evaluación.
|
||||||
|
En estas lecciones, descubrirá cómo utilizar estos pasos para preparar, construir, probar, evaluar, y predecir - todos los gestos de un científico de datos y más, a medida que avanza en su viaje para convertirse en un ingeniero de machine learning 'full stack'.
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀Desafío
|
||||||
|
|
||||||
|
Dibuje un diagrama de flujos que refleje los pasos de practicante de ML. ¿Dónde te ves ahora mismo en el proceso? ¿Dónde predice que encontrará dificultades? ¿Qué te parece fácil?
|
||||||
|
|
||||||
|
## [Cuestionario previo a la conferencia](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/8/)
|
||||||
|
|
||||||
|
## Revisión & Autoestudio
|
||||||
|
|
||||||
|
Busque en línea entrevistas con científicos de datos que analicen su trabajo diario. Aquí está [uno](https://www.youtube.com/watch?v=Z3IjgbbCEfs).
|
||||||
|
|
||||||
|
## Asignación
|
||||||
|
|
||||||
|
[Entrevistar a un científico de datos](assignment.md)
|
@ -0,0 +1,105 @@
|
|||||||
|
# Teknik-teknik Machine Learning
|
||||||
|
|
||||||
|
Proses membangun, menggunakan, dan memelihara model machine learning dan data yang digunakan adalah proses yang sangat berbeda dari banyak alur kerja pengembangan lainnya. Dalam pelajaran ini, kita akan mengungkap prosesnya dan menguraikan teknik utama yang perlu Kamu ketahui. Kamu akan:
|
||||||
|
|
||||||
|
- Memahami gambaran dari proses yang mendasari machine learning.
|
||||||
|
- Menjelajahi konsep dasar seperti '*models*', '*predictions*', dan '*training data*'.
|
||||||
|
|
||||||
|
## [Quiz Pra-Pelajaran](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/7/)
|
||||||
|
## Pengantar
|
||||||
|
|
||||||
|
Gambaran membuat proses machine learning (ML) terdiri dari sejumlah langkah:
|
||||||
|
|
||||||
|
1. **Menentukan pertanyaan**. Sebagian besar proses ML dimulai dengan mengajukan pertanyaan yang tidak dapat dijawab oleh program kondisional sederhana atau mesin berbasis aturan (*rules-based engine*). Pertanyaan-pertanyaan ini sering berkisar seputar prediksi berdasarkan kumpulan data.
|
||||||
|
2. **Mengumpulkan dan menyiapkan data**. Untuk dapat menjawab pertanyaanmu, Kamu memerlukan data. Bagaimana kualitas dan terkadang kuantitas data kamu akan menentukan seberapa baik kamu dapat menjawab pertanyaan awal kamu. Memvisualisasikan data merupakan aspek penting dari fase ini. Fase ini juga mencakup pemisahan data menjadi kelompok *training* dan *testing* untuk membangun model.
|
||||||
|
3. **Memilih metode training**. Tergantung dari pertanyaan dan sifat datamu, Kamu perlu memilih bagaimana kamu ingin men-training sebuah model untuk mencerminkan data kamu dengan baik dan membuat prediksi yang akurat terhadapnya. Ini adalah bagian dari proses ML yang membutuhkan keahlian khusus dan seringkali perlu banyak eksperimen.
|
||||||
|
4. **Melatih model**. Dengan menggunakan data *training*, kamu akan menggunakan berbagai algoritma untuk melatih model guna mengenali pola dalam data. Modelnya mungkin bisa memanfaatkan *internal weight* yang dapat disesuaikan untuk memberi hak istimewa pada bagian tertentu dari data dibandingkan bagian lainnya untuk membangun model yang lebih baik.
|
||||||
|
5. **Mengevaluasi model**. Gunakan data yang belum pernah dilihat sebelumnya (data *testing*) untuk melihat bagaimana kinerja model.
|
||||||
|
6. **Parameter tuning**. Berdasarkan kinerja modelmu, Kamu dapat mengulang prosesnya menggunakan parameter atau variabel yang berbeda, yang mengontrol perilaku algoritma yang digunakan untuk melatih model.
|
||||||
|
7. **Prediksi**. Gunakan input baru untuk menguji keakuratan model kamu.
|
||||||
|
|
||||||
|
## Pertanyaan apa yang harus ditanyakan?
|
||||||
|
|
||||||
|
Komputer sangat ahli dalam menemukan pola tersembunyi dalam data. Hal ini sangat membantu peneliti yang memiliki pertanyaan tentang domain tertentu yang tidak dapat dijawab dengan mudah dari hanya membuat mesin berbasis aturan kondisional (*conditionally-based rules engine*). Untuk tugas aktuaria misalnya, seorang data scientist mungkin dapat membuat aturan secara manual seputar mortalitas perokok vs non-perokok.
|
||||||
|
|
||||||
|
Namun, ketika banyak variabel lain dimasukkan ke dalam persamaan, model ML mungkin terbukti lebih efisien untuk memprediksi tingkat mortalitas di masa depan berdasarkan riwayat kesehatan masa lalu. Contoh yang lebih menyenangkan mungkin membuat prediksi cuaca untuk bulan April di lokasi tertentu berdasarkan data yang mencakup garis lintang, garis bujur, perubahan iklim, kedekatan dengan laut, pola aliran udara (Jet Stream), dan banyak lagi.
|
||||||
|
|
||||||
|
✅ [Slide deck](https://www2.cisl.ucar.edu/sites/default/files/0900%20June%2024%20Haupt_0.pdf) ini menawarkan perspektif historis pada model cuaca dengan menggunakan ML dalam analisis cuaca.
|
||||||
|
|
||||||
|
## Tugas Pra-Pembuatan
|
||||||
|
|
||||||
|
Sebelum mulai membangun model kamu, ada beberapa tugas yang harus kamu selesaikan. Untuk menguji pertanyaan kamu dan membentuk hipotesis berdasarkan prediksi model, Kamu perlu mengidentifikasi dan mengonfigurasi beberapa elemen.
|
||||||
|
|
||||||
|
### Data
|
||||||
|
|
||||||
|
Untuk dapat menjawab pertanyaan kamu dengan kepastian, Kamu memerlukan sejumlah besar data dengan jenis yang tepat. Ada dua hal yang perlu kamu lakukan pada saat ini:
|
||||||
|
|
||||||
|
- **Mengumpulkan data**. Ingat pelajaran sebelumnya tentang keadilan dalam analisis data, kumpulkan data kamu dengan hati-hati. Waspadai sumber datanya, bias bawaan apa pun yang mungkin dimiliki, dan dokumentasikan asalnya.
|
||||||
|
- **Menyiapkan data**. Ada beberapa langkah dalam proses persiapan data. Kamu mungkin perlu menyusun data dan melakukan normalisasi jika berasal dari berbagai sumber. Kamu dapat meningkatkan kualitas dan kuantitas data melalui berbagai metode seperti mengonversi string menjadi angka (seperti yang kita lakukan di [Clustering](../../5-Clustering/1-Visualize/translations/README.id.md)). Kamu mungkin juga bisa membuat data baru berdasarkan data yang asli (seperti yang kita lakukan di [Classification](../../4-Classification/1-Introduction/translations/README.id.md)). Kamu bisa membersihkan dan mengubah data (seperti yang kita lakukan sebelum pelajaran [Web App](../3-Web-App/translations/README.id.md)). Terakhir, Kamu mungkin juga perlu mengacaknya dan mengubah urutannya, tergantung pada teknik *training* kamu.
|
||||||
|
|
||||||
|
✅ Setelah mengumpulkan dan memproses data kamu, luangkan waktu sejenak untuk melihat apakah bentuknya memungkinkan kamu untuk menjawab pertanyaan yang kamu maksudkan. Mungkin data tidak akan berkinerja baik dalam tugas yang kamu berikan, seperti yang kita temukan dalam pelajaran [Clustering](../../5-Clustering/1-Visualize/translations/README.id.md).
|
||||||
|
|
||||||
|
### Memilih variabel fiturmu
|
||||||
|
|
||||||
|
Sebuah [fitur](https://www.datasciencecentral.com/profiles/blogs/an-introduction-to-variable-and-feature-selection) adalah sebuah properti yang dapat diukur dalam data kamu. Dalam banyak dataset, properti dinyatakan sebagai sebuah heading kolom seperti 'date' 'size' atau 'color'. Variabel fitur kamu yang biasanya direpresentasikan sebagai `y` dalam kode, mewakili jawaban atas pertanyaan yang kamu coba tanyakan tentang data kamu: pada bulan Desember, labu dengan **warna** apa yang akan paling murah? di San Francisco, lingkungan mana yang menawarkan **harga** real estate terbaik?
|
||||||
|
|
||||||
|
🎓 **Feature Selection dan Feature Extraction** Bagaimana kamu tahu variabel mana yang harus dipilih saat membangun model? Kamu mungkin akan melalui proses pemilihan fitur (*Feature Selection*) atau ekstraksi fitur (*Feature Extraction*) untuk memilih variabel yang tepat untuk membuat model yang berkinerja paling baik. Namun, keduanya tidak sama: "Ekstraksi fitur membuat fitur baru dari fungsi fitur asli, sedangkan pemilihan fitur mengembalikan subset fitur." ([sumber](https://wikipedia.org/wiki/Feature_selection))
|
||||||
|
### Visualisasikan datamu
|
||||||
|
|
||||||
|
Aspek penting dari toolkit data scientist adalah kemampuan untuk memvisualisasikan data menggunakan beberapa *library* seperti Seaborn atau MatPlotLib. Merepresentasikan data kamu secara visual memungkinkan kamu mengungkap korelasi tersembunyi yang dapat kamu manfaatkan. Visualisasimu mungkin juga membantu kamu mengungkap data yang bias atau tidak seimbang (seperti yang kita temukan dalam [Classification](../../4-Classification/2-Classifiers-1/translations/README.id.md)).
|
||||||
|
### Membagi dataset
|
||||||
|
|
||||||
|
Sebelum memulai *training*, Kamu perlu membagi dataset menjadi dua atau lebih bagian dengan ukuran yang tidak sama tapi masih mewakili data dengan baik.
|
||||||
|
|
||||||
|
- **Training**. Bagian dataset ini digunakan untuk men-training model kamu. Bagian dataset ini merupakan mayoritas dari dataset asli.
|
||||||
|
- **Testing**. Sebuah dataset tes adalah kelompok data independen, seringkali dikumpulkan dari data yang asli yang akan digunakan untuk mengkonfirmasi kinerja dari model yang dibuat.
|
||||||
|
- **Validating**. Dataset validasi adalah kumpulan contoh mandiri yang lebih kecil yang kamu gunakan untuk menyetel hyperparameter atau arsitektur model untuk meningkatkan model. Tergantung dari ukuran data dan pertanyaan yang kamu ajukan, Kamu mungkin tidak perlu membuat dataset ketiga ini (seperti yang kita catat dalam [Time Series Forecasting](../7-TimeSeries/1-Introduction/translations/README.id.md)).
|
||||||
|
|
||||||
|
## Membuat sebuah model
|
||||||
|
|
||||||
|
Dengan menggunakan data *training*, tujuan kamu adalah membuat model atau representasi statistik data kamu menggunakan berbagai algoritma untuk **melatihnya**. Melatih model berarti mengeksposnya dengan data dan mengizinkannya membuat asumsi tentang pola yang ditemukan, divalidasi, dan diterima atau ditolak.
|
||||||
|
|
||||||
|
### Tentukan metode training
|
||||||
|
|
||||||
|
Tergantung dari pertanyaan dan sifat datamu, Kamu akan memilih metode untuk melatihnya. Buka dokumentasi [Scikit-learn](https://scikit-learn.org/stable/user_guide.html) yang kita gunakan dalam pelajaran ini, kamu bisa menjelajahi banyak cara untuk melatih sebuah model. Tergantung dari pengalamanmu, kamu mungkin perlu mencoba beberapa metode yang berbeda untuk membuat model yang terbaik. Kemungkinan kamu akan melalui proses di mana data scientist mengevaluasi kinerja model dengan memasukkan data yang belum pernah dilihat, memeriksa akurasi, bias, dan masalah penurunan kualitas lainnya, dan memilih metode training yang paling tepat untuk tugas yang ada.
|
||||||
|
### Melatih sebuah model
|
||||||
|
|
||||||
|
Berbekal data *training*, Kamu siap untuk menggunakannya untuk membuat model. Kamu akan melihat di banyak *library* ML mengenai kode 'model.fit' - pada saat inilah kamu mengirimkan data kamu sebagai *array* nilai (biasanya 'X') dan variabel fitur (biasanya 'y' ).
|
||||||
|
### Mengevaluasi model
|
||||||
|
|
||||||
|
Setelah proses *training* selesai (ini mungkin membutuhkan banyak iterasi, atau 'epoch', untuk melatih model besar), Kamu akan dapat mengevaluasi kualitas model dengan menggunakan data tes untuk mengukur kinerjanya. Data ini merupakan subset dari data asli yang modelnya belum pernah dianalisis sebelumnya. Kamu dapat mencetak tabel metrik tentang kualitas model kamu.
|
||||||
|
|
||||||
|
🎓 **Model fitting**
|
||||||
|
|
||||||
|
Dalam konteks machine learning, *model fitting* mengacu pada keakuratan dari fungsi yang mendasari model saat mencoba menganalisis data yang tidak familiar.
|
||||||
|
|
||||||
|
🎓 **Underfitting** dan **overfitting** adalah masalah umum yang menurunkan kualitas model, karena model tidak cukup akurat atau terlalu akurat. Hal ini menyebabkan model membuat prediksi yang terlalu selaras atau tidak cukup selaras dengan data trainingnya. Model overfit memprediksi data *training* terlalu baik karena telah mempelajari detail dan noise data dengan terlalu baik. Model underfit tidak akurat karena tidak dapat menganalisis data *training* atau data yang belum pernah dilihat sebelumnya secara akurat.
|
||||||
|
|
||||||
|

|
||||||
|
> Infografis oleh [Jen Looper](https://twitter.com/jenlooper)
|
||||||
|
|
||||||
|
## Parameter tuning
|
||||||
|
|
||||||
|
Setelah *training* awal selesai, amati kualitas model dan pertimbangkan untuk meningkatkannya dengan mengubah 'hyperparameter' nya. Baca lebih lanjut tentang prosesnya [di dalam dokumentasi](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters?WT.mc_id=academic-15963-cxa).
|
||||||
|
|
||||||
|
## Prediksi
|
||||||
|
|
||||||
|
Ini adalah saat di mana Kamu dapat menggunakan data yang sama sekali baru untuk menguji akurasi model kamu. Dalam setelan ML 'terapan', di mana kamu membangun aset web untuk menggunakan modelnya dalam produksi, proses ini mungkin melibatkan pengumpulan input pengguna (misalnya menekan tombol) untuk menyetel variabel dan mengirimkannya ke model untuk inferensi, atau evaluasi.
|
||||||
|
|
||||||
|
Dalam pelajaran ini, Kamu akan menemukan cara untuk menggunakan langkah-langkah ini untuk mempersiapkan, membangun, menguji, mengevaluasi, dan memprediksi - semua gestur data scientist dan banyak lagi, seiring kemajuanmu dalam perjalanan menjadi 'full stack' ML engineer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀Tantangan
|
||||||
|
|
||||||
|
Gambarlah sebuah flow chart yang mencerminkan langkah-langkah seorang praktisi ML. Di mana kamu melihat diri kamu saat ini dalam prosesnya? Di mana kamu memprediksi kamu akan menemukan kesulitan? Apa yang tampak mudah bagi kamu?
|
||||||
|
|
||||||
|
## [Quiz Pra-Pelajaran](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/8/)
|
||||||
|
|
||||||
|
## Ulasan & Belajar Mandiri
|
||||||
|
|
||||||
|
Cari di Internet mengenai wawancara dengan data scientist yang mendiskusikan pekerjaan sehari-hari mereka. Ini [salah satunya](https://www.youtube.com/watch?v=Z3IjgbbCEfs).
|
||||||
|
|
||||||
|
## Tugas
|
||||||
|
|
||||||
|
[Wawancara dengan data scientist](assignment.id.md)
|
@ -0,0 +1,11 @@
|
|||||||
|
# Wawancara seorang data scientist
|
||||||
|
|
||||||
|
## Instruksi
|
||||||
|
|
||||||
|
Di perusahaan Kamu, dalam user group, atau di antara teman atau sesama siswa, berbicaralah dengan seseorang yang bekerja secara profesional sebagai data scientist. Tulis makalah singkat (500 kata) tentang pekerjaan sehari-hari mereka. Apakah mereka spesialis, atau apakah mereka bekerja 'full stack'?
|
||||||
|
|
||||||
|
## Rubrik
|
||||||
|
|
||||||
|
| Kriteria | Sangat Bagus | Cukup | Perlu Peningkatan |
|
||||||
|
| -------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------ | --------------------- |
|
||||||
|
| | Sebuah esai dengan panjang yang sesuai, dengan sumber yang dikaitkan, disajikan sebagai file .doc | Esai dikaitkan dengan buruk atau lebih pendek dari panjang yang dibutuhkan | Tidak ada esai yang disajikan |
|
@ -0,0 +1,23 @@
|
|||||||
|
# Pengantar Machine Learning
|
||||||
|
|
||||||
|
Di bagian kurikulum ini, Kamu akan berkenalan dengan konsep yang mendasari bidang Machine Learning, apa itu Machine Learning, dan belajar mengenai
|
||||||
|
sejarah serta teknik-teknik yang digunakan oleh para peneliti. Ayo jelajahi dunia baru Machine Learning bersama!
|
||||||
|
|
||||||
|

|
||||||
|
> Foto oleh <a href="https://unsplash.com/@bill_oxford?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Bill Oxford</a> di <a href="https://unsplash.com/s/photos/globe?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
|
||||||
|
|
||||||
|
### Pelajaran
|
||||||
|
|
||||||
|
1. [Pengantar Machine Learning](../1-intro-to-ML/translations/README.id.md)
|
||||||
|
1. [Sejarah dari Machine Learning dan AI](../2-history-of-ML/translations/README.id.md)
|
||||||
|
1. [Keadilan dan Machine Learning](../3-fairness/translations/README.id.md)
|
||||||
|
1. [Teknik-Teknik Machine Learning](../4-techniques-of-ML/translations/README.id.md)
|
||||||
|
### Penghargaan
|
||||||
|
|
||||||
|
"Pengantar Machine Learning" ditulis dengan ♥️ oleh sebuah tim yang terdiri dari [Muhammad Sakib Khan Inan](https://twitter.com/Sakibinan), [Ornella Altunyan](https://twitter.com/ornelladotcom) dan [Jen Looper](https://twitter.com/jenlooper)
|
||||||
|
|
||||||
|
"Sejarah dari Machine Learning dan AI" ditulis dengan ♥️ oleh [Jen Looper](https://twitter.com/jenlooper) dan [Amy Boyd](https://twitter.com/AmyKateNicho)
|
||||||
|
|
||||||
|
"Keadilan dan Machine Learning" ditulis dengan ♥️ oleh [Tomomi Imura](https://twitter.com/girliemac)
|
||||||
|
|
||||||
|
"Teknik-Teknik Machine Learning" ditulis dengan ♥️ oleh [Jen Looper](https://twitter.com/jenlooper) dan [Chris Noring](https://twitter.com/softchris)
|
@ -0,0 +1,22 @@
|
|||||||
|
# 机器学习入门
|
||||||
|
|
||||||
|
课程的本章节将为您介绍机器学习领域背后的基本概念、什么是机器学习,并学习它的历史以及曾为此做出贡献的技术研究者门。让我们一起开始探索机器学习的全新世界吧!
|
||||||
|
|
||||||
|

|
||||||
|
> 图片由 <a href="https://unsplash.com/@bill_oxford?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Bill Oxford</a>提供,来自 <a href="https://unsplash.com/s/photos/globe?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
|
||||||
|
|
||||||
|
### 课程安排
|
||||||
|
|
||||||
|
1. [机器学习简介](../1-intro-to-ML/translations/README.zh-cn.md)
|
||||||
|
1. [机器学习的历史](../2-history-of-ML/translations/README.zh-cn.md)
|
||||||
|
1. [机器学习中的公平性](../3-fairness/translations/README.zh-cn.md)
|
||||||
|
1. [机器学习技术](../4-techniques-of-ML/translations/README.zh-cn.md)
|
||||||
|
### 致谢
|
||||||
|
|
||||||
|
"机器学习简介"由 [Muhammad Sakib Khan Inan](https://twitter.com/Sakibinan), [Ornella Altunyan](https://twitter.com/ornelladotcom) 及 [Jen Looper](https://twitter.com/jenlooper),共同倾 ♥️ 而作
|
||||||
|
|
||||||
|
"机器学习及人工智能历史" 由 [Jen Looper](https://twitter.com/jenlooper) 及 [Amy Boyd](https://twitter.com/AmyKateNicho)倾 ♥️ 而作
|
||||||
|
|
||||||
|
"公平性与机器学习" 由 [Tomomi Imura](https://twitter.com/girliemac) 倾 ♥️ 而作
|
||||||
|
|
||||||
|
"机器学习的技术" 由 [Jen Looper](https://twitter.com/jenlooper) 及 [Chris Noring](https://twitter.com/softchris) 倾 ♥️ 而作
|
After Width: | Height: | Size: 558 KiB |
Before Width: | Height: | Size: 283 KiB After Width: | Height: | Size: 16 KiB |
@ -0,0 +1,436 @@
|
|||||||
|
{
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 0,
|
||||||
|
"metadata": {
|
||||||
|
"colab": {
|
||||||
|
"name": "lesson_1-R.ipynb",
|
||||||
|
"provenance": [],
|
||||||
|
"collapsed_sections": [],
|
||||||
|
"toc_visible": true
|
||||||
|
},
|
||||||
|
"kernelspec": {
|
||||||
|
"name": "ir",
|
||||||
|
"display_name": "R"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"name": "R"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "YJUHCXqK57yz"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"#Build a regression model: Get started with R and Tidymodels for regression models"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "LWNNzfqd6feZ"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## Introduction to Regression - Lesson 1\n",
|
||||||
|
"\n",
|
||||||
|
"#### Putting it into perspective\n",
|
||||||
|
"\n",
|
||||||
|
"✅ There are many types of regression methods, and which one you pick depends on the answer you're looking for. If you want to predict the probable height for a person of a given age, you'd use `linear regression`, as you're seeking a **numeric value**. If you're interested in discovering whether a type of cuisine should be considered vegan or not, you're looking for a **category assignment** so you would use `logistic regression`. You'll learn more about logistic regression later. Think a bit about some questions you can ask of data, and which of these methods would be more appropriate.\n",
|
||||||
|
"\n",
|
||||||
|
"In this section, you will work with a [small dataset about diabetes](https://www4.stat.ncsu.edu/~boos/var.select/diabetes.html). Imagine that you wanted to test a treatment for diabetic patients. Machine Learning models might help you determine which patients would respond better to the treatment, based on combinations of variables. Even a very basic regression model, when visualized, might show information about variables that would help you organize your theoretical clinical trials.\n",
|
||||||
|
"\n",
|
||||||
|
"That said, let's get started on this task!\n",
|
||||||
|
"\n",
|
||||||
|
"<br>Artwork by @allison_horst"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "FIo2YhO26wI9"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 1. Loading up our tool set\n",
|
||||||
|
"\n",
|
||||||
|
"For this task, we'll require the following packages:\n",
|
||||||
|
"\n",
|
||||||
|
"- `tidyverse`: The [tidyverse](https://www.tidyverse.org/) is a [collection of R packages](https://www.tidyverse.org/packages) designed to makes data science faster, easier and more fun!\n",
|
||||||
|
"\n",
|
||||||
|
"- `tidymodels`: The [tidymodels](https://www.tidymodels.org/) framework is a [collection of packages](https://www.tidymodels.org/packages/) for modeling and machine learning.\n",
|
||||||
|
"\n",
|
||||||
|
"You can have them installed as:\n",
|
||||||
|
"\n",
|
||||||
|
"`install.packages(c(\"tidyverse\", \"tidymodels\"))`\n",
|
||||||
|
"\n",
|
||||||
|
"The script below checks whether you have the packages required to complete this module and installs them for you in case some are missing."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "cIA9fz9v7Dss",
|
||||||
|
"colab": {
|
||||||
|
"base_uri": "https://localhost:8080/"
|
||||||
|
},
|
||||||
|
"outputId": "2df7073b-86b2-4b32-cb86-0da605a0dc11"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"if (!require(\"pacman\")) install.packages(\"pacman\")\n",
|
||||||
|
"pacman::p_load(tidyverse, tidymodels)"
|
||||||
|
],
|
||||||
|
"execution_count": 2,
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"Loading required package: pacman\n",
|
||||||
|
"\n"
|
||||||
|
],
|
||||||
|
"name": "stderr"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "gpO_P_6f9WUG"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Now, let's load these awesome packages and make them available in our current R session.(This is for mere illustration, `pacman::p_load()` already did that for you)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "NLMycgG-9ezO"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# load the core Tidyverse packages\n",
|
||||||
|
"library(tidyverse)\n",
|
||||||
|
"\n",
|
||||||
|
"# load the core Tidymodels packages\n",
|
||||||
|
"library(tidymodels)\n"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "KM6iXLH996Cl"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 2. The diabetes dataset\n",
|
||||||
|
"\n",
|
||||||
|
"In this exercise, we'll put our regression skills into display by making predictions on a diabetes dataset. The [diabetes dataset](https://www4.stat.ncsu.edu/~boos/var.select/diabetes.rwrite1.txt) includes `442 samples` of data around diabetes, with 10 predictor feature variables, `age`, `sex`, `body mass index`, `average blood pressure`, and `six blood serum measurements` as well as an outcome variable `y`: a quantitative measure of disease progression one year after baseline.\n",
|
||||||
|
"\n",
|
||||||
|
"|Number of observations|442|\n",
|
||||||
|
"|----------------------|:---|\n",
|
||||||
|
"|Number of predictors|First 10 columns are numeric predictive|\n",
|
||||||
|
"|Outcome/Target|Column 11 is a quantitative measure of disease progression one year after baseline|\n",
|
||||||
|
"|Predictor Information|- age in years\n",
|
||||||
|
"||- sex\n",
|
||||||
|
"||- bmi body mass index\n",
|
||||||
|
"||- bp average blood pressure\n",
|
||||||
|
"||- s1 tc, total serum cholesterol\n",
|
||||||
|
"||- s2 ldl, low-density lipoproteins\n",
|
||||||
|
"||- s3 hdl, high-density lipoproteins\n",
|
||||||
|
"||- s4 tch, total cholesterol / HDL\n",
|
||||||
|
"||- s5 ltg, possibly log of serum triglycerides level\n",
|
||||||
|
"||- s6 glu, blood sugar level|\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"> 🎓 Remember, this is supervised learning, and we need a named 'y' target.\n",
|
||||||
|
"\n",
|
||||||
|
"Before you can manipulate data with R, you need to import the data into R's memory, or build a connection to the data that R can use to access the data remotely.\n",
|
||||||
|
"\n",
|
||||||
|
"> The [readr](https://readr.tidyverse.org/) package, which is part of the Tidyverse, provides a fast and friendly way to read rectangular data into R.\n",
|
||||||
|
"\n",
|
||||||
|
"Now, let's load the diabetes dataset provided in this source URL: <https://www4.stat.ncsu.edu/~boos/var.select/diabetes.html>\n",
|
||||||
|
"\n",
|
||||||
|
"Also, we'll perform a sanity check on our data using `glimpse()` and dsiplay the first 5 rows using `slice()`.\n",
|
||||||
|
"\n",
|
||||||
|
"Before going any further, let's also introduce something you will encounter often in R code 🥁🥁: the pipe operator `%>%`\n",
|
||||||
|
"\n",
|
||||||
|
"The pipe operator (`%>%`) performs operations in logical sequence by passing an object forward into a function or call expression. You can think of the pipe operator as saying \"and then\" in your code."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "Z1geAMhM-bSP"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Import the data set\n",
|
||||||
|
"diabetes <- read_table2(file = \"https://www4.stat.ncsu.edu/~boos/var.select/diabetes.rwrite1.txt\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Get a glimpse and dimensions of the data\n",
|
||||||
|
"glimpse(diabetes)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Select the first 5 rows of the data\n",
|
||||||
|
"diabetes %>% \n",
|
||||||
|
" slice(1:5)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "UwjVT1Hz-c3Z"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"`glimpse()` shows us that this data has 442 rows and 11 columns with all the columns being of data type `double` \n",
|
||||||
|
"\n",
|
||||||
|
"<br>\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"> glimpse() and slice() are functions in [`dplyr`](https://dplyr.tidyverse.org/). Dplyr, part of the Tidyverse, is a grammar of data manipulation that provides a consistent set of verbs that help you solve the most common data manipulation challenges\n",
|
||||||
|
"\n",
|
||||||
|
"<br>\n",
|
||||||
|
"\n",
|
||||||
|
"Now that we have the data, let's narrow down to one feature (`bmi`) to target for this exercise. This will require us to select the desired columns. So, how do we do this?\n",
|
||||||
|
"\n",
|
||||||
|
"[`dplyr::select()`](https://dplyr.tidyverse.org/reference/select.html) allows us to *select* (and optionally rename) columns in a data frame."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "RDY1oAKI-m80"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Select predictor feature `bmi` and outcome `y`\n",
|
||||||
|
"diabetes_select <- diabetes %>% \n",
|
||||||
|
" select(c(bmi, y))\n",
|
||||||
|
"\n",
|
||||||
|
"# Print the first 5 rows\n",
|
||||||
|
"diabetes_select %>% \n",
|
||||||
|
" slice(1:10)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "SDk668xK-tc3"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 3. Training and Testing data\n",
|
||||||
|
"\n",
|
||||||
|
"It's common practice in supervised learning to *split* the data into two subsets; a (typically larger) set with which to train the model, and a smaller \"hold-back\" set with which to see how the model performed.\n",
|
||||||
|
"\n",
|
||||||
|
"Now that we have data ready, we can see if a machine can help determine a logical split between the numbers in this dataset. We can use the [rsample](https://tidymodels.github.io/rsample/) package, which is part of the Tidymodels framework, to create an object that contains the information on *how* to split the data, and then two more rsample functions to extract the created training and testing sets:\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "EqtHx129-1h-"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"set.seed(2056)\n",
|
||||||
|
"# Split 67% of the data for training and the rest for tesing\n",
|
||||||
|
"diabetes_split <- diabetes_select %>% \n",
|
||||||
|
" initial_split(prop = 0.67)\n",
|
||||||
|
"\n",
|
||||||
|
"# Extract the resulting train and test sets\n",
|
||||||
|
"diabetes_train <- training(diabetes_split)\n",
|
||||||
|
"diabetes_test <- testing(diabetes_split)\n",
|
||||||
|
"\n",
|
||||||
|
"# Print the first 3 rows of the training set\n",
|
||||||
|
"diabetes_train %>% \n",
|
||||||
|
" slice(1:10)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "sBOS-XhB-6v7"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 4. Train a linear regression model with Tidymodels\n",
|
||||||
|
"\n",
|
||||||
|
"Now we are ready to train our model!\n",
|
||||||
|
"\n",
|
||||||
|
"In Tidymodels, you specify models using `parsnip()` by specifying three concepts:\n",
|
||||||
|
"\n",
|
||||||
|
"- Model **type** differentiates models such as linear regression, logistic regression, decision tree models, and so forth.\n",
|
||||||
|
"\n",
|
||||||
|
"- Model **mode** includes common options like regression and classification; some model types support either of these while some only have one mode.\n",
|
||||||
|
"\n",
|
||||||
|
"- Model **engine** is the computational tool which will be used to fit the model. Often these are R packages, such as **`\"lm\"`** or **`\"ranger\"`**\n",
|
||||||
|
"\n",
|
||||||
|
"This modeling information is captured in a model specification, so let's build one!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "20OwEw20--t3"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Build a linear model specification\n",
|
||||||
|
"lm_spec <- \n",
|
||||||
|
" # Type\n",
|
||||||
|
" linear_reg() %>% \n",
|
||||||
|
" # Engine\n",
|
||||||
|
" set_engine(\"lm\") %>% \n",
|
||||||
|
" # Mode\n",
|
||||||
|
" set_mode(\"regression\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Print the model specification\n",
|
||||||
|
"lm_spec"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "_oDHs89k_CJj"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"After a model has been *specified*, the model can be `estimated` or `trained` using the [`fit()`](https://parsnip.tidymodels.org/reference/fit.html) function, typically using a formula and some data.\n",
|
||||||
|
"\n",
|
||||||
|
"`y ~ .` means we'll fit `y` as the predicted quantity/target, explained by all the predictors/features ie, `.` (in this case, we only have one predictor: `bmi` )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "YlsHqd-q_GJQ"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Build a linear model specification\n",
|
||||||
|
"lm_spec <- linear_reg() %>% \n",
|
||||||
|
" set_engine(\"lm\") %>%\n",
|
||||||
|
" set_mode(\"regression\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Train a linear regression model\n",
|
||||||
|
"lm_mod <- lm_spec %>% \n",
|
||||||
|
" fit(y ~ ., data = diabetes_train)\n",
|
||||||
|
"\n",
|
||||||
|
"# Print the model\n",
|
||||||
|
"lm_mod"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "kGZ22RQj_Olu"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"From the model output, we can see the coefficients learned during training. They represent the coefficients of the line of best fit that gives us the lowest overall error between the actual and predicted variable.\n",
|
||||||
|
"<br>\n",
|
||||||
|
"\n",
|
||||||
|
"## 5. Make predictions on the test set\n",
|
||||||
|
"\n",
|
||||||
|
"Now that we've trained a model, we can use it to predict the disease progression y for the test dataset using [parsnip::predict()](https://parsnip.tidymodels.org/reference/predict.model_fit.html). This will be used to draw the line between data groups."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "nXHbY7M2_aao"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Make predictions for the test set\n",
|
||||||
|
"predictions <- lm_mod %>% \n",
|
||||||
|
" predict(new_data = diabetes_test)\n",
|
||||||
|
"\n",
|
||||||
|
"# Print out some of the predictions\n",
|
||||||
|
"predictions %>% \n",
|
||||||
|
" slice(1:5)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "R_JstwUY_bIs"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Woohoo! 💃🕺 We just trained a model and used it to make predictions!\n",
|
||||||
|
"\n",
|
||||||
|
"When making predictions, the tidymodels convention is to always produce a tibble/data frame of results with standardized column names. This makes it easy to combine the original data and the predictions in a usable format for subsequent operations such as plotting.\n",
|
||||||
|
"\n",
|
||||||
|
"`dplyr::bind_cols()` efficiently binds multiple data frames column."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "RybsMJR7_iI8"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Combine the predictions and the original test set\n",
|
||||||
|
"results <- diabetes_test %>% \n",
|
||||||
|
" bind_cols(predictions)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"results %>% \n",
|
||||||
|
" slice(1:5)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "XJbYbMZW_n_s"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 6. Plot modelling results\n",
|
||||||
|
"\n",
|
||||||
|
"Now, its time to see this visually 📈. We'll create a scatter plot of all the `y` and `bmi` values of the test set, then use the predictions to draw a line in the most appropriate place, between the model's data groupings.\n",
|
||||||
|
"\n",
|
||||||
|
"R has several systems for making graphs, but `ggplot2` is one of the most elegant and most versatile. This allows you to compose graphs by **combining independent components**."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "R9tYp3VW_sTn"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Set a theme for the plot\n",
|
||||||
|
"theme_set(theme_light())\n",
|
||||||
|
"# Create a scatter plot\n",
|
||||||
|
"results %>% \n",
|
||||||
|
" ggplot(aes(x = bmi)) +\n",
|
||||||
|
" # Add a scatter plot\n",
|
||||||
|
" geom_point(aes(y = y), size = 1.6) +\n",
|
||||||
|
" # Add a line plot\n",
|
||||||
|
" geom_line(aes(y = .pred), color = \"blue\", size = 1.5)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "zrPtHIxx_tNI"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"> ✅ Think a bit about what's going on here. A straight line is running through many small dots of data, but what is it doing exactly? Can you see how you should be able to use this line to predict where a new, unseen data point should fit in relationship to the plot's y axis? Try to put into words the practical use of this model.\n",
|
||||||
|
"\n",
|
||||||
|
"Congratulations, you built your first linear regression model, created a prediction with it, and displayed it in a plot!\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
@ -0,0 +1,250 @@
|
|||||||
|
---
|
||||||
|
title: 'Build a regression model: Get started with R and Tidymodels for regression models'
|
||||||
|
output:
|
||||||
|
html_document:
|
||||||
|
df_print: paged
|
||||||
|
theme: flatly
|
||||||
|
highlight: breezedark
|
||||||
|
toc: yes
|
||||||
|
toc_float: yes
|
||||||
|
code_download: yes
|
||||||
|
---
|
||||||
|
|
||||||
|
## Introduction to Regression - Lesson 1
|
||||||
|
|
||||||
|
#### Putting it into perspective
|
||||||
|
|
||||||
|
✅ There are many types of regression methods, and which one you pick depends on the answer you're looking for. If you want to predict the probable height for a person of a given age, you'd use `linear regression`, as you're seeking a **numeric value**. If you're interested in discovering whether a type of cuisine should be considered vegan or not, you're looking for a **category assignment** so you would use `logistic regression`. You'll learn more about logistic regression later. Think a bit about some questions you can ask of data, and which of these methods would be more appropriate.
|
||||||
|
|
||||||
|
In this section, you will work with a [small dataset about diabetes](https://www4.stat.ncsu.edu/~boos/var.select/diabetes.html). Imagine that you wanted to test a treatment for diabetic patients. Machine Learning models might help you determine which patients would respond better to the treatment, based on combinations of variables. Even a very basic regression model, when visualized, might show information about variables that would help you organize your theoretical clinical trials.
|
||||||
|
|
||||||
|
That said, let's get started on this task!
|
||||||
|
|
||||||
|
{width="630"}
|
||||||
|
|
||||||
|
## 1. Loading up our tool set
|
||||||
|
|
||||||
|
For this task, we'll require the following packages:
|
||||||
|
|
||||||
|
- `tidyverse`: The [tidyverse](https://www.tidyverse.org/) is a [collection of R packages](https://www.tidyverse.org/packages) designed to makes data science faster, easier and more fun!
|
||||||
|
|
||||||
|
- `tidymodels`: The [tidymodels](https://www.tidymodels.org/) framework is a [collection of packages](https://www.tidymodels.org/packages/) for modeling and machine learning.
|
||||||
|
|
||||||
|
You can have them installed as:
|
||||||
|
|
||||||
|
`install.packages(c("tidyverse", "tidymodels"))`
|
||||||
|
|
||||||
|
The script below checks whether you have the packages required to complete this module and installs them for you in case they are missing.
|
||||||
|
|
||||||
|
```{r, message=F, warning=F}
|
||||||
|
if (!require("pacman")) install.packages("pacman")
|
||||||
|
pacman::p_load(tidyverse, tidymodels)
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, let's load these awesome packages and make them available in our current R session. (This is for mere illustration, `pacman::p_load()` already did that for you)
|
||||||
|
|
||||||
|
```{r load_tidy_verse_models, message=F, warning=F}
|
||||||
|
# load the core Tidyverse packages
|
||||||
|
library(tidyverse)
|
||||||
|
|
||||||
|
# load the core Tidymodels packages
|
||||||
|
library(tidymodels)
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2. The diabetes dataset
|
||||||
|
|
||||||
|
In this exercise, we'll put our regression skills into display by making predictions on a diabetes dataset. The [diabetes dataset](https://www4.stat.ncsu.edu/~boos/var.select/diabetes.rwrite1.txt) includes `442 samples` of data around diabetes, with 10 predictor feature variables, `age`, `sex`, `body mass index`, `average blood pressure`, and `six blood serum measurements` as well as an outcome variable `y`: a quantitative measure of disease progression one year after baseline.
|
||||||
|
|
||||||
|
+----------------------------+------------------------------------------------------------------------------------+
|
||||||
|
| **Number of observations** | **442** |
|
||||||
|
+============================+====================================================================================+
|
||||||
|
| **Number of predictors** | First 10 columns are numeric predictive values |
|
||||||
|
+----------------------------+------------------------------------------------------------------------------------+
|
||||||
|
| **Outcome/Target** | Column 11 is a quantitative measure of disease progression one year after baseline |
|
||||||
|
+----------------------------+------------------------------------------------------------------------------------+
|
||||||
|
| **Predictor Information** | - age age in years |
|
||||||
|
| | - sex |
|
||||||
|
| | - bmi body mass index |
|
||||||
|
| | - bp average blood pressure |
|
||||||
|
| | - s1 tc, total serum cholesterol |
|
||||||
|
| | - s2 ldl, low-density lipoproteins |
|
||||||
|
| | - s3 hdl, high-density lipoproteins |
|
||||||
|
| | - s4 tch, total cholesterol / HDL |
|
||||||
|
| | - s5 ltg, possibly log of serum triglycerides level |
|
||||||
|
| | - s6 glu, blood sugar level |
|
||||||
|
+----------------------------+------------------------------------------------------------------------------------+
|
||||||
|
|
||||||
|
> 🎓 Remember, this is supervised learning, and we need a named 'y' target.
|
||||||
|
|
||||||
|
Before you can manipulate data with R, you need to import the data into R's memory, or build a connection to the data that R can use to access the data remotely.\
|
||||||
|
|
||||||
|
> The [readr](https://readr.tidyverse.org/) package, which is part of the Tidyverse, provides a fast and friendly way to read rectangular data into R.
|
||||||
|
|
||||||
|
Now, let's load the diabetes dataset provided in this source URL: <https://www4.stat.ncsu.edu/~boos/var.select/diabetes.html>
|
||||||
|
|
||||||
|
Also, we'll perform a sanity check on our data using `glimpse()` and dsiplay the first 5 rows using `slice()`.
|
||||||
|
|
||||||
|
Before going any further, let's introduce something you will encounter quite often in R code: the pipe operator `%>%`
|
||||||
|
|
||||||
|
The pipe operator (`%>%`) performs operations in logical sequence by passing an object forward into a function or call expression. You can think of the pipe operator as saying "and then" in your code.\
|
||||||
|
|
||||||
|
```{r load_dataset, message=F, warning=F}
|
||||||
|
# Import the data set
|
||||||
|
diabetes <- read_table2(file = "https://www4.stat.ncsu.edu/~boos/var.select/diabetes.rwrite1.txt")
|
||||||
|
|
||||||
|
|
||||||
|
# Get a glimpse and dimensions of the data
|
||||||
|
glimpse(diabetes)
|
||||||
|
|
||||||
|
|
||||||
|
# Select the first 5 rows of the data
|
||||||
|
diabetes %>%
|
||||||
|
slice(1:5)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
`glimpse()` shows us that this data has 442 rows and 11 columns with all the columns being of data type `double`
|
||||||
|
|
||||||
|
> glimpse() and slice() are functions in [`dplyr`](https://dplyr.tidyverse.org/). Dplyr, part of the Tidyverse, is a grammar of data manipulation that provides a consistent set of verbs that help you solve the most common data manipulation challenges
|
||||||
|
|
||||||
|
Now that we have the data, let's narrow down to one feature (`bmi`) to target for this exercise. This will require us to select the desired columns. So, how do we do this?
|
||||||
|
|
||||||
|
[`dplyr::select()`](https://dplyr.tidyverse.org/reference/select.html) allows us to *select* (and optionally rename) columns in a data frame.
|
||||||
|
|
||||||
|
```{r select, message=F, warning=F}
|
||||||
|
# Select predictor feature `bmi` and outcome `y`
|
||||||
|
diabetes_select <- diabetes %>%
|
||||||
|
select(c(bmi, y))
|
||||||
|
|
||||||
|
# Print the first 5 rows
|
||||||
|
diabetes_select %>%
|
||||||
|
slice(1:5)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. Training and Testing data
|
||||||
|
|
||||||
|
It's common practice in supervised learning to *split* the data into two subsets; a (typically larger) set with which to train the model, and a smaller "hold-back" set with which to see how the model performed.
|
||||||
|
|
||||||
|
Now that we have data ready, we can see if a machine can help determine a logical split between the numbers in this dataset. We can use the [rsample](https://tidymodels.github.io/rsample/) package, which is part of the Tidymodels framework, to create an object that contains the information on *how* to split the data, and then two more rsample functions to extract the created training and testing sets:
|
||||||
|
|
||||||
|
```{r split, message=F, warning=F}
|
||||||
|
set.seed(2056)
|
||||||
|
# Split 67% of the data for training and the rest for tesing
|
||||||
|
diabetes_split <- diabetes_select %>%
|
||||||
|
initial_split(prop = 0.67)
|
||||||
|
|
||||||
|
# Extract the resulting train and test sets
|
||||||
|
diabetes_train <- training(diabetes_split)
|
||||||
|
diabetes_test <- testing(diabetes_split)
|
||||||
|
|
||||||
|
# Print the first 3 rows of the training set
|
||||||
|
diabetes_train %>%
|
||||||
|
slice(1:3)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. Train a linear regression model with Tidymodels
|
||||||
|
|
||||||
|
Now we are ready to train our model!
|
||||||
|
|
||||||
|
In Tidymodels, you specify models using `parsnip()` by specifying three concepts:
|
||||||
|
|
||||||
|
- Model **type** differentiates models such as linear regression, logistic regression, decision tree models, and so forth.
|
||||||
|
|
||||||
|
- Model **mode** includes common options like regression and classification; some model types support either of these while some only have one mode.
|
||||||
|
|
||||||
|
- Model **engine** is the computational tool which will be used to fit the model. Often these are R packages, such as **`"lm"`** or **`"ranger"`**
|
||||||
|
|
||||||
|
This modeling information is captured in a model specification, so let's build one!
|
||||||
|
|
||||||
|
```{r lm_model_spec, message=F, warning=F}
|
||||||
|
# Build a linear model specification
|
||||||
|
lm_spec <-
|
||||||
|
# Type
|
||||||
|
linear_reg() %>%
|
||||||
|
# Engine
|
||||||
|
set_engine("lm") %>%
|
||||||
|
# Mode
|
||||||
|
set_mode("regression")
|
||||||
|
|
||||||
|
|
||||||
|
# Print the model specification
|
||||||
|
lm_spec
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
After a model has been *specified*, the model can be `estimated` or `trained` using the [`fit()`](https://parsnip.tidymodels.org/reference/fit.html) function, typically using a formula and some data.
|
||||||
|
|
||||||
|
`y ~ .` means we'll fit `y` as the predicted quantity/target, explained by all the predictors/features ie, `.` (in this case, we only have one predictor: `bmi` )
|
||||||
|
|
||||||
|
```{r train, message=F, warning=F}
|
||||||
|
# Build a linear model specification
|
||||||
|
lm_spec <- linear_reg() %>%
|
||||||
|
set_engine("lm") %>%
|
||||||
|
set_mode("regression")
|
||||||
|
|
||||||
|
|
||||||
|
# Train a linear regression model
|
||||||
|
lm_mod <- lm_spec %>%
|
||||||
|
fit(y ~ ., data = diabetes_train)
|
||||||
|
|
||||||
|
# Print the model
|
||||||
|
lm_mod
|
||||||
|
```
|
||||||
|
|
||||||
|
From the model output, we can see the coefficients learned during training. They represent the coefficients of the line of best fit that gives us the lowest overall error between the actual and predicted variable.
|
||||||
|
|
||||||
|
## 5. Make predictions on the test set
|
||||||
|
|
||||||
|
Now that we've trained a model, we can use it to predict the disease progression y for the test dataset using [parsnip::predict()](https://parsnip.tidymodels.org/reference/predict.model_fit.html). This will be used to draw the line between data groups.
|
||||||
|
|
||||||
|
```{r test, message=F, warning=F}
|
||||||
|
# Make predictions for the test set
|
||||||
|
predictions <- lm_mod %>%
|
||||||
|
predict(new_data = diabetes_test)
|
||||||
|
|
||||||
|
# Print out some of the predictions
|
||||||
|
predictions %>%
|
||||||
|
slice(1:5)
|
||||||
|
```
|
||||||
|
|
||||||
|
Woohoo! 💃🕺 We just trained a model and used it to make predictions!
|
||||||
|
|
||||||
|
When making predictions, the tidymodels convention is to always produce a tibble/data frame of results with standardized column names. This makes it easy to combine the original data and the predictions in a usable format for subsequent operations such as plotting.
|
||||||
|
|
||||||
|
`dplyr::bind_cols()` efficiently binds multiple data frames column.
|
||||||
|
|
||||||
|
```{r test_pred, message=F, warning=F}
|
||||||
|
# Combine the predictions and the original test set
|
||||||
|
results <- diabetes_test %>%
|
||||||
|
bind_cols(predictions)
|
||||||
|
|
||||||
|
|
||||||
|
results %>%
|
||||||
|
slice(1:5)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. Plot modelling results
|
||||||
|
|
||||||
|
Now, its time to see this visually 📈. We'll create a scatter plot of all the `y` and `bmi` values of the test set, then use the predictions to draw a line in the most appropriate place, between the model's data groupings.
|
||||||
|
|
||||||
|
R has several systems for making graphs, but `ggplot2` is one of the most elegant and most versatile. This allows you to compose graphs by **combining independent components**.
|
||||||
|
|
||||||
|
```{r plot_pred, message=F, warning=F}
|
||||||
|
# Set a theme for the plot
|
||||||
|
theme_set(theme_light())
|
||||||
|
# Create a scatter plot
|
||||||
|
results %>%
|
||||||
|
ggplot(aes(x = bmi)) +
|
||||||
|
# Add a scatter plot
|
||||||
|
geom_point(aes(y = y), size = 1.6) +
|
||||||
|
# Add a line plot
|
||||||
|
geom_line(aes(y = .pred), color = "blue", size = 1.5)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
> ✅ Think a bit about what's going on here. A straight line is running through many small dots of data, but what is it doing exactly? Can you see how you should be able to use this line to predict where a new, unseen data point should fit in relationship to the plot's y axis? Try to put into words the practical use of this model.
|
||||||
|
|
||||||
|
Congratulations, you built your first linear regression model, created a prediction with it, and displayed it in a plot!
|
@ -0,0 +1,211 @@
|
|||||||
|
# Iniziare con Python e Scikit-learn per i modelli di regressione
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> Sketchnote di [Tomomi Imura](https://www.twitter.com/girlie_mac)
|
||||||
|
|
||||||
|
## [Qui Pre-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/9/)
|
||||||
|
|
||||||
|
## Introduzione
|
||||||
|
|
||||||
|
In queste quattro lezioni, si scoprirà come costruire modelli di regressione. Si discuterà di cosa siano fra breve.
|
||||||
|
Prima di tutto, ci si deve assicurare di avere a disposizione gli strumenti adatti per far partire il processo!
|
||||||
|
|
||||||
|
In questa lezione, si imparerà come:
|
||||||
|
|
||||||
|
- Configurare il proprio computer per attività locali di machine learning.
|
||||||
|
- Lavorare con i Jupyter notebook.
|
||||||
|
- Usare Scikit-learn, compresa l'installazione.
|
||||||
|
- Esplorare la regressione lineare con un esercizio pratico.
|
||||||
|
|
||||||
|
## Installazioni e configurazioni
|
||||||
|
|
||||||
|
[](https://youtu.be/7EXd4_ttIuw "Using Python with Visual Studio Code")
|
||||||
|
|
||||||
|
> 🎥 Fare click sull'immagine qui sopra per un video: usare Python all'interno di VS Code.
|
||||||
|
|
||||||
|
1. **Installare Python**. Assicurarsi che [Python](https://www.python.org/downloads/) sia installato nel proprio computer. Si userà Python for per molte attività di data science e machine learning. La maggior parte dei sistemi già include una installazione di Python. Ci sono anche utili [Pacchetti di Codice Python](https://code.visualstudio.com/learn/educators/installers?WT.mc_id=academic-15963-cxa) disponbili, per facilitare l'installazione per alcuni utenti.
|
||||||
|
|
||||||
|
Alcuni utilizzi di Python, tuttavia, richiedono una versione del software, laddove altri ne richiedono un'altra differente. Per questa ragione, è utile lavorare con un [ambiente virtuale](https://docs.python.org/3/library/venv.html).
|
||||||
|
|
||||||
|
2. **Installare Visual Studio Code**. Assicurarsi di avere installato Visual Studio Code sul proprio computer. Si seguano queste istruzioni per [installare Visual Studio Code](https://code.visualstudio.com/) per l'installazione basica. Si userà Python in Visual Studio Code in questo corso, quindi meglio rinfrescarsi le idee su come [configurare Visual Studio Code](https://docs.microsoft.com/learn/modules/python-install-vscode?WT.mc_id=academic-15963-cxa) per lo sviluppo in Python.
|
||||||
|
|
||||||
|
> Si prenda confidenza con Python tramite questa collezione di [moduli di apprendimento](https://docs.microsoft.com/users/jenlooper-2911/collections/mp1pagggd5qrq7?WT.mc_id=academic-15963-cxa)
|
||||||
|
|
||||||
|
3. **Installare Scikit-learn**, seguendo [queste istruzioni](https://scikit-learn.org/stable/install.html). Visto che ci si deve assicurare di usare Python 3, ci si raccomanda di usare un ambiente virtuale. Si noti che se si installa questa libreria in un M1 Mac, ci sono istruzioni speciali nella pagina di cui al riferimento qui sopra.
|
||||||
|
|
||||||
|
1. **Installare Jupyter Notebook**. Servirà [installare il pacchetto Jupyter](https://pypi.org/project/jupyter/).
|
||||||
|
|
||||||
|
## Ambiente di creazione ML
|
||||||
|
|
||||||
|
Si useranno **notebook** per sviluppare il codice Python e creare modelli di machine learning. Questo tipo di file è uno strumento comune per i data scientist, e viene identificato dal suffisso o estensione `.ipynb`.
|
||||||
|
|
||||||
|
I notebook sono un ambiente interattivo che consente allo sviluppatore di scrivere codice, aggiungere note e scrivere documentazione attorno al codice il che è particolarmente utile per progetti sperimentali o orientati alla ricerca.
|
||||||
|
|
||||||
|
### Esercizio - lavorare con un notebook
|
||||||
|
|
||||||
|
In questa cartella, si troverà il file _notebook.ipynb_.
|
||||||
|
|
||||||
|
1. Aprire _notebook.ipynb_ in Visual Studio Code.
|
||||||
|
|
||||||
|
Un server Jupyter verrà lanciato con Python 3+. Si troveranno aree del notebook che possono essere `eseguite`, pezzi di codice. Si può eseguire un blocco di codice selezionando l'icona che assomiglia a un bottone di riproduzione.
|
||||||
|
|
||||||
|
1. Selezionare l'icona `md` e aggiungere un poco di markdown, e il seguente testo **# Benvenuto nel tuo notebook**.
|
||||||
|
|
||||||
|
Poi, aggiungere un blocco di codice Python.
|
||||||
|
|
||||||
|
1. Digitare **print('hello notebook')** nell'area riservata al codice.
|
||||||
|
1. Selezionare la freccia per eseguire il codice.
|
||||||
|
|
||||||
|
Si dovrebbe vedere stampata la seguente frase:
|
||||||
|
|
||||||
|
```output
|
||||||
|
hello notebook
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Si può inframezzare il codice con commenti per auto documentare il notebook.
|
||||||
|
|
||||||
|
✅ Si pensi per un minuto all'ambiente di lavoro di uno sviluppatore web rispetto a quello di un data scientist.
|
||||||
|
|
||||||
|
## Scikit-learn installato e funzionante
|
||||||
|
|
||||||
|
Adesso che Python è impostato nel proprio ambiente locale, e si è familiari con i notebook Jupyter, si acquisterà ora confidenza con Scikit-learn (si pronuncia con la `si` della parola inglese `science`). Scikit-learn fornisce una [API estensiva](https://scikit-learn.org/stable/modules/classes.html#api-ref) che aiuta a eseguire attività ML.
|
||||||
|
|
||||||
|
Stando al loro [sito web](https://scikit-learn.org/stable/getting_started.html), "Scikit-learn è una libreria di machine learning open source che supporta l'apprendimento assistito (supervised learning) e non assistito (unsuperivised learnin). Fornisce anche strumenti vari per l'adattamento del modello, la pre-elaborazione dei dati, la selezione e la valutazione dei modelli e molte altre utilità."
|
||||||
|
|
||||||
|
In questo corso, si userà Scikit-learn e altri strumenti per costruire modelli di machine learning per eseguire quelle che vengono chiamate attività di 'machine learning tradizionale'. Si sono deliberamente evitate le reti neurali e il deep learning visto che saranno meglio trattati nel prossimo programma di studi 'AI per Principianti'.
|
||||||
|
|
||||||
|
Scikit-learn rende semplice costruire modelli e valutarli per l'uso. Si concentra principalmente sull'utilizzo di dati numerici e contiene diversi insiemi di dati già pronti per l'uso come strumenti di apprendimento. Include anche modelli pre-costruiti per gli studenti da provare. Si esplora ora il processo di caricamento dei dati preconfezionati, e, utilizzando un modello di stimatore incorporato, un primo modello ML con Scikit-Learn con alcuni dati di base.
|
||||||
|
|
||||||
|
## Esercizio - Il Primo notebook Scikit-learn
|
||||||
|
|
||||||
|
> Questo tutorial è stato ispirato dall'[esempio di regressione lineare](https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py) nel sito web di Scikit-learn.
|
||||||
|
|
||||||
|
Nel file _notebook.ipynb_ associato a questa lezione, svuotare tutte le celle usando l'icona cestino ('trash can').
|
||||||
|
|
||||||
|
In questa sezione, di lavorerà con un piccolo insieme di dati sul diabete che è incorporato in Scikit-learn per scopi di apprendimento. Si immagini di voler testare un trattamento per i pazienti diabetici. I modelli di machine learning potrebbero essere di aiuto nel determinare quali pazienti risponderebbero meglio al trattamento, in base a combinazioni di variabili. Anche un modello di regressione molto semplice, quando visualizzato, potrebbe mostrare informazioni sulle variabili che aiuteranno a organizzare le sperimentazioni cliniche teoriche.
|
||||||
|
|
||||||
|
✅ Esistono molti tipi di metodi di regressione e quale scegliere dipende dalla risposta che si sta cercando. Se si vuole prevedere l'altezza probabile per una persona di una data età, si dovrebbe usare la regressione lineare, visto che si sta cercando un **valore numerico**. Se si è interessati a scoprire se un tipo di cucina dovrebbe essere considerato vegano o no, si sta cercando un'**assegnazione di categoria** quindi si dovrebbe usare la regressione logistica. Si imparerà di più sulla regressione logistica in seguito. Si pensi ad alcune domande che si possono chiedere ai dati e quale di questi metodi sarebbe più appropriato.
|
||||||
|
|
||||||
|
Si inizia con questa attività.
|
||||||
|
|
||||||
|
### Importare le librerie
|
||||||
|
|
||||||
|
Per questo compito verranno importate alcune librerie:
|
||||||
|
|
||||||
|
- **matplotlib**. E' un utile [strumento grafico](https://matplotlib.org/) e verrà usato per creare una trama a linee.
|
||||||
|
- **numpy**. [numpy](https://numpy.org/doc/stable/user/whatisnumpy.html) è una libreira utile per gestire i dati numerici in Python.
|
||||||
|
- **sklearn**. Questa è la libreria Scikit-learn.
|
||||||
|
|
||||||
|
Importare alcune librerie che saranno di aiuto per le proprie attività.
|
||||||
|
|
||||||
|
1. Con il seguente codice si aggiungono le importazioni:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import numpy as np
|
||||||
|
from sklearn import datasets, linear_model, model_selection
|
||||||
|
```
|
||||||
|
|
||||||
|
Qui sopra vengono importati `matplottlib`, e `numpy`, da `sklearn` si importa `datasets`, `linear_model` e `model_selection`. `model_selection` viene usato per dividere i dati negli insiemi di addestramento e test.
|
||||||
|
|
||||||
|
### L'insieme di dati riguardante il diabete
|
||||||
|
|
||||||
|
L'[insieme dei dati sul diabete](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset) include 442 campioni di dati sul diabete, con 10 variabili caratteristiche, alcune delle quali includono:
|
||||||
|
|
||||||
|
- age (età): età in anni
|
||||||
|
- bmi: indice di massa corporea (body mass index)
|
||||||
|
- bp: media pressione sanguinea
|
||||||
|
- s1 tc: Cellule T (un tipo di leucocito)
|
||||||
|
|
||||||
|
✅ Questo insieme di dati include il concetto di "sesso" come caratteristica variabile importante per la ricerca sul diabete. Molti insiemi di dati medici includono questo tipo di classificazione binaria. Si rifletta su come categorizzazioni come questa potrebbe escludere alcune parti di una popolazione dai trattamenti.
|
||||||
|
|
||||||
|
Ora si caricano i dati di X e y.
|
||||||
|
|
||||||
|
> 🎓 Si ricordi, questo è apprendimento supervisionato (supervised learning), e serve dare un nome all'obiettivo 'y'.
|
||||||
|
|
||||||
|
In una nuova cella di codice, caricare l'insieme di dati sul diabete chiamando `load_diabetes()`. Il parametro `return_X_y=True` segnala che `X` sarà una matrice di dati e `y` sarà l'obiettivo della regressione.
|
||||||
|
|
||||||
|
1. Si aggiungono alcuni comandi di stampa per msotrare la forma della matrice di dati e i suoi primi elementi:
|
||||||
|
|
||||||
|
```python
|
||||||
|
X, y = datasets.load_diabetes(return_X_y=True)
|
||||||
|
print(X.shape)
|
||||||
|
print(X[0])
|
||||||
|
```
|
||||||
|
|
||||||
|
Quella che viene ritornata è una tuple. Quello che si sta facento è assegnare i primi due valori della tupla a `X` e `y` rispettivamente. Per saperne di più sulle [tuples](https://wikipedia.org/wiki/Tuple).
|
||||||
|
|
||||||
|
Si può vedere che questi dati hanno 442 elementi divisi in array di 10 elementi:
|
||||||
|
|
||||||
|
```text
|
||||||
|
(442, 10)
|
||||||
|
[ 0.03807591 0.05068012 0.06169621 0.02187235 -0.0442235 -0.03482076
|
||||||
|
-0.04340085 -0.00259226 0.01990842 -0.01764613]
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ Si rifletta sulla relazione tra i dati e l'obiettivo di regressione. La regressione lineare prevede le relazioni tra la caratteristica X e la variabile di destinazione y. Si può trovare l'[obiettivo](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset) per l'insieme di dati sul diabete nella documentazione? Cosa dimostra questo insieme di dati, dato quell'obiettivo?
|
||||||
|
|
||||||
|
2. Successivamente, selezionare una porzione di questo insieme di dati da tracciare sistemandola in un nuovo array usando la funzione di numpy's `newaxis`. Verrà usata la regressione lineare per generare una linea tra i valori in questi dati secondo il modello che determina.
|
||||||
|
|
||||||
|
```python
|
||||||
|
X = X[:, np.newaxis, 2]
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ A piacere, stampare i dati per verificarne la forma.
|
||||||
|
|
||||||
|
3. Ora che si hanno dei dati pronti per essere tracciati, è possibile vedere se una macchina può aiutare a determinare una divisione logica tra i numeri in questo insieme di dati. Per fare ciò, è necessario dividere sia i dati (X) che l'obiettivo (y) in insiemi di test e addestamento. Scikit-learn ha un modo semplice per farlo; si possono dividere i dati di prova in un determinato punto.
|
||||||
|
|
||||||
|
```python
|
||||||
|
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33)
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Ora si è pronti ad addestare il modello! Caricare il modello di regressione lineare e addestrarlo con i propri insiemi di addestramento X e y usando `model.fit()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
model = linear_model.LinearRegression()
|
||||||
|
model.fit(X_train, y_train)
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ `model.fit()` è una funzione che si vedrà in molte librerie ML tipo TensorFlow
|
||||||
|
|
||||||
|
5. Successivamente creare una previsione usando i dati di test, con la funzione `predict()`. Questo servirà per tracciare la linea tra i gruppi di dati
|
||||||
|
|
||||||
|
```python
|
||||||
|
y_pred = model.predict(X_test)
|
||||||
|
```
|
||||||
|
|
||||||
|
6. Ora è il momento di mostrare i dati in un tracciato. Matplotlib è uno strumento molto utile per questo compito. Si crei un grafico a dispersione (scatterplot) di tutti i dati del test X e y e si utilizzi la previsione per disegnare una linea nel luogo più appropriato, tra i raggruppamenti dei dati del modello.
|
||||||
|
|
||||||
|
```python
|
||||||
|
plt.scatter(X_test, y_test, color='black')
|
||||||
|
plt.plot(X_test, y_pred, color='blue', linewidth=3)
|
||||||
|
plt.show()
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
✅ Si pensi a cosa sta succedendo qui. Una linea retta scorre attraverso molti piccoli punti dati, ma cosa sta facendo esattamente? Si può capire come si dovrebbe utilizzare questa linea per prevedere dove un nuovo punto di dati non noto dovrebbe adattarsi alla relazione con l'asse y del tracciato? Si cerchi di mettere in parole l'uso pratico di questo modello.
|
||||||
|
|
||||||
|
Congratulazioni, si è costruito il primo modello di regressione lineare, creato una previsione con esso, e visualizzata in una tracciato!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀Sfida
|
||||||
|
|
||||||
|
Tracciare una variabile diversa da questo insieme di dati. Suggerimento: modificare questa riga: `X = X[:, np.newaxis, 2]`. Dato l'obiettivo di questo insieme di dati, cosa si potrebbe riuscire a scoprire circa la progressione del diabete come matattia?
|
||||||
|
|
||||||
|
## [Qui post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/10/)
|
||||||
|
|
||||||
|
## Riepilogo e Auto Apprendimento
|
||||||
|
|
||||||
|
In questo tutorial, si è lavorato con una semplice regressione lineare, piuttosto che una regressione univariata o multipla. Ci so informi circa le differenze tra questi metodi oppure si dia uno sguardo a [questo video](https://www.coursera.org/lecture/quantifying-relationships-regression-models/linear-vs-nonlinear-categorical-variables-ai2Ef)
|
||||||
|
|
||||||
|
Si legga di più sul concetto di regressione e si pensi a quale tipo di domande potrebbero trovare risposta con questa tecnica. Seguire questo [tutorial](https://docs.microsoft.com/learn/modules/train-evaluate-regression-models?WT.mc_id=academic-15963-cxa) per approfondire la propria conoscenza.
|
||||||
|
|
||||||
|
## Compito
|
||||||
|
|
||||||
|
[Un insieme di dati diverso](assignment.it.md)
|
||||||
|
|
@ -0,0 +1,13 @@
|
|||||||
|
# Regressione con Scikit-learn
|
||||||
|
|
||||||
|
## Istruzioni
|
||||||
|
|
||||||
|
Dare un'occhiata all'[insieme di dati Linnerud](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_linnerud.html#sklearn.datasets.load_linnerud) in Scikit-learn. Questo insieme di dati ha [obiettivi](https://scikit-learn.org/stable/datasets/toy_dataset.html#linnerrud-dataset) multipli: "Consiste di tre variabili di esercizio (dati) e tre variabili fisiologiche (obiettivo) raccolte da venti uomini di mezza età in un fitness club".
|
||||||
|
|
||||||
|
Con parole proprie, descrivere come creare un modello di Regressione che tracci la relazione tra il punto vita e il numero di addominali realizzati. Fare lo stesso per gli altri punti dati in questo insieme di dati.
|
||||||
|
|
||||||
|
## Rubrica
|
||||||
|
|
||||||
|
| Criteri | Ottimo | Adeguato | Necessita miglioramento |
|
||||||
|
| ------------------------------ | ----------------------------------- | ----------------------------- | -------------------------- |
|
||||||
|
| Inviare un paragrafo descrittivo | Viene presentato un paragrafo ben scritto | Vengono inviate alcune frasi | Non viene fornita alcuna descrizione |
|
@ -0,0 +1,13 @@
|
|||||||
|
# Scikit-learnを用いた回帰
|
||||||
|
|
||||||
|
## 課題の指示
|
||||||
|
|
||||||
|
Scikit-learnで[Linnerud dataset](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_linnerud.html#sklearn.datasets.load_linnerud) を見てみましょう。このデータセットは複数の[ターゲット](https://scikit-learn.org/stable/datasets/toy_dataset.html#linnerrud-dataset) を持っています。フィットネスクラブで20人の中年男性から収集した3つの運動変数(data)と3つの生理変数(target)で構成されています。
|
||||||
|
|
||||||
|
あなた自身の言葉で、ウエストラインと腹筋の回数との関係をプロットする回帰モデルの作成方法を説明してください。このデータセットの他のデータポイントについても同様に説明してみてください。
|
||||||
|
|
||||||
|
## ルーブリック
|
||||||
|
|
||||||
|
| 指標 | 模範的 | 適切 | 要改善 |
|
||||||
|
| ------------------------------ | ----------------------------------- | ----------------------------- | -------------------------- |
|
||||||
|
| 説明文を提出してください。 | よく書けた文章が提出されている。 | いくつかの文章が提出されている。 | 文章が提出されていません。 |
|
After Width: | Height: | Size: 1.0 MiB |
After Width: | Height: | Size: 125 KiB |
@ -0,0 +1,644 @@
|
|||||||
|
{
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 0,
|
||||||
|
"metadata": {
|
||||||
|
"colab": {
|
||||||
|
"name": "lesson_2-R.ipynb",
|
||||||
|
"provenance": [],
|
||||||
|
"collapsed_sections": [],
|
||||||
|
"toc_visible": true
|
||||||
|
},
|
||||||
|
"kernelspec": {
|
||||||
|
"name": "ir",
|
||||||
|
"display_name": "R"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"name": "R"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "Pg5aexcOPqAZ"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Build a regression model: prepare and visualize data\n",
|
||||||
|
"\n",
|
||||||
|
"## **Linear Regression for Pumpkins - Lesson 2**\n",
|
||||||
|
"#### Introduction\n",
|
||||||
|
"\n",
|
||||||
|
"Now that you are set up with the tools you need to start tackling machine learning model building with Tidymodels and the Tidyverse, you are ready to start asking questions of your data. As you work with data and apply ML solutions, it's very important to understand how to ask the right question to properly unlock the potentials of your dataset.\n",
|
||||||
|
"\n",
|
||||||
|
"In this lesson, you will learn:\n",
|
||||||
|
"\n",
|
||||||
|
"- How to prepare your data for model-building.\n",
|
||||||
|
"\n",
|
||||||
|
"- How to use `ggplot2` for data visualization.\n",
|
||||||
|
"\n",
|
||||||
|
"The question you need answered will determine what type of ML algorithms you will leverage. And the quality of the answer you get back will be heavily dependent on the nature of your data.\n",
|
||||||
|
"\n",
|
||||||
|
"Let's see this by working through a practical exercise.\n",
|
||||||
|
"\n",
|
||||||
|
"<br>Artwork by \\@allison_horst"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "dc5WhyVdXAjR"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 1. Importing pumpkins data and summoning the Tidyverse\n",
|
||||||
|
"\n",
|
||||||
|
"We'll require the following packages to slice and dice this lesson:\n",
|
||||||
|
"\n",
|
||||||
|
"- `tidyverse`: The [tidyverse](https://www.tidyverse.org/) is a [collection of R packages](https://www.tidyverse.org/packages) designed to makes data science faster, easier and more fun!\n",
|
||||||
|
"\n",
|
||||||
|
"You can have them installed as:\n",
|
||||||
|
"\n",
|
||||||
|
"`install.packages(c(\"tidyverse\"))`\n",
|
||||||
|
"\n",
|
||||||
|
"The script below checks whether you have the packages required to complete this module and installs them for you in case some are missing."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "GqPYUZgfXOBt"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"if (!require(\"pacman\")) install.packages(\"pacman\")\n",
|
||||||
|
"pacman::p_load(tidyverse)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "kvjDTPDSXRr2"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Now, let's fire up some packages and load the [data](https://github.com/microsoft/ML-For-Beginners/blob/main/2-Regression/data/US-pumpkins.csv) provided for this lesson!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "VMri-t2zXqgD"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Load the core Tidyverse packages\n",
|
||||||
|
"library(tidyverse)\n",
|
||||||
|
"\n",
|
||||||
|
"# Import the pumpkins data\n",
|
||||||
|
"pumpkins <- read_csv(file = \"https://raw.githubusercontent.com/microsoft/ML-For-Beginners/main/2-Regression/data/US-pumpkins.csv\")\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Get a glimpse and dimensions of the data\n",
|
||||||
|
"glimpse(pumpkins)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Print the first 50 rows of the data set\n",
|
||||||
|
"pumpkins %>% \n",
|
||||||
|
" slice_head(n =50)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "REWcIv9yX29v"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"A quick `glimpse()` immediately shows that there are blanks and a mix of strings (`chr`) and numeric data (`dbl`). The `Date` is of type character and there's also a strange column called `Package` where the data is a mix between `sacks`, `bins` and other values. The data, in fact, is a bit of a mess 😤.\n",
|
||||||
|
"\n",
|
||||||
|
"In fact, it is not very common to be gifted a dataset that is completely ready to use to create a ML model out of the box. But worry not, in this lesson, you will learn how to prepare a raw dataset using standard R libraries 🧑🔧. You will also learn various techniques to visualize the data.📈📊\n",
|
||||||
|
"<br>\n",
|
||||||
|
"\n",
|
||||||
|
"> A refresher: The pipe operator (`%>%`) performs operations in logical sequence by passing an object forward into a function or call expression. You can think of the pipe operator as saying \"and then\" in your code.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "Zxfb3AM5YbUe"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 2. Check for missing data\n",
|
||||||
|
"\n",
|
||||||
|
"One of the most common issues data scientists need to deal with is incomplete or missing data. R represents missing, or unknown values, with special sentinel value: `NA` (Not Available).\n",
|
||||||
|
"\n",
|
||||||
|
"So how would we know that the data frame contains missing values?\n",
|
||||||
|
"<br>\n",
|
||||||
|
"- One straight forward way would be to use the base R function `anyNA` which returns the logical objects `TRUE` or `FALSE`"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "G--DQutAYltj"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"pumpkins %>% \n",
|
||||||
|
" anyNA()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "mU-7-SB6YokF"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Great, there seems to be some missing data! That's a good place to start.\n",
|
||||||
|
"\n",
|
||||||
|
"- Another way would be to use the function `is.na()` that indicates which individual column elements are missing with a logical `TRUE`."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "W-DxDOR4YxSW"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"pumpkins %>% \n",
|
||||||
|
" is.na() %>% \n",
|
||||||
|
" head(n = 7)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "xUWxipKYY0o7"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Okay, got the job done but with a large data frame such as this, it would be inefficient and practically impossible to review all of the rows and columns individually😴.\n",
|
||||||
|
"\n",
|
||||||
|
"- A more intuitive way would be to calculate the sum of the missing values for each column:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "ZRBWV6P9ZArL"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"pumpkins %>% \n",
|
||||||
|
" is.na() %>% \n",
|
||||||
|
" colSums()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "9gv-crB6ZD1Y"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Much better! There is missing data, but maybe it won't matter for the task at hand. Let's see what further analysis brings forth.\n",
|
||||||
|
"\n",
|
||||||
|
"> Along with the awesome sets of packages and functions, R has a very good documentation. For instance, use `help(colSums)` or `?colSums` to find out more about the function."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "o4jLY5-VZO2C"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 3. Dplyr: A Grammar of Data Manipulation\n",
|
||||||
|
"\n",
|
||||||
|
"<br/>Artwork by \\@allison_horst"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "i5o33MQBZWWw"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"[`dplyr`](https://dplyr.tidyverse.org/), a package in the Tidyverse, is a grammar of data manipulation that provides a consistent set of verbs that help you solve the most common data manipulation challenges. In this section, we'll explore some of dplyr's verbs!\n",
|
||||||
|
"<br>\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "x3VGMAGBZiUr"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"#### dplyr::select()\n",
|
||||||
|
"\n",
|
||||||
|
"`select()` is a function in the package `dplyr` which helps you pick columns to keep or exclude.\n",
|
||||||
|
"\n",
|
||||||
|
"To make your data frame easier to work with, drop several of its columns, using `select()`, keeping only the columns you need.\n",
|
||||||
|
"\n",
|
||||||
|
"For instance, in this exercise, our analysis will involve the columns `Package`, `Low Price`, `High Price` and `Date`. Let's select these columns."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "F_FgxQnVZnM0"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Select desired columns\n",
|
||||||
|
"pumpkins <- pumpkins %>% \n",
|
||||||
|
" select(Package, `Low Price`, `High Price`, Date)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"# Print data set\n",
|
||||||
|
"pumpkins %>% \n",
|
||||||
|
" slice_head(n = 5)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "2KKo0Ed9Z1VB"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"#### dplyr::mutate()\n",
|
||||||
|
"\n",
|
||||||
|
"`mutate()` is a function in the package `dplyr` which helps you create or modify columns, while keeping the existing columns.\n",
|
||||||
|
"\n",
|
||||||
|
"The general structure of mutate is:\n",
|
||||||
|
"\n",
|
||||||
|
"`data %>% mutate(new_column_name = what_it_contains)`\n",
|
||||||
|
"\n",
|
||||||
|
"Let's take `mutate` out for a spin using the `Date` column by doing the following operations:\n",
|
||||||
|
"\n",
|
||||||
|
"1. Convert the dates (currently of type character) to a month format (these are US dates, so the format is `MM/DD/YYYY`).\n",
|
||||||
|
"\n",
|
||||||
|
"2. Extract the month from the dates to a new column.\n",
|
||||||
|
"\n",
|
||||||
|
"In R, the package [lubridate](https://lubridate.tidyverse.org/) makes it easier to work with Date-time data. So, let's use `dplyr::mutate()`, `lubridate::mdy()`, `lubridate::month()` and see how to achieve the above objectives. We can drop the Date column since we won't be needing it again in subsequent operations."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "5joszIVSZ6xe"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Load lubridate\n",
|
||||||
|
"library(lubridate)\n",
|
||||||
|
"\n",
|
||||||
|
"pumpkins <- pumpkins %>% \n",
|
||||||
|
" # Convert the Date column to a date object\n",
|
||||||
|
" mutate(Date = mdy(Date)) %>% \n",
|
||||||
|
" # Extract month from Date\n",
|
||||||
|
" mutate(Month = month(Date)) %>% \n",
|
||||||
|
" # Drop Date column\n",
|
||||||
|
" select(-Date)\n",
|
||||||
|
"\n",
|
||||||
|
"# View the first few rows\n",
|
||||||
|
"pumpkins %>% \n",
|
||||||
|
" slice_head(n = 7)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "nIgLjNMCZ-6Y"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Woohoo! 🤩\n",
|
||||||
|
"\n",
|
||||||
|
"Next, let's create a new column `Price`, which represents the average price of a pumpkin. Now, let's take the average of the `Low Price` and `High Price` columns to populate the new Price column.\n",
|
||||||
|
"<br>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "Zo0BsqqtaJw2"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Create a new column Price\n",
|
||||||
|
"pumpkins <- pumpkins %>% \n",
|
||||||
|
" mutate(Price = (`Low Price` + `High Price`)/2)\n",
|
||||||
|
"\n",
|
||||||
|
"# View the first few rows of the data\n",
|
||||||
|
"pumpkins %>% \n",
|
||||||
|
" slice_head(n = 5)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "p77WZr-9aQAR"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Yeees!💪\n",
|
||||||
|
"\n",
|
||||||
|
"\"But wait!\", you'll say after skimming through the whole data set with `View(pumpkins)`, \"There's something odd here!\"🤔\n",
|
||||||
|
"\n",
|
||||||
|
"If you look at the `Package` column, pumpkins are sold in many different configurations. Some are sold in `1 1/9 bushel` measures, and some in `1/2 bushel` measures, some per pumpkin, some per pound, and some in big boxes with varying widths.\n",
|
||||||
|
"\n",
|
||||||
|
"Let's verify this:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "XISGfh0IaUy6"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Verify the distinct observations in Package column\n",
|
||||||
|
"pumpkins %>% \n",
|
||||||
|
" distinct(Package)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "7sMjiVujaZxY"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Amazing!👏\n",
|
||||||
|
"\n",
|
||||||
|
"Pumpkins seem to be very hard to weigh consistently, so let's filter them by selecting only pumpkins with the string *bushel* in the `Package` column and put this in a new data frame `new_pumpkins`.\n",
|
||||||
|
"<br>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "L8Qfcs92ageF"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"#### dplyr::filter() and stringr::str_detect()\n",
|
||||||
|
"\n",
|
||||||
|
"[`dplyr::filter()`](https://dplyr.tidyverse.org/reference/filter.html): creates a subset of the data only containing **rows** that satisfy your conditions, in this case, pumpkins with the string *bushel* in the `Package` column.\n",
|
||||||
|
"\n",
|
||||||
|
"[stringr::str_detect()](https://stringr.tidyverse.org/reference/str_detect.html): detects the presence or absence of a pattern in a string.\n",
|
||||||
|
"\n",
|
||||||
|
"The [`stringr`](https://github.com/tidyverse/stringr) package provides simple functions for common string operations."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "hy_SGYREampd"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Retain only pumpkins with \"bushel\"\n",
|
||||||
|
"new_pumpkins <- pumpkins %>% \n",
|
||||||
|
" filter(str_detect(Package, \"bushel\"))\n",
|
||||||
|
"\n",
|
||||||
|
"# Get the dimensions of the new data\n",
|
||||||
|
"dim(new_pumpkins)\n",
|
||||||
|
"\n",
|
||||||
|
"# View a few rows of the new data\n",
|
||||||
|
"new_pumpkins %>% \n",
|
||||||
|
" slice_head(n = 5)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "VrDwF031avlR"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"You can see that we have narrowed down to 415 or so rows of data containing pumpkins by the bushel.🤩\n",
|
||||||
|
"<br>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "mLpw2jH4a0tx"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"#### dplyr::case_when()\n",
|
||||||
|
"\n",
|
||||||
|
"**But wait! There's one more thing to do**\n",
|
||||||
|
"\n",
|
||||||
|
"Did you notice that the bushel amount varies per row? You need to normalize the pricing so that you show the pricing per bushel, not per 1 1/9 or 1/2 bushel. Time to do some math to standardize it.\n",
|
||||||
|
"\n",
|
||||||
|
"We'll use the function [`case_when()`](https://dplyr.tidyverse.org/reference/case_when.html) to *mutate* the Price column depending on some conditions. `case_when` allows you to vectorise multiple `if_else()`statements.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "P68kLVQmbM6I"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Convert the price if the Package contains fractional bushel values\n",
|
||||||
|
"new_pumpkins <- new_pumpkins %>% \n",
|
||||||
|
" mutate(Price = case_when(\n",
|
||||||
|
" str_detect(Package, \"1 1/9\") ~ Price/(1 + 1/9),\n",
|
||||||
|
" str_detect(Package, \"1/2\") ~ Price/(1/2),\n",
|
||||||
|
" TRUE ~ Price))\n",
|
||||||
|
"\n",
|
||||||
|
"# View the first few rows of the data\n",
|
||||||
|
"new_pumpkins %>% \n",
|
||||||
|
" slice_head(n = 30)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "pS2GNPagbSdb"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Now, we can analyze the pricing per unit based on their bushel measurement. All this study of bushels of pumpkins, however, goes to show how very `important` it is to `understand the nature of your data`!\n",
|
||||||
|
"\n",
|
||||||
|
"> ✅ According to [The Spruce Eats](https://www.thespruceeats.com/how-much-is-a-bushel-1389308), a bushel's weight depends on the type of produce, as it's a volume measurement. \"A bushel of tomatoes, for example, is supposed to weigh 56 pounds... Leaves and greens take up more space with less weight, so a bushel of spinach is only 20 pounds.\" It's all pretty complicated! Let's not bother with making a bushel-to-pound conversion, and instead price by the bushel. All this study of bushels of pumpkins, however, goes to show how very important it is to understand the nature of your data!\n",
|
||||||
|
">\n",
|
||||||
|
"> ✅ Did you notice that pumpkins sold by the half-bushel are very expensive? Can you figure out why? Hint: little pumpkins are way pricier than big ones, probably because there are so many more of them per bushel, given the unused space taken by one big hollow pie pumpkin.\n",
|
||||||
|
"<br>\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "qql1SowfbdnP"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Now lastly, for the sheer sake of adventure 💁♀️, let's also move the Month column to the first position i.e `before` column `Package`.\n",
|
||||||
|
"\n",
|
||||||
|
"`dplyr::relocate()` is used to change column positions."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "JJ1x6kw8bixF"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Create a new data frame new_pumpkins\n",
|
||||||
|
"new_pumpkins <- new_pumpkins %>% \n",
|
||||||
|
" relocate(Month, .before = Package)\n",
|
||||||
|
"\n",
|
||||||
|
"new_pumpkins %>% \n",
|
||||||
|
" slice_head(n = 7)"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "y8TJ0Za_bn5Y"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Good job!👌 You now have a clean, tidy dataset on which you can build your new regression model!\n",
|
||||||
|
"<br>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "mYSH6-EtbvNa"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"## 4. Data visualization with ggplot2\n",
|
||||||
|
"\n",
|
||||||
|
"{width=\"600\"}\n",
|
||||||
|
"\n",
|
||||||
|
"There is a *wise* saying that goes like this:\n",
|
||||||
|
"\n",
|
||||||
|
"> \"The simple graph has brought more information to the data analyst's mind than any other device.\" --- John Tukey\n",
|
||||||
|
"\n",
|
||||||
|
"Part of the data scientist's role is to demonstrate the quality and nature of the data they are working with. To do this, they often create interesting visualizations, or plots, graphs, and charts, showing different aspects of data. In this way, they are able to visually show relationships and gaps that are otherwise hard to uncover.\n",
|
||||||
|
"\n",
|
||||||
|
"Visualizations can also help determine the machine learning technique most appropriate for the data. A scatterplot that seems to follow a line, for example, indicates that the data is a good candidate for a linear regression exercise.\n",
|
||||||
|
"\n",
|
||||||
|
"R offers a number of several systems for making graphs, but [`ggplot2`](https://ggplot2.tidyverse.org/index.html) is one of the most elegant and most versatile. `ggplot2` allows you to compose graphs by **combining independent components**.\n",
|
||||||
|
"\n",
|
||||||
|
"Let's start with a simple scatter plot for the Price and Month columns.\n",
|
||||||
|
"\n",
|
||||||
|
"So in this case, we'll start with [`ggplot()`](https://ggplot2.tidyverse.org/reference/ggplot.html), supply a dataset and aesthetic mapping (with [`aes()`](https://ggplot2.tidyverse.org/reference/aes.html)) then add a layers (like [`geom_point()`](https://ggplot2.tidyverse.org/reference/geom_point.html)) for scatter plots.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "g2YjnGeOcLo4"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Set a theme for the plots\n",
|
||||||
|
"theme_set(theme_light())\n",
|
||||||
|
"\n",
|
||||||
|
"# Create a scatter plot\n",
|
||||||
|
"p <- ggplot(data = new_pumpkins, aes(x = Price, y = Month))\n",
|
||||||
|
"p + geom_point()"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "Ml7SDCLQcPvE"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Is this a useful plot 🤷? Does anything about it surprise you?\n",
|
||||||
|
"\n",
|
||||||
|
"It's not particularly useful as all it does is display in your data as a spread of points in a given month.\n",
|
||||||
|
"<br>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "jMakvJZIcVkh"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"### **How do we make it useful?**\n",
|
||||||
|
"\n",
|
||||||
|
"To get charts to display useful data, you usually need to group the data somehow. For instance in our case, finding the average price of pumpkins for each month would provide more insights to the underlying patterns in our data. This leads us to one more **dplyr** flyby:\n",
|
||||||
|
"\n",
|
||||||
|
"#### `dplyr::group_by() %>% summarize()`\n",
|
||||||
|
"\n",
|
||||||
|
"Grouped aggregation in R can be easily computed using\n",
|
||||||
|
"\n",
|
||||||
|
"`dplyr::group_by() %>% summarize()`\n",
|
||||||
|
"\n",
|
||||||
|
"- `dplyr::group_by()` changes the unit of analysis from the complete dataset to individual groups such as per month.\n",
|
||||||
|
"\n",
|
||||||
|
"- `dplyr::summarize()` creates a new data frame with one column for each grouping variable and one column for each of the summary statistics that you have specified.\n",
|
||||||
|
"\n",
|
||||||
|
"For example, we can use the `dplyr::group_by() %>% summarize()` to group the pumpkins into groups based on the **Month** columns and then find the **mean price** for each month."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "6kVSUa2Bcilf"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Find the average price of pumpkins per month\n",
|
||||||
|
"new_pumpkins %>%\n",
|
||||||
|
" group_by(Month) %>% \n",
|
||||||
|
" summarise(mean_price = mean(Price))"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "Kds48GUBcj3W"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"Succinct!✨\n",
|
||||||
|
"\n",
|
||||||
|
"Categorical features such as months are better represented using a bar plot 📊. The layers responsible for bar charts are `geom_bar()` and `geom_col()`. Consult `?geom_bar` to find out more.\n",
|
||||||
|
"\n",
|
||||||
|
"Let's whip up one!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"metadata": {
|
||||||
|
"id": "VNbU1S3BcrxO"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"# Find the average price of pumpkins per month then plot a bar chart\n",
|
||||||
|
"new_pumpkins %>%\n",
|
||||||
|
" group_by(Month) %>% \n",
|
||||||
|
" summarise(mean_price = mean(Price)) %>% \n",
|
||||||
|
" ggplot(aes(x = Month, y = mean_price)) +\n",
|
||||||
|
" geom_col(fill = \"midnightblue\", alpha = 0.7) +\n",
|
||||||
|
" ylab(\"Pumpkin Price\")"
|
||||||
|
],
|
||||||
|
"execution_count": null,
|
||||||
|
"outputs": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {
|
||||||
|
"id": "zDm0VOzzcuzR"
|
||||||
|
},
|
||||||
|
"source": [
|
||||||
|
"🤩🤩This is a more useful data visualization! It seems to indicate that the highest price for pumpkins occurs in September and October. Does that meet your expectation? Why or why not?\n",
|
||||||
|
"\n",
|
||||||
|
"Congratulations on finishing the second lesson 👏! You prepared your data for model building, then uncovered more insights using visualizations!"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
@ -0,0 +1,345 @@
|
|||||||
|
---
|
||||||
|
title: 'Build a regression model: prepare and visualize data'
|
||||||
|
output:
|
||||||
|
html_document:
|
||||||
|
df_print: paged
|
||||||
|
theme: flatly
|
||||||
|
highlight: breezedark
|
||||||
|
toc: yes
|
||||||
|
toc_float: yes
|
||||||
|
code_download: yes
|
||||||
|
---
|
||||||
|
|
||||||
|
## **Linear Regression for Pumpkins - Lesson 2**
|
||||||
|
|
||||||
|
#### Introduction
|
||||||
|
|
||||||
|
Now that you are set up with the tools you need to start tackling machine learning model building with Tidymodels and the Tidyverse, you are ready to start asking questions of your data. As you work with data and apply ML solutions, it's very important to understand how to ask the right question to properly unlock the potentials of your dataset.
|
||||||
|
|
||||||
|
In this lesson, you will learn:
|
||||||
|
|
||||||
|
- How to prepare your data for model-building.
|
||||||
|
|
||||||
|
- How to use `ggplot2` for data visualization.
|
||||||
|
|
||||||
|
The question you need answered will determine what type of ML algorithms you will leverage. And the quality of the answer you get back will be heavily dependent on the nature of your data.
|
||||||
|
|
||||||
|
Let's see this by working through a practical exercise.
|
||||||
|
|
||||||
|
{width="700"}
|
||||||
|
|
||||||
|
## 1. Importing pumpkins data and summoning the Tidyverse
|
||||||
|
|
||||||
|
We'll require the following packages to slice and dice this lesson:
|
||||||
|
|
||||||
|
- `tidyverse`: The [tidyverse](https://www.tidyverse.org/) is a [collection of R packages](https://www.tidyverse.org/packages) designed to makes data science faster, easier and more fun!
|
||||||
|
|
||||||
|
You can have them installed as:
|
||||||
|
|
||||||
|
`install.packages(c("tidyverse"))`
|
||||||
|
|
||||||
|
The script below checks whether you have the packages required to complete this module and installs them for you in case they are missing.
|
||||||
|
|
||||||
|
```{r, message=F, warning=F}
|
||||||
|
if (!require("pacman")) install.packages("pacman")
|
||||||
|
pacman::p_load(tidyverse)
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, let's fire up some packages and load the [data](https://github.com/microsoft/ML-For-Beginners/blob/main/2-Regression/data/US-pumpkins.csv) provided for this lesson!
|
||||||
|
|
||||||
|
```{r load_tidy_verse_models, message=F, warning=F}
|
||||||
|
# Load the core Tidyverse packages
|
||||||
|
library(tidyverse)
|
||||||
|
|
||||||
|
# Import the pumpkins data
|
||||||
|
pumpkins <- read_csv(file = "https://raw.githubusercontent.com/microsoft/ML-For-Beginners/main/2-Regression/data/US-pumpkins.csv")
|
||||||
|
|
||||||
|
|
||||||
|
# Get a glimpse and dimensions of the data
|
||||||
|
glimpse(pumpkins)
|
||||||
|
|
||||||
|
|
||||||
|
# Print the first 50 rows of the data set
|
||||||
|
pumpkins %>%
|
||||||
|
slice_head(n =50)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
A quick `glimpse()` immediately shows that there are blanks and a mix of strings (`chr`) and numeric data (`dbl`). The `Date` is of type character and there's also a strange column called `Package` where the data is a mix between `sacks`, `bins` and other values. The data, in fact, is a bit of a mess 😤.
|
||||||
|
|
||||||
|
In fact, it is not very common to be gifted a dataset that is completely ready to use to create a ML model out of the box. But worry not, in this lesson, you will learn how to prepare a raw dataset using standard R libraries 🧑🔧. You will also learn various techniques to visualize the data.📈📊
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
> A refresher: The pipe operator (`%>%`) performs operations in logical sequence by passing an object forward into a function or call expression. You can think of the pipe operator as saying "and then" in your code.
|
||||||
|
|
||||||
|
|
||||||
|
## 2. Check for missing data
|
||||||
|
|
||||||
|
One of the most common issues data scientists need to deal with is incomplete or missing data. R represents missing, or unknown values, with special sentinel value: `NA` (Not Available).
|
||||||
|
|
||||||
|
So how would we know that the data frame contains missing values?
|
||||||
|
|
||||||
|
- One straight forward way would be to use the base R function `anyNA` which returns the logical objects `TRUE` or `FALSE`
|
||||||
|
|
||||||
|
```{r anyNA, message=F, warning=F}
|
||||||
|
pumpkins %>%
|
||||||
|
anyNA()
|
||||||
|
```
|
||||||
|
|
||||||
|
Great, there seems to be some missing data! That's a good place to start.
|
||||||
|
|
||||||
|
- Another way would be to use the function `is.na()` that indicates which individual column elements are missing with a logical `TRUE`.
|
||||||
|
|
||||||
|
```{r is_na, message=F, warning=F}
|
||||||
|
pumpkins %>%
|
||||||
|
is.na() %>%
|
||||||
|
head(n = 7)
|
||||||
|
```
|
||||||
|
|
||||||
|
Okay, got the job done but with a large data frame such as this, it would be inefficient and practically impossible to review all of the rows and columns individually😴.
|
||||||
|
|
||||||
|
- A more intuitive way would be to calculate the sum of the missing values for each column:
|
||||||
|
|
||||||
|
```{r colSum_NA, message=F, warning=F}
|
||||||
|
pumpkins %>%
|
||||||
|
is.na() %>%
|
||||||
|
colSums()
|
||||||
|
```
|
||||||
|
|
||||||
|
Much better! There is missing data, but maybe it won't matter for the task at hand. Let's see what further analysis brings forth.
|
||||||
|
|
||||||
|
> Along with the awesome sets of packages and functions, R has a very good documentation. For instance, use `help(colSums)` or `?colSums` to find out more about the function.
|
||||||
|
|
||||||
|
## 3. Dplyr: A Grammar of Data Manipulation
|
||||||
|
|
||||||
|
{width="569"}
|
||||||
|
|
||||||
|
[`dplyr`](https://dplyr.tidyverse.org/), a package in the Tidyverse, is a grammar of data manipulation that provides a consistent set of verbs that help you solve the most common data manipulation challenges. In this section, we'll explore some of dplyr's verbs!
|
||||||
|
|
||||||
|
#### dplyr::select()
|
||||||
|
|
||||||
|
`select()` is a function in the package `dplyr` which helps you pick columns to keep or exclude.
|
||||||
|
|
||||||
|
To make your data frame easier to work with, drop several of its columns, using `select()`, keeping only the columns you need.
|
||||||
|
|
||||||
|
For instance, in this exercise, our analysis will involve the columns `Package`, `Low Price`, `High Price` and `Date`. Let's select these columns.
|
||||||
|
|
||||||
|
```{r select, message=F, warning=F}
|
||||||
|
# Select desired columns
|
||||||
|
pumpkins <- pumpkins %>%
|
||||||
|
select(Package, `Low Price`, `High Price`, Date)
|
||||||
|
|
||||||
|
|
||||||
|
# Print data set
|
||||||
|
pumpkins %>%
|
||||||
|
slice_head(n = 5)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### dplyr::mutate()
|
||||||
|
|
||||||
|
`mutate()` is a function in the package `dplyr` which helps you create or modify columns, while keeping the existing columns.
|
||||||
|
|
||||||
|
The general structure of mutate is:
|
||||||
|
|
||||||
|
`data %>% mutate(new_column_name = what_it_contains)`
|
||||||
|
|
||||||
|
Let's take `mutate` out for a spin using the `Date` column by doing the following operations:
|
||||||
|
|
||||||
|
1. Convert the dates (currently of type character) to a month format (these are US dates, so the format is `MM/DD/YYYY`).
|
||||||
|
|
||||||
|
2. Extract the month from the dates to a new column.
|
||||||
|
|
||||||
|
In R, the package [lubridate](https://lubridate.tidyverse.org/) makes it easier to work with Date-time data. So, let's use `dplyr::mutate()`, `lubridate::mdy()`, `lubridate::month()` and see how to achieve the above objectives. We can drop the Date column since we won't be needing it again in subsequent operations.
|
||||||
|
|
||||||
|
```{r mut_date, message=F, warning=F}
|
||||||
|
# Load lubridate
|
||||||
|
library(lubridate)
|
||||||
|
|
||||||
|
pumpkins <- pumpkins %>%
|
||||||
|
# Convert the Date column to a date object
|
||||||
|
mutate(Date = mdy(Date)) %>%
|
||||||
|
# Extract month from Date
|
||||||
|
mutate(Month = month(Date)) %>%
|
||||||
|
# Drop Date column
|
||||||
|
select(-Date)
|
||||||
|
|
||||||
|
# View the first few rows
|
||||||
|
pumpkins %>%
|
||||||
|
slice_head(n = 7)
|
||||||
|
```
|
||||||
|
|
||||||
|
Woohoo! 🤩
|
||||||
|
|
||||||
|
Next, let's create a new column `Price`, which represents the average price of a pumpkin. Now, let's take the average of the `Low Price` and `High Price` columns to populate the new Price column.
|
||||||
|
|
||||||
|
```{r price, message=F, warning=F}
|
||||||
|
# Create a new column Price
|
||||||
|
pumpkins <- pumpkins %>%
|
||||||
|
mutate(Price = (`Low Price` + `High Price`)/2)
|
||||||
|
|
||||||
|
# View the first few rows of the data
|
||||||
|
pumpkins %>%
|
||||||
|
slice_head(n = 5)
|
||||||
|
```
|
||||||
|
|
||||||
|
Yeees!💪
|
||||||
|
|
||||||
|
"But wait!", you'll say after skimming through the whole data set with `View(pumpkins)`, "There's something odd here!"🤔
|
||||||
|
|
||||||
|
If you look at the `Package` column, pumpkins are sold in many different configurations. Some are sold in `1 1/9 bushel` measures, and some in `1/2 bushel` measures, some per pumpkin, some per pound, and some in big boxes with varying widths.
|
||||||
|
|
||||||
|
Let's verify this:
|
||||||
|
|
||||||
|
```{r Package, message=F, warning=F}
|
||||||
|
# Verify the distinct observations in Package column
|
||||||
|
pumpkins %>%
|
||||||
|
distinct(Package)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Amazing!👏
|
||||||
|
|
||||||
|
Pumpkins seem to be very hard to weigh consistently, so let's filter them by selecting only pumpkins with the string *bushel* in the `Package` column and put this in a new data frame `new_pumpkins`.
|
||||||
|
|
||||||
|
#### dplyr::filter() and stringr::str_detect()
|
||||||
|
|
||||||
|
[`dplyr::filter()`](https://dplyr.tidyverse.org/reference/filter.html): creates a subset of the data only containing **rows** that satisfy your conditions, in this case, pumpkins with the string *bushel* in the `Package` column.
|
||||||
|
|
||||||
|
[stringr::str_detect()](https://stringr.tidyverse.org/reference/str_detect.html): detects the presence or absence of a pattern in a string.
|
||||||
|
|
||||||
|
The [`stringr`](https://github.com/tidyverse/stringr) package provides simple functions for common string operations.
|
||||||
|
|
||||||
|
```{r filter, message=F, warning=F}
|
||||||
|
# Retain only pumpkins with "bushel"
|
||||||
|
new_pumpkins <- pumpkins %>%
|
||||||
|
filter(str_detect(Package, "bushel"))
|
||||||
|
|
||||||
|
# Get the dimensions of the new data
|
||||||
|
dim(new_pumpkins)
|
||||||
|
|
||||||
|
# View a few rows of the new data
|
||||||
|
new_pumpkins %>%
|
||||||
|
slice_head(n = 5)
|
||||||
|
```
|
||||||
|
|
||||||
|
You can see that we have narrowed down to 415 or so rows of data containing pumpkins by the bushel.🤩
|
||||||
|
|
||||||
|
#### dplyr::case_when()
|
||||||
|
|
||||||
|
**But wait! There's one more thing to do**
|
||||||
|
|
||||||
|
Did you notice that the bushel amount varies per row? You need to normalize the pricing so that you show the pricing per bushel, not per 1 1/9 or 1/2 bushel. Time to do some math to standardize it.
|
||||||
|
|
||||||
|
We'll use the function [`case_when()`](https://dplyr.tidyverse.org/reference/case_when.html) to *mutate* the Price column depending on some conditions. `case_when` allows you to vectorise multiple `if_else()`statements.
|
||||||
|
|
||||||
|
```{r normalize_price, message=F, warning=F}
|
||||||
|
# Convert the price if the Package contains fractional bushel values
|
||||||
|
new_pumpkins <- new_pumpkins %>%
|
||||||
|
mutate(Price = case_when(
|
||||||
|
str_detect(Package, "1 1/9") ~ Price/(1 + 1/9),
|
||||||
|
str_detect(Package, "1/2") ~ Price/(1/2),
|
||||||
|
TRUE ~ Price))
|
||||||
|
|
||||||
|
# View the first few rows of the data
|
||||||
|
new_pumpkins %>%
|
||||||
|
slice_head(n = 30)
|
||||||
|
```
|
||||||
|
|
||||||
|
Now, we can analyze the pricing per unit based on their bushel measurement. All this study of bushels of pumpkins, however, goes to show how very `important` it is to `understand the nature of your data`!
|
||||||
|
|
||||||
|
> ✅ According to [The Spruce Eats](https://www.thespruceeats.com/how-much-is-a-bushel-1389308), a bushel's weight depends on the type of produce, as it's a volume measurement. "A bushel of tomatoes, for example, is supposed to weigh 56 pounds... Leaves and greens take up more space with less weight, so a bushel of spinach is only 20 pounds." It's all pretty complicated! Let's not bother with making a bushel-to-pound conversion, and instead price by the bushel. All this study of bushels of pumpkins, however, goes to show how very important it is to understand the nature of your data!
|
||||||
|
>
|
||||||
|
> ✅ Did you notice that pumpkins sold by the half-bushel are very expensive? Can you figure out why? Hint: little pumpkins are way pricier than big ones, probably because there are so many more of them per bushel, given the unused space taken by one big hollow pie pumpkin.
|
||||||
|
|
||||||
|
Now lastly, for the sheer sake of adventure 💁♀️, let's also move the Month column to the first position i.e `before` column `Package`.
|
||||||
|
|
||||||
|
`dplyr::relocate()` is used to change column positions.
|
||||||
|
|
||||||
|
```{r new_pumpkins, message=F, warning=F}
|
||||||
|
# Create a new data frame new_pumpkins
|
||||||
|
new_pumpkins <- new_pumpkins %>%
|
||||||
|
relocate(Month, .before = Package)
|
||||||
|
|
||||||
|
new_pumpkins %>%
|
||||||
|
slice_head(n = 7)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Good job!👌 You now have a clean, tidy dataset on which you can build your new regression model!
|
||||||
|
|
||||||
|
## 4. Data visualization with ggplot2
|
||||||
|
|
||||||
|
{width="600"}
|
||||||
|
|
||||||
|
There is a *wise* saying that goes like this:
|
||||||
|
|
||||||
|
> "The simple graph has brought more information to the data analyst's mind than any other device." --- John Tukey
|
||||||
|
|
||||||
|
Part of the data scientist's role is to demonstrate the quality and nature of the data they are working with. To do this, they often create interesting visualizations, or plots, graphs, and charts, showing different aspects of data. In this way, they are able to visually show relationships and gaps that are otherwise hard to uncover.
|
||||||
|
|
||||||
|
Visualizations can also help determine the machine learning technique most appropriate for the data. A scatterplot that seems to follow a line, for example, indicates that the data is a good candidate for a linear regression exercise.
|
||||||
|
|
||||||
|
R offers a number of several systems for making graphs, but [`ggplot2`](https://ggplot2.tidyverse.org/index.html) is one of the most elegant and most versatile. `ggplot2` allows you to compose graphs by **combining independent components**.
|
||||||
|
|
||||||
|
Let's start with a simple scatter plot for the Price and Month columns.
|
||||||
|
|
||||||
|
So in this case, we'll start with [`ggplot()`](https://ggplot2.tidyverse.org/reference/ggplot.html), supply a dataset and aesthetic mapping (with [`aes()`](https://ggplot2.tidyverse.org/reference/aes.html)) then add a layers (like [`geom_point()`](https://ggplot2.tidyverse.org/reference/geom_point.html)) for scatter plots.
|
||||||
|
|
||||||
|
```{r scatter_plt, message=F, warning=F}
|
||||||
|
# Set a theme for the plots
|
||||||
|
theme_set(theme_light())
|
||||||
|
|
||||||
|
# Create a scatter plot
|
||||||
|
p <- ggplot(data = new_pumpkins, aes(x = Price, y = Month))
|
||||||
|
p + geom_point()
|
||||||
|
```
|
||||||
|
|
||||||
|
Is this a useful plot 🤷? Does anything about it surprise you?
|
||||||
|
|
||||||
|
It's not particularly useful as all it does is display in your data as a spread of points in a given month.
|
||||||
|
|
||||||
|
### **How do we make it useful?**
|
||||||
|
|
||||||
|
To get charts to display useful data, you usually need to group the data somehow. For instance in our case, finding the average price of pumpkins for each month would provide more insights to the underlying patterns in our data. This leads us to one more **dplyr** flyby:
|
||||||
|
|
||||||
|
#### `dplyr::group_by() %>% summarize()`
|
||||||
|
|
||||||
|
Grouped aggregation in R can be easily computed using
|
||||||
|
|
||||||
|
`dplyr::group_by() %>% summarize()`
|
||||||
|
|
||||||
|
- `dplyr::group_by()` changes the unit of analysis from the complete dataset to individual groups such as per month.
|
||||||
|
|
||||||
|
- `dplyr::summarize()` creates a new data frame with one column for each grouping variable and one column for each of the summary statistics that you have specified.
|
||||||
|
|
||||||
|
For example, we can use the `dplyr::group_by() %>% summarize()` to group the pumpkins into groups based on the **Month** columns and then find the **mean price** for each month.
|
||||||
|
|
||||||
|
```{r grp_sumry, message=F, warning=F}
|
||||||
|
# Find the average price of pumpkins per month
|
||||||
|
new_pumpkins %>%
|
||||||
|
group_by(Month) %>%
|
||||||
|
summarise(mean_price = mean(Price))
|
||||||
|
```
|
||||||
|
|
||||||
|
Succinct!✨
|
||||||
|
|
||||||
|
Categorical features such as months are better represented using a bar plot 📊. The layers responsible for bar charts are `geom_bar()` and `geom_col()`. Consult
|
||||||
|
|
||||||
|
`?geom_bar` to find out more.
|
||||||
|
|
||||||
|
Let's whip up one!
|
||||||
|
|
||||||
|
```{r bar_plt, message=F, warning=F}
|
||||||
|
# Find the average price of pumpkins per month then plot a bar chart
|
||||||
|
new_pumpkins %>%
|
||||||
|
group_by(Month) %>%
|
||||||
|
summarise(mean_price = mean(Price)) %>%
|
||||||
|
ggplot(aes(x = Month, y = mean_price)) +
|
||||||
|
geom_col(fill = "midnightblue", alpha = 0.7) +
|
||||||
|
ylab("Pumpkin Price")
|
||||||
|
```
|
||||||
|
|
||||||
|
🤩🤩This is a more useful data visualization! It seems to indicate that the highest price for pumpkins occurs in September and October. Does that meet your expectation? Why or why not?
|
||||||
|
|
||||||
|
Congratulations on finishing the second lesson 👏! You did prepared your data for model building, then uncovered more insights using visualizations!\
|
@ -0,0 +1,201 @@
|
|||||||
|
# Costruire un modello di regressione usando Scikit-learn: preparare e visualizzare i dati
|
||||||
|
|
||||||
|
> 
|
||||||
|
> Infografica di [Dasani Madipalli](https://twitter.com/dasani_decoded)
|
||||||
|
|
||||||
|
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/11/)
|
||||||
|
|
||||||
|
## Introduzione
|
||||||
|
|
||||||
|
Ora che si hanno a disposizione gli strumenti necessari per iniziare ad affrontare la creazione di modelli di machine learning con Scikit-learn, si è pronti per iniziare a porre domande sui propri dati. Mentre si lavora con i dati e si applicano soluzioni ML, è molto importante capire come porre la domanda giusta per sbloccare correttamente le potenzialità del proprio insieme di dati.
|
||||||
|
|
||||||
|
In questa lezione, si imparerà:
|
||||||
|
|
||||||
|
- Come preparare i dati per la creazione del modello.
|
||||||
|
- Come utilizzare Matplotlib per la visualizzazione dei dati.
|
||||||
|
|
||||||
|
## Fare la domanda giusta ai propri dati
|
||||||
|
|
||||||
|
La domanda a cui si deve rispondere determinerà il tipo di algoritmi ML che verranno utilizzati. La qualità della risposta che si riceverà dipenderà fortemente dalla natura dei propri dati.
|
||||||
|
|
||||||
|
Si dia un'occhiata ai [dati](../../data/US-pumpkins.csv) forniti per questa lezione. Si può aprire questo file .csv in VS Code. Una rapida scrematura mostra immediatamente che ci sono spazi vuoti e un mix di stringhe e dati numerici. C'è anche una strana colonna chiamata "Package" (pacchetto) in cui i dati sono un mix tra "sacks" (sacchi), "bins" (contenitori) e altri valori. I dati, infatti, sono un po' un pasticcio.
|
||||||
|
|
||||||
|
In effetti, non è molto comune ricevere un insieme di dati completamente pronto per creare un modello ML pronto all'uso. In questa lezione si imparerà come preparare un insieme di dati non elaborato utilizzando le librerie standard di Python. Si impareranno anche varie tecniche per visualizzare i dati.
|
||||||
|
|
||||||
|
## Caso di studio: 'il mercato della zucca'
|
||||||
|
|
||||||
|
In questa cartella si troverà un file .csv nella cartella `data` radice chiamato [US-pumpkins.csv](../../data/US-pumpkins.csv) che include 1757 righe di dati sul mercato delle zucche, ordinate in raggruppamenti per città. Si tratta di dati grezzi estratti dai [Report Standard dei Mercati Terminali delle Colture Speciali](https://www.marketnews.usda.gov/mnp/fv-report-config-step1?type=termPrice) distribuiti dal Dipartimento dell'Agricoltura degli Stati Uniti.
|
||||||
|
|
||||||
|
### Preparazione dati
|
||||||
|
|
||||||
|
Questi dati sono di pubblico dominio. Possono essere scaricati in molti file separati, per città, dal sito web dell'USDA. Per evitare troppi file separati, sono stati concatenati tutti i dati della città in un unico foglio di calcolo, quindi un po' i dati sono già stati _preparati_ . Successivamente, si darà un'occhiata più da vicino ai dati.
|
||||||
|
|
||||||
|
### I dati della zucca - prime conclusioni
|
||||||
|
|
||||||
|
Cosa si nota riguardo a questi dati? Si è già visto che c'è un mix di stringhe, numeri, spazi e valori strani a cui occorre dare un senso.
|
||||||
|
|
||||||
|
Che domanda si puà fare a questi dati, utilizzando una tecnica di Regressione? Che dire di "Prevedere il prezzo di una zucca in vendita durante un dato mese". Esaminando nuovamente i dati, ci sono alcune modifiche da apportare per creare la struttura dati necessaria per l'attività.
|
||||||
|
|
||||||
|
## Esercizio: analizzare i dati della zucca
|
||||||
|
|
||||||
|
Si usa [Pandas](https://pandas.pydata.org/), (il nome sta per `Python Data Analysis`) uno strumento molto utile per dare forma ai dati, per analizzare e preparare questi dati sulla zucca.
|
||||||
|
|
||||||
|
### Innanzitutto, controllare le date mancanti
|
||||||
|
|
||||||
|
Prima si dovranno eseguire i passaggi per verificare le date mancanti:
|
||||||
|
|
||||||
|
1. Convertire le date in un formato mensile (queste sono date statunitensi, quindi il formato è `MM/GG/AAAA`).
|
||||||
|
2. Estrarre il mese in una nuova colonna.
|
||||||
|
|
||||||
|
Aprire il file _notebook.ipynb_ in Visual Studio Code e importare il foglio di calcolo in un nuovo dataframe Pandas.
|
||||||
|
|
||||||
|
1. Usare la funzione `head()` per visualizzare le prime cinque righe.
|
||||||
|
|
||||||
|
```python
|
||||||
|
import pandas as pd
|
||||||
|
pumpkins = pd.read_csv('../data/US-pumpkins.csv')
|
||||||
|
pumpkins.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ Quale funzione si userebbe per visualizzare le ultime cinque righe?
|
||||||
|
|
||||||
|
1. Controllare se mancano dati nel dataframe corrente:
|
||||||
|
|
||||||
|
```python
|
||||||
|
pumpkins.isnull().sum()
|
||||||
|
```
|
||||||
|
|
||||||
|
Ci sono dati mancanti, ma forse non avrà importanza per l'attività da svolgere.
|
||||||
|
|
||||||
|
1. Per rendere più facile lavorare con il dataframe, si scartano molte delle sue colonne, usando `drop()`, mantenendo solo le colonne di cui si ha bisogno:
|
||||||
|
|
||||||
|
```python
|
||||||
|
new_columns = ['Package', 'Month', 'Low Price', 'High Price', 'Date']
|
||||||
|
pumpkins = pumpkins.drop([c for c in pumpkins.columns if c not in new_columns], axis=1)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Secondo, determinare il prezzo medio della zucca
|
||||||
|
|
||||||
|
Si pensi a come determinare il prezzo medio di una zucca in un dato mese. Quali colonne si sceglierebbero per questa attività? Suggerimento: serviranno 3 colonne.
|
||||||
|
|
||||||
|
Soluzione: prendere la media delle colonne `Low Price` e `High Price` per popolare la nuova colonna Price e convertire la colonna Date per mostrare solo il mese. Fortunatamente, secondo il controllo di cui sopra, non mancano dati per date o prezzi.
|
||||||
|
|
||||||
|
1. Per calcolare la media, aggiungere il seguente codice:
|
||||||
|
|
||||||
|
```python
|
||||||
|
price = (pumpkins['Low Price'] + pumpkins['High Price']) / 2
|
||||||
|
|
||||||
|
month = pd.DatetimeIndex(pumpkins['Date']).month
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ Si possono di stampare tutti i dati che si desidera controllare utilizzando `print(month)`.
|
||||||
|
|
||||||
|
2. Ora copiare i dati convertiti in un nuovo dataframe Pandas:
|
||||||
|
|
||||||
|
```python
|
||||||
|
new_pumpkins = pd.DataFrame({'Month': month, 'Package': pumpkins['Package'], 'Low Price': pumpkins['Low Price'],'High Price': pumpkins['High Price'], 'Price': price})
|
||||||
|
```
|
||||||
|
|
||||||
|
La stampa del dataframe mostrerà un insieme di dati pulito e ordinato su cui si può costruire il nuovo modello di regressione.
|
||||||
|
|
||||||
|
### Ma non è finita qui! C'è qualcosa di strano qui.
|
||||||
|
|
||||||
|
Osservando la colonna `Package`, le zucche sono vendute in molte configurazioni diverse. Alcune sono venduti in misure '1 1/9 bushel' (bushel = staio) e alcuni in misure '1/2 bushel', alcuni per zucca, alcuni per libbra e alcuni in grandi scatole con larghezze variabili.
|
||||||
|
|
||||||
|
> Le zucche sembrano molto difficili da pesare in modo coerente
|
||||||
|
|
||||||
|
Scavando nei dati originali, è interessante notare che qualsiasi cosa con `Unit of Sale` (Unità di vendita) uguale a 'EACH' o 'PER BIN' ha anche il tipo di `Package` per 'inch' (pollice), per 'bin' (contenitore) o 'each' (entrambi). Le zucche sembrano essere molto difficili da pesare in modo coerente, quindi si filtrano selezionando solo zucche con la stringa "bushel" nella colonna `Package`.
|
||||||
|
|
||||||
|
1. Aggiungere un filtro nella parte superiore del file, sotto l'importazione .csv iniziale:
|
||||||
|
|
||||||
|
```python
|
||||||
|
pumpkins = pumpkins[pumpkins['Package'].str.contains('bushel', case=True, regex=True)]
|
||||||
|
```
|
||||||
|
|
||||||
|
Se si stampano i dati ora, si può vedere che si stanno ricevendo solo le circa 415 righe di dati contenenti zucche per bushel.
|
||||||
|
|
||||||
|
### Ma non è finita qui! C'è un'altra cosa da fare.
|
||||||
|
|
||||||
|
Si è notato che la quantità di bushel varia per riga? Si deve normalizzare il prezzo in modo da mostrare il prezzo per bushel, quindi si facciano un po' di calcoli per standardizzarlo.
|
||||||
|
|
||||||
|
1. Aggiungere queste righe dopo il blocco che crea il dataframe new_pumpkins:
|
||||||
|
|
||||||
|
```python
|
||||||
|
new_pumpkins.loc[new_pumpkins['Package'].str.contains('1 1/9'), 'Price'] = price/(1 + 1/9)
|
||||||
|
|
||||||
|
new_pumpkins.loc[new_pumpkins['Package'].str.contains('1/2'), 'Price'] = price/(1/2)
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ Secondo [The Spruce Eats](https://www.thespruceeats.com/how-much-is-a-bushel-1389308), il peso di un bushel dipende dal tipo di prodotto, poiché è una misura di volume. "Un bushel di pomodori, per esempio, dovrebbe pesare 56 libbre... Foglie e verdure occupano più spazio con meno peso, quindi un bushel di spinaci è solo 20 libbre". È tutto piuttosto complicato! Non occorre preoccuparsi di fare una conversione da bushel a libbra, e invece si valuta a bushel. Tutto questo studio sui bushel di zucche, però, dimostra quanto sia importante capire la natura dei propri dati!
|
||||||
|
|
||||||
|
Ora si può analizzare il prezzo per unità in base alla misurazione del bushel. Se si stampano i dati ancora una volta, si può vedere come sono standardizzati.
|
||||||
|
|
||||||
|
✅ Si è notato che le zucche vendute a metà bushel sono molto costose? Si riesce a capire perché? Suggerimento: le zucche piccole sono molto più costose di quelle grandi, probabilmente perché ce ne sono molte di più per bushel, dato lo spazio inutilizzato occupato da una grande zucca cava.
|
||||||
|
|
||||||
|
## Strategie di Visualizzazione
|
||||||
|
|
||||||
|
Parte del ruolo del data scientist è dimostrare la qualità e la natura dei dati con cui sta lavorando. Per fare ciò, si creano spesso visualizzazioni interessanti o tracciati, grafici e diagrammi, che mostrano diversi aspetti dei dati. In questo modo, sono in grado di mostrare visivamente relazioni e lacune altrimenti difficili da scoprire.
|
||||||
|
|
||||||
|
Le visualizzazioni possono anche aiutare a determinare la tecnica di machine learning più appropriata per i dati. Un grafico a dispersione che sembra seguire una linea, ad esempio, indica che i dati sono un buon candidato per un esercizio di regressione lineare.
|
||||||
|
|
||||||
|
Una libreria di visualizzazione dei dati che funziona bene nei notebook Jupyter è [Matplotlib](https://matplotlib.org/) (che si è visto anche nella lezione precedente).
|
||||||
|
|
||||||
|
> Per fare più esperienza con la visualizzazione dei dati si seguano [questi tutorial](https://docs.microsoft.com/learn/modules/explore-analyze-data-with-python?WT.mc_id=academic-15963-cxa).
|
||||||
|
|
||||||
|
## Esercizio - sperimentare con Matplotlib
|
||||||
|
|
||||||
|
Provare a creare alcuni grafici di base per visualizzare il nuovo dataframe appena creato. Cosa mostrerebbe un grafico a linee di base?
|
||||||
|
|
||||||
|
1. Importare Matplotlib nella parte superiore del file, sotto l'importazione di Pandas:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Rieseguire l'intero notebook per aggiornare.
|
||||||
|
1. Nella parte inferiore del notebook, aggiungere una cella per tracciare i dati come una casella:
|
||||||
|
|
||||||
|
```python
|
||||||
|
price = new_pumpkins.Price
|
||||||
|
month = new_pumpkins.Month
|
||||||
|
plt.scatter(price, month)
|
||||||
|
plt.show()
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
È un tracciato utile? C'è qualcosa che sorprende?
|
||||||
|
|
||||||
|
Non è particolarmente utile in quanto tutto ciò che fa è visualizzare nei propri dati come una diffusione di punti in un dato mese.
|
||||||
|
|
||||||
|
### Renderlo utile
|
||||||
|
|
||||||
|
Per fare in modo che i grafici mostrino dati utili, di solito è necessario raggruppare i dati in qualche modo. Si prova a creare un grafico che mostra la distribuzione dei dati dove l'asse x mostra i mesi.
|
||||||
|
|
||||||
|
1. Aggiungere una cella per creare un grafico a barre raggruppato:
|
||||||
|
|
||||||
|
```python
|
||||||
|
new_pumpkins.groupby(['Month'])['Price'].mean().plot(kind='bar')
|
||||||
|
plt.ylabel("Pumpkin Price")
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Questa è una visualizzazione dei dati più utile! Sembra indicare che il prezzo più alto per le zucche si verifica a settembre e ottobre. Questo soddisfa le proprie aspettative? Perché o perché no?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Sfida
|
||||||
|
|
||||||
|
Esplorare i diversi tipi di visualizzazione offerti da Matplotlib. Quali tipi sono più appropriati per i problemi di regressione?
|
||||||
|
|
||||||
|
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/12/)
|
||||||
|
|
||||||
|
## Revisione e Auto Apprendimento
|
||||||
|
|
||||||
|
Dare un'occhiata ai molti modi per visualizzare i dati. Fare un elenco delle varie librerie disponibili e annotare quali sono le migliori per determinati tipi di attività, ad esempio visualizzazioni 2D rispetto a visualizzazioni 3D. Cosa si è scoperto?
|
||||||
|
|
||||||
|
## Compito
|
||||||
|
|
||||||
|
[Esplorazione della visualizzazione](assignment.it.md)
|
@ -0,0 +1,9 @@
|
|||||||
|
# Esplorazione delle visualizzazioni
|
||||||
|
|
||||||
|
Sono disponibili diverse librerie per la visualizzazione dei dati. Creare alcune visualizzazioni utilizzando i dati della zucca in questa lezione con matplotlib e seaborn in un notebook di esempio. Con quali librerie è più facile lavorare?
|
||||||
|
|
||||||
|
## Rubrica
|
||||||
|
|
||||||
|
| Criteri | Ottimo | Adeguato | Necessita miglioramento |
|
||||||
|
| -------- | --------- | -------- | ----------------- |
|
||||||
|
| | Viene inviato un notebook con due esplorazioni/visualizzazioni | Viene inviato un notebook con una esplorazione/visualizzazione | Non è stato inviato un notebook |
|
@ -0,0 +1,9 @@
|
|||||||
|
# 探索数据可视化
|
||||||
|
|
||||||
|
有好几个库都可以进行数据可视化。用 matplotlib 和 seaborn 对本课中涉及的 Pumpkin 数据集创建一些数据可视化的图标。并思考哪个库更容易使用?
|
||||||
|
|
||||||
|
## 评判标准
|
||||||
|
|
||||||
|
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
|
||||||
|
| -------- | --------- | -------- | ----------------- |
|
||||||
|
| | 提交了含有两种探索可视化方法的notebook工程文件 | 提交了只包含有一种探索可视化方法的notebook工程文件 | 没提交 notebook 工程文件 |
|
After Width: | Height: | Size: 873 KiB |
After Width: | Height: | Size: 6.3 MiB |
@ -0,0 +1,679 @@
|
|||||||
|
---
|
||||||
|
title: 'Build a regression model: linear and polynomial regression models'
|
||||||
|
output:
|
||||||
|
html_document:
|
||||||
|
df_print: paged
|
||||||
|
theme: flatly
|
||||||
|
highlight: breezedark
|
||||||
|
toc: yes
|
||||||
|
toc_float: yes
|
||||||
|
code_download: yes
|
||||||
|
---
|
||||||
|
|
||||||
|
## Linear and Polynomial Regression for Pumpkin Pricing - Lesson 3
|
||||||
|
|
||||||
|
{width="800"}
|
||||||
|
|
||||||
|
#### Introduction
|
||||||
|
|
||||||
|
So far you have explored what regression is with sample data gathered from the pumpkin pricing dataset that we will use throughout this lesson. You have also visualized it using `ggplot2`.💪
|
||||||
|
|
||||||
|
Now you are ready to dive deeper into regression for ML. In this lesson, you will learn more about two types of regression: *basic linear regression* and *polynomial regression*, along with some of the math underlying these techniques.
|
||||||
|
|
||||||
|
> Throughout this curriculum, we assume minimal knowledge of math, and seek to make it accessible for students coming from other fields, so watch for notes, 🧮 callouts, diagrams, and other learning tools to aid in comprehension.
|
||||||
|
|
||||||
|
#### Preparation
|
||||||
|
|
||||||
|
As a reminder, you are loading this data so as to ask questions of it.
|
||||||
|
|
||||||
|
- When is the best time to buy pumpkins?
|
||||||
|
|
||||||
|
- What price can I expect of a case of miniature pumpkins?
|
||||||
|
|
||||||
|
- Should I buy them in half-bushel baskets or by the 1 1/9 bushel box? Let's keep digging into this data.
|
||||||
|
|
||||||
|
In the previous lesson, you created a `tibble` (a modern reimagining of the data frame) and populated it with part of the original dataset, standardizing the pricing by the bushel. By doing that, however, you were only able to gather about 400 data points and only for the fall months. Maybe we can get a little more detail about the nature of the data by cleaning it more? We'll see... 🕵️♀️
|
||||||
|
|
||||||
|
For this task, we'll require the following packages:
|
||||||
|
|
||||||
|
- `tidyverse`: The [tidyverse](https://www.tidyverse.org/) is a [collection of R packages](https://www.tidyverse.org/packages) designed to makes data science faster, easier and more fun!
|
||||||
|
|
||||||
|
- `tidymodels`: The [tidymodels](https://www.tidymodels.org/) framework is a [collection of packages](https://www.tidymodels.org/packages/) for modeling and machine learning.
|
||||||
|
|
||||||
|
- `janitor`: The [janitor package](https://github.com/sfirke/janitor) provides simple little tools for examining and cleaning dirty data.
|
||||||
|
|
||||||
|
- `corrplot`: The [corrplot package](https://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html) provides a visual exploratory tool on correlation matrix that supports automatic variable reordering to help detect hidden patterns among variables.
|
||||||
|
|
||||||
|
You can have them installed as:
|
||||||
|
|
||||||
|
`install.packages(c("tidyverse", "tidymodels", "janitor", "corrplot"))`
|
||||||
|
|
||||||
|
The script below checks whether you have the packages required to complete this module and installs them for you in case they are missing.
|
||||||
|
|
||||||
|
```{r, message=F, warning=F}
|
||||||
|
suppressWarnings(if (!require("pacman")) install.packages("pacman"))
|
||||||
|
|
||||||
|
pacman::p_load(tidyverse, tidymodels, janitor, corrplot)
|
||||||
|
```
|
||||||
|
|
||||||
|
We'll later load these awesome packages and make them available in our current R session. (This is for mere illustration, `pacman::p_load()` already did that for you)
|
||||||
|
|
||||||
|
## 1. A linear regression line
|
||||||
|
|
||||||
|
As you learned in Lesson 1, the goal of a linear regression exercise is to be able to plot a *line* *of* *best fit* to:
|
||||||
|
|
||||||
|
- **Show variable relationships**. Show the relationship between variables
|
||||||
|
|
||||||
|
- **Make predictions**. Make accurate predictions on where a new data point would fall in relationship to that line.
|
||||||
|
|
||||||
|
To draw this type of line, we use a statistical technique called **Least-Squares Regression**. The term `least-squares` means that all the data points surrounding the regression line are squared and then added up. Ideally, that final sum is as small as possible, because we want a low number of errors, or `least-squares`. As such, the line of best fit is the line that gives us the lowest value for the sum of the squared errors - hence the name *least squares regression*.
|
||||||
|
|
||||||
|
We do so since we want to model a line that has the least cumulative distance from all of our data points. We also square the terms before adding them since we are concerned with its magnitude rather than its direction.
|
||||||
|
|
||||||
|
> **🧮 Show me the math**
|
||||||
|
>
|
||||||
|
> This line, called the *line of best fit* can be expressed by [an equation](https://en.wikipedia.org/wiki/Simple_linear_regression):
|
||||||
|
>
|
||||||
|
> Y = a + bX
|
||||||
|
>
|
||||||
|
> `X` is the '`explanatory variable` or `predictor`'. `Y` is the '`dependent variable` or `outcome`'. The slope of the line is `b` and `a` is the y-intercept, which refers to the value of `Y` when `X = 0`.
|
||||||
|
>
|
||||||
|
> {width="400"}
|
||||||
|
>
|
||||||
|
> First, calculate the slope `b`.
|
||||||
|
>
|
||||||
|
> In other words, and referring to our pumpkin data's original question: "predict the price of a pumpkin per bushel by month", `X` would refer to the price and `Y` would refer to the month of sale.
|
||||||
|
>
|
||||||
|
> 
|
||||||
|
>
|
||||||
|
> Calculate the value of Y. If you're paying around \$4, it must be April!
|
||||||
|
>
|
||||||
|
> The math that calculates the line must demonstrate the slope of the line, which is also dependent on the intercept, or where `Y` is situated when `X = 0`.
|
||||||
|
>
|
||||||
|
> You can observe the method of calculation for these values on the [Math is Fun](https://www.mathsisfun.com/data/least-squares-regression.html) web site. Also visit [this Least-squares calculator](https://www.mathsisfun.com/data/least-squares-calculator.html) to watch how the numbers' values impact the line.
|
||||||
|
|
||||||
|
Not so scary, right? 🤓
|
||||||
|
|
||||||
|
#### Correlation
|
||||||
|
|
||||||
|
One more term to understand is the **Correlation Coefficient** between given X and Y variables. Using a scatterplot, you can quickly visualize this coefficient. A plot with datapoints scattered in a neat line have high correlation, but a plot with datapoints scattered everywhere between X and Y have a low correlation.
|
||||||
|
|
||||||
|
A good linear regression model will be one that has a high (nearer to 1 than 0) Correlation Coefficient using the Least-Squares Regression method with a line of regression.
|
||||||
|
|
||||||
|
## **2. A dance with data: creating a data frame that will be used for modelling**
|
||||||
|
|
||||||
|
{width="700"}
|
||||||
|
|
||||||
|
Load up required libraries and dataset. Convert the data to a data frame containing a subset of the data:
|
||||||
|
|
||||||
|
- Only get pumpkins priced by the bushel
|
||||||
|
|
||||||
|
- Convert the date to a month
|
||||||
|
|
||||||
|
- Calculate the price to be an average of high and low prices
|
||||||
|
|
||||||
|
- Convert the price to reflect the pricing by bushel quantity
|
||||||
|
|
||||||
|
> We covered these steps in the [previous lesson](https://github.com/microsoft/ML-For-Beginners/blob/main/2-Regression/2-Data/solution/lesson_2-R.ipynb).
|
||||||
|
|
||||||
|
```{r load_tidy_verse_models, message=F, warning=F}
|
||||||
|
# Load the core Tidyverse packages
|
||||||
|
library(tidyverse)
|
||||||
|
library(lubridate)
|
||||||
|
|
||||||
|
# Import the pumpkins data
|
||||||
|
pumpkins <- read_csv(file = "https://raw.githubusercontent.com/microsoft/ML-For-Beginners/main/2-Regression/data/US-pumpkins.csv")
|
||||||
|
|
||||||
|
|
||||||
|
# Get a glimpse and dimensions of the data
|
||||||
|
glimpse(pumpkins)
|
||||||
|
|
||||||
|
|
||||||
|
# Print the first 50 rows of the data set
|
||||||
|
pumpkins %>%
|
||||||
|
slice_head(n = 5)
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
In the spirit of sheer adventure, let's explore the [`janitor package`](github.com/sfirke/janitor) that provides simple functions for examining and cleaning dirty data. For instance, let's take a look at the column names for our data:
|
||||||
|
|
||||||
|
```{r col_names}
|
||||||
|
# Return column names
|
||||||
|
pumpkins %>%
|
||||||
|
names()
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
🤔 We can do better. Let's make these column names `friendR` by converting them to the [snake_case](https://en.wikipedia.org/wiki/Snake_case) convention using `janitor::clean_names`. To find out more about this function: `?clean_names`
|
||||||
|
|
||||||
|
```{r friendR}
|
||||||
|
# Clean names to the snake_case convention
|
||||||
|
pumpkins <- pumpkins %>%
|
||||||
|
clean_names(case = "snake")
|
||||||
|
|
||||||
|
# Return column names
|
||||||
|
pumpkins %>%
|
||||||
|
names()
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Much tidyR 🧹! Now, a dance with the data using `dplyr` as in the previous lesson! 💃
|
||||||
|
|
||||||
|
```{r prep_data, message=F, warning=F}
|
||||||
|
# Select desired columns
|
||||||
|
pumpkins <- pumpkins %>%
|
||||||
|
select(variety, city_name, package, low_price, high_price, date)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Extract the month from the dates to a new column
|
||||||
|
pumpkins <- pumpkins %>%
|
||||||
|
mutate(date = mdy(date),
|
||||||
|
month = month(date)) %>%
|
||||||
|
select(-date)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Create a new column for average Price
|
||||||
|
pumpkins <- pumpkins %>%
|
||||||
|
mutate(price = (low_price + high_price)/2)
|
||||||
|
|
||||||
|
|
||||||
|
# Retain only pumpkins with the string "bushel"
|
||||||
|
new_pumpkins <- pumpkins %>%
|
||||||
|
filter(str_detect(string = package, pattern = "bushel"))
|
||||||
|
|
||||||
|
|
||||||
|
# Normalize the pricing so that you show the pricing per bushel, not per 1 1/9 or 1/2 bushel
|
||||||
|
new_pumpkins <- new_pumpkins %>%
|
||||||
|
mutate(price = case_when(
|
||||||
|
str_detect(package, "1 1/9") ~ price/(1.1),
|
||||||
|
str_detect(package, "1/2") ~ price*2,
|
||||||
|
TRUE ~ price))
|
||||||
|
|
||||||
|
# Relocate column positions
|
||||||
|
new_pumpkins <- new_pumpkins %>%
|
||||||
|
relocate(month, .before = variety)
|
||||||
|
|
||||||
|
|
||||||
|
# Display the first 5 rows
|
||||||
|
new_pumpkins %>%
|
||||||
|
slice_head(n = 5)
|
||||||
|
```
|
||||||
|
|
||||||
|
Good job!👌 You now have a clean, tidy data set on which you can build your new regression model!
|
||||||
|
|
||||||
|
Mind a scatter plot?
|
||||||
|
|
||||||
|
```{r scatter_price_month}
|
||||||
|
# Set theme
|
||||||
|
theme_set(theme_light())
|
||||||
|
|
||||||
|
# Make a scatter plot of month and price
|
||||||
|
new_pumpkins %>%
|
||||||
|
ggplot(mapping = aes(x = month, y = price)) +
|
||||||
|
geom_point(size = 1.6)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
A scatter plot reminds us that we only have month data from August through December. We probably need more data to be able to draw conclusions in a linear fashion.
|
||||||
|
|
||||||
|
Let's take a look at our modelling data again:
|
||||||
|
|
||||||
|
```{r modelling data}
|
||||||
|
# Display first 5 rows
|
||||||
|
new_pumpkins %>%
|
||||||
|
slice_head(n = 5)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
What if we wanted to predict the `price` of a pumpkin based on the `city` or `package` columns which are of type character? Or even more simply, how could we find the correlation (which requires both of its inputs to be numeric) between, say, `package` and `price`? 🤷🤷
|
||||||
|
|
||||||
|
Machine learning models work best with numeric features rather than text values, so you generally need to convert categorical features into numeric representations.
|
||||||
|
|
||||||
|
This means that we have to find a way to reformat our predictors to make them easier for a model to use effectively, a process known as `feature engineering`.
|
||||||
|
|
||||||
|
## 3. Preprocessing data for modelling with recipes 👩🍳👨🍳
|
||||||
|
|
||||||
|
Activities that reformat predictor values to make them easier for a model to use effectively has been termed `feature engineering`.
|
||||||
|
|
||||||
|
Different models have different preprocessing requirements. For instance, least squares requires `encoding categorical variables` such as month, variety and city_name. This simply involves `translating` a column with `categorical values` into one or more `numeric columns` that take the place of the original.
|
||||||
|
|
||||||
|
For example, suppose your data includes the following categorical feature:
|
||||||
|
|
||||||
|
| city |
|
||||||
|
|:-------:|
|
||||||
|
| Denver |
|
||||||
|
| Nairobi |
|
||||||
|
| Tokyo |
|
||||||
|
|
||||||
|
You can apply *ordinal encoding* to substitute a unique integer value for each category, like this:
|
||||||
|
|
||||||
|
| city |
|
||||||
|
|:----:|
|
||||||
|
| 0 |
|
||||||
|
| 1 |
|
||||||
|
| 2 |
|
||||||
|
|
||||||
|
And that's what we'll do to our data!
|
||||||
|
|
||||||
|
In this section, we'll explore another amazing Tidymodels package: [recipes](https://tidymodels.github.io/recipes/) - which is designed to help you preprocess your data **before** training your model. At its core, a recipe is an object that defines what steps should be applied to a data set in order to get it ready for modelling.
|
||||||
|
|
||||||
|
Now, let's create a recipe that prepares our data for modelling by substituting a unique integer for all the observations in the predictor columns:
|
||||||
|
|
||||||
|
```{r pumpkins_recipe}
|
||||||
|
# Specify a recipe
|
||||||
|
pumpkins_recipe <- recipe(price ~ ., data = new_pumpkins) %>%
|
||||||
|
step_integer(all_predictors(), zero_based = TRUE)
|
||||||
|
|
||||||
|
|
||||||
|
# Print out the recipe
|
||||||
|
pumpkins_recipe
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Awesome! 👏 We just created our first recipe that specifies an outcome (price) and its corresponding predictors and that all the predictor columns should be encoded into a set of integers 🙌! Let's quickly break it down:
|
||||||
|
|
||||||
|
- The call to `recipe()` with a formula tells the recipe the *roles* of the variables using `new_pumpkins` data as the reference. For instance the `price` column has been assigned an `outcome` role while the rest of the columns have been assigned a `predictor` role.
|
||||||
|
|
||||||
|
- `step_integer(all_predictors(), zero_based = TRUE)` specifies that all the predictors should be converted into a set of integers with the numbering starting at 0.
|
||||||
|
|
||||||
|
We are sure you may be having thoughts such as: "This is so cool!! But what if I needed to confirm that the recipes are doing exactly what I expect them to do? 🤔"
|
||||||
|
|
||||||
|
That's an awesome thought! You see, once your recipe is defined, you can estimate the parameters required to actually preprocess the data, and then extract the processed data. You don't typically need to do this when you use Tidymodels (we'll see the normal convention in just a minute-\> `workflows`) but it can come in handy when you want to do some kind of sanity check for confirming that recipes are doing what you expect.
|
||||||
|
|
||||||
|
For that, you'll need two more verbs: `prep()` and `bake()` and as always, our little R friends by [`Allison Horst`](https://github.com/allisonhorst/stats-illustrations) help you in understanding this better!
|
||||||
|
|
||||||
|
{width="550"}
|
||||||
|
|
||||||
|
[`prep()`](https://recipes.tidymodels.org/reference/prep.html): estimates the required parameters from a training set that can be later applied to other data sets. For instance, for a given predictor column, what observation will be assigned integer 0 or 1 or 2 etc
|
||||||
|
|
||||||
|
[`bake()`](https://recipes.tidymodels.org/reference/bake.html): takes a prepped recipe and applies the operations to any data set.
|
||||||
|
|
||||||
|
That said, lets prep and bake our recipes to really confirm that under the hood, the predictor columns will be first encoded before a model is fit.
|
||||||
|
|
||||||
|
```{r prep_bake}
|
||||||
|
# Prep the recipe
|
||||||
|
pumpkins_prep <- prep(pumpkins_recipe)
|
||||||
|
|
||||||
|
# Bake the recipe to extract a preprocessed new_pumpkins data
|
||||||
|
baked_pumpkins <- bake(pumpkins_prep, new_data = NULL)
|
||||||
|
|
||||||
|
# Print out the baked data set
|
||||||
|
baked_pumpkins %>%
|
||||||
|
slice_head(n = 10)
|
||||||
|
```
|
||||||
|
|
||||||
|
Woo-hoo!🥳 The processed data `baked_pumpkins` has all it's predictors encoded confirming that indeed the preprocessing steps defined as our recipe will work as expected. This makes it harder for you to read but much more intelligible for Tidymodels! Take some time to find out what observation has been mapped to a corresponding integer.
|
||||||
|
|
||||||
|
It is also worth mentioning that `baked_pumpkins` is a data frame that we can perform computations on.
|
||||||
|
|
||||||
|
For instance, let's try to find a good correlation between two points of your data to potentially build a good predictive model. We'll use the function `cor()` to do this. Type `?cor()` to find out more about the function.
|
||||||
|
|
||||||
|
```{r corr}
|
||||||
|
# Find the correlation between the city_name and the price
|
||||||
|
cor(baked_pumpkins$city_name, baked_pumpkins$price)
|
||||||
|
|
||||||
|
# Find the correlation between the package and the price
|
||||||
|
cor(baked_pumpkins$package, baked_pumpkins$price)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
As it turns out, there's only weak correlation between the City and Price. However there's a bit better correlation between the Package and its Price. That makes sense, right? Normally, the bigger the produce box, the higher the price.
|
||||||
|
|
||||||
|
While we are at it, let's also try and visualize a correlation matrix of all the columns using the `corrplot` package.
|
||||||
|
|
||||||
|
```{r corrplot}
|
||||||
|
# Load the corrplot package
|
||||||
|
library(corrplot)
|
||||||
|
|
||||||
|
# Obtain correlation matrix
|
||||||
|
corr_mat <- cor(baked_pumpkins %>%
|
||||||
|
# Drop columns that are not really informative
|
||||||
|
select(-c(low_price, high_price)))
|
||||||
|
|
||||||
|
# Make a correlation plot between the variables
|
||||||
|
corrplot(corr_mat, method = "shade", shade.col = NA, tl.col = "black", tl.srt = 45, addCoef.col = "black", cl.pos = "n", order = "original")
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
🤩🤩 Much better.
|
||||||
|
|
||||||
|
A good question to now ask of this data will be: '`What price can I expect of a given pumpkin package?`' Let's get right into it!
|
||||||
|
|
||||||
|
> Note: When you **`bake()`** the prepped recipe **`pumpkins_prep`** with **`new_data = NULL`**, you extract the processed (i.e. encoded) training data. If you had another data set for example a test set and would want to see how a recipe would pre-process it, you would simply bake **`pumpkins_prep`** with **`new_data = test_set`**
|
||||||
|
|
||||||
|
## 4. Build a linear regression model
|
||||||
|
|
||||||
|
{width="800"}
|
||||||
|
|
||||||
|
Now that we have build a recipe, and actually confirmed that the data will be pre-processed appropriately, let's now build a regression model to answer the question: `What price can I expect of a given pumpkin package?`
|
||||||
|
|
||||||
|
#### Train a linear regression model using the training set
|
||||||
|
|
||||||
|
As you may have already figured out, the column *price* is the `outcome` variable while the *package* column is the `predictor` variable.
|
||||||
|
|
||||||
|
To do this, we'll first split the data such that 80% goes into training and 20% into test set, then define a recipe that will encode the predictor column into a set of integers, then build a model specification. We won't prep and bake our recipe since we already know it will preprocess the data as expected.
|
||||||
|
|
||||||
|
```{r lm_rec_spec}
|
||||||
|
set.seed(2056)
|
||||||
|
# Split the data into training and test sets
|
||||||
|
pumpkins_split <- new_pumpkins %>%
|
||||||
|
initial_split(prop = 0.8)
|
||||||
|
|
||||||
|
|
||||||
|
# Extract training and test data
|
||||||
|
pumpkins_train <- training(pumpkins_split)
|
||||||
|
pumpkins_test <- testing(pumpkins_split)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Create a recipe for preprocessing the data
|
||||||
|
lm_pumpkins_recipe <- recipe(price ~ package, data = pumpkins_train) %>%
|
||||||
|
step_integer(all_predictors(), zero_based = TRUE)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Create a linear model specification
|
||||||
|
lm_spec <- linear_reg() %>%
|
||||||
|
set_engine("lm") %>%
|
||||||
|
set_mode("regression")
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Good job! Now that we have a recipe and a model specification, we need to find a way of bundling them together into an object that will first preprocess the data (prep+bake behind the scenes), fit the model on the preprocessed data and also allow for potential post-processing activities. How's that for your peace of mind!🤩
|
||||||
|
|
||||||
|
In Tidymodels, this convenient object is called a [`workflow`](https://workflows.tidymodels.org/) and conveniently holds your modeling components! This is what we'd call *pipelines* in *Python*.
|
||||||
|
|
||||||
|
So let's bundle everything up into a workflow!📦
|
||||||
|
|
||||||
|
```{r lm_workflow}
|
||||||
|
# Hold modelling components in a workflow
|
||||||
|
lm_wf <- workflow() %>%
|
||||||
|
add_recipe(lm_pumpkins_recipe) %>%
|
||||||
|
add_model(lm_spec)
|
||||||
|
|
||||||
|
# Print out the workflow
|
||||||
|
lm_wf
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
👌 Into the bargain, a workflow can be fit/trained in much the same way a model can.
|
||||||
|
|
||||||
|
```{r lm_wf_fit}
|
||||||
|
# Train the model
|
||||||
|
lm_wf_fit <- lm_wf %>%
|
||||||
|
fit(data = pumpkins_train)
|
||||||
|
|
||||||
|
# Print the model coefficients learned
|
||||||
|
lm_wf_fit
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
From the model output, we can see the coefficients learned during training. They represent the coefficients of the line of best fit that gives us the lowest overall error between the actual and predicted variable.
|
||||||
|
|
||||||
|
#### Evaluate model performance using the test set
|
||||||
|
|
||||||
|
It's time to see how the model performed 📏! How do we do this?
|
||||||
|
|
||||||
|
Now that we've trained the model, we can use it to make predictions for the test_set using `parsnip::predict()`. Then we can compare these predictions to the actual label values to evaluate how well (or not!) the model is working.
|
||||||
|
|
||||||
|
Let's start with making predictions for the test set then bind the columns to the test set.
|
||||||
|
|
||||||
|
```{r lm_pred}
|
||||||
|
# Make predictions for the test set
|
||||||
|
predictions <- lm_wf_fit %>%
|
||||||
|
predict(new_data = pumpkins_test)
|
||||||
|
|
||||||
|
|
||||||
|
# Bind predictions to the test set
|
||||||
|
lm_results <- pumpkins_test %>%
|
||||||
|
select(c(package, price)) %>%
|
||||||
|
bind_cols(predictions)
|
||||||
|
|
||||||
|
|
||||||
|
# Print the first ten rows of the tibble
|
||||||
|
lm_results %>%
|
||||||
|
slice_head(n = 10)
|
||||||
|
```
|
||||||
|
|
||||||
|
Yes, you have just trained a model and used it to make predictions!🔮 Is it any good, let's evaluate the model's performance!
|
||||||
|
|
||||||
|
In Tidymodels, we do this using `yardstick::metrics()`! For linear regression, let's focus on the following metrics:
|
||||||
|
|
||||||
|
- `Root Mean Square Error (RMSE)`: The square root of the [MSE](https://en.wikipedia.org/wiki/Mean_squared_error). This yields an absolute metric in the same unit as the label (in this case, the price of a pumpkin). The smaller the value, the better the model (in a simplistic sense, it represents the average price by which the predictions are wrong!)
|
||||||
|
|
||||||
|
- `Coefficient of Determination (usually known as R-squared or R2)`: A relative metric in which the higher the value, the better the fit of the model. In essence, this metric represents how much of the variance between predicted and actual label values the model is able to explain.
|
||||||
|
|
||||||
|
```{r lm_yardstick}
|
||||||
|
# Evaluate performance of linear regression
|
||||||
|
metrics(data = lm_results,
|
||||||
|
truth = price,
|
||||||
|
estimate = .pred)
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
There goes the model performance. Let's see if we can get a better indication by visualizing a scatter plot of the package and price then use the predictions made to overlay a line of best fit.
|
||||||
|
|
||||||
|
This means we'll have to prep and bake the test set in order to encode the package column then bind this to the predictions made by our model.
|
||||||
|
|
||||||
|
```{r lm_plot}
|
||||||
|
# Encode package column
|
||||||
|
package_encode <- lm_pumpkins_recipe %>%
|
||||||
|
prep() %>%
|
||||||
|
bake(new_data = pumpkins_test) %>%
|
||||||
|
select(package)
|
||||||
|
|
||||||
|
|
||||||
|
# Bind encoded package column to the results
|
||||||
|
lm_results <- lm_results %>%
|
||||||
|
bind_cols(package_encode %>%
|
||||||
|
rename(package_integer = package)) %>%
|
||||||
|
relocate(package_integer, .after = package)
|
||||||
|
|
||||||
|
|
||||||
|
# Print new results data frame
|
||||||
|
lm_results %>%
|
||||||
|
slice_head(n = 5)
|
||||||
|
|
||||||
|
|
||||||
|
# Make a scatter plot
|
||||||
|
lm_results %>%
|
||||||
|
ggplot(mapping = aes(x = package_integer, y = price)) +
|
||||||
|
geom_point(size = 1.6) +
|
||||||
|
# Overlay a line of best fit
|
||||||
|
geom_line(aes(y = .pred), color = "orange", size = 1.2) +
|
||||||
|
xlab("package")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Great! As you can see, the linear regression model does not really well generalize the relationship between a package and its corresponding price.
|
||||||
|
|
||||||
|
🎃 Congratulations, you just created a model that can help predict the price of a few varieties of pumpkins. Your holiday pumpkin patch will be beautiful. But you can probably create a better model!
|
||||||
|
|
||||||
|
## 5. Build a polynomial regression model
|
||||||
|
|
||||||
|
{width="800"}
|
||||||
|
|
||||||
|
Sometimes our data may not have a linear relationship, but we still want to predict an outcome. Polynomial regression can help us make predictions for more complex non-linear relationships.
|
||||||
|
|
||||||
|
Take for instance the relationship between the package and price for our pumpkins data set. While sometimes there's a linear relationship between variables - the bigger the pumpkin in volume, the higher the price - sometimes these relationships can't be plotted as a plane or straight line.
|
||||||
|
|
||||||
|
> ✅ Here are [some more examples](https://online.stat.psu.edu/stat501/lesson/9/9.8) of data that could use polynomial regression
|
||||||
|
>
|
||||||
|
> Take another look at the relationship between Variety to Price in the previous plot. Does this scatterplot seem like it should necessarily be analyzed by a straight line? Perhaps not. In this case, you can try polynomial regression.
|
||||||
|
>
|
||||||
|
> ✅ Polynomials are mathematical expressions that might consist of one or more variables and coefficients
|
||||||
|
|
||||||
|
#### Train a polynomial regression model using the training set
|
||||||
|
|
||||||
|
Polynomial regression creates a *curved line* to better fit nonlinear data.
|
||||||
|
|
||||||
|
Let's see whether a polynomial model will perform better in making predictions. We'll follow a somewhat similar procedure as we did before:
|
||||||
|
|
||||||
|
- Create a recipe that specifies the preprocessing steps that should be carried out on our data to get it ready for modelling i.e: encoding predictors and computing polynomials of degree *n*
|
||||||
|
|
||||||
|
- Build a model specification
|
||||||
|
|
||||||
|
- Bundle the recipe and model specification into a workflow
|
||||||
|
|
||||||
|
- Create a model by fitting the workflow
|
||||||
|
|
||||||
|
- Evaluate how well the model performs on the test data
|
||||||
|
|
||||||
|
Let's get right into it!
|
||||||
|
|
||||||
|
```{r polynomial_reg}
|
||||||
|
# Specify a recipe
|
||||||
|
poly_pumpkins_recipe <-
|
||||||
|
recipe(price ~ package, data = pumpkins_train) %>%
|
||||||
|
step_integer(all_predictors(), zero_based = TRUE) %>%
|
||||||
|
step_poly(all_predictors(), degree = 4)
|
||||||
|
|
||||||
|
|
||||||
|
# Create a model specification
|
||||||
|
poly_spec <- linear_reg() %>%
|
||||||
|
set_engine("lm") %>%
|
||||||
|
set_mode("regression")
|
||||||
|
|
||||||
|
|
||||||
|
# Bundle recipe and model spec into a workflow
|
||||||
|
poly_wf <- workflow() %>%
|
||||||
|
add_recipe(poly_pumpkins_recipe) %>%
|
||||||
|
add_model(poly_spec)
|
||||||
|
|
||||||
|
|
||||||
|
# Create a model
|
||||||
|
poly_wf_fit <- poly_wf %>%
|
||||||
|
fit(data = pumpkins_train)
|
||||||
|
|
||||||
|
|
||||||
|
# Print learned model coefficients
|
||||||
|
poly_wf_fit
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Evaluate model performance
|
||||||
|
|
||||||
|
👏👏You've built a polynomial model let's make predictions on the test set!
|
||||||
|
|
||||||
|
```{r poly_predict}
|
||||||
|
# Make price predictions on test data
|
||||||
|
poly_results <- poly_wf_fit %>% predict(new_data = pumpkins_test) %>%
|
||||||
|
bind_cols(pumpkins_test %>% select(c(package, price))) %>%
|
||||||
|
relocate(.pred, .after = last_col())
|
||||||
|
|
||||||
|
|
||||||
|
# Print the results
|
||||||
|
poly_results %>%
|
||||||
|
slice_head(n = 10)
|
||||||
|
```
|
||||||
|
|
||||||
|
Woo-hoo , let's evaluate how the model performed on the test_set using `yardstick::metrics()`.
|
||||||
|
|
||||||
|
```{r poly_eval}
|
||||||
|
metrics(data = poly_results, truth = price, estimate = .pred)
|
||||||
|
```
|
||||||
|
|
||||||
|
🤩🤩 Much better performance.
|
||||||
|
|
||||||
|
The `rmse` decreased from about 7. to about 3. an indication that of a reduced error between the actual price and the predicted price. You can *loosely* interpret this as meaning that on average, incorrect predictions are wrong by around \$3. The `rsq` increased from about 0.4 to 0.8.
|
||||||
|
|
||||||
|
All these metrics indicate that the polynomial model performs way better than the linear model. Good job!
|
||||||
|
|
||||||
|
Let's see if we can visualize this!
|
||||||
|
|
||||||
|
```{r poly_viz}
|
||||||
|
# Bind encoded package column to the results
|
||||||
|
poly_results <- poly_results %>%
|
||||||
|
bind_cols(package_encode %>%
|
||||||
|
rename(package_integer = package)) %>%
|
||||||
|
relocate(package_integer, .after = package)
|
||||||
|
|
||||||
|
|
||||||
|
# Print new results data frame
|
||||||
|
poly_results %>%
|
||||||
|
slice_head(n = 5)
|
||||||
|
|
||||||
|
|
||||||
|
# Make a scatter plot
|
||||||
|
poly_results %>%
|
||||||
|
ggplot(mapping = aes(x = package_integer, y = price)) +
|
||||||
|
geom_point(size = 1.6) +
|
||||||
|
# Overlay a line of best fit
|
||||||
|
geom_line(aes(y = .pred), color = "midnightblue", size = 1.2) +
|
||||||
|
xlab("package")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
You can see a curved line that fits your data better! 🤩
|
||||||
|
|
||||||
|
You can make this more smoother by passing a polynomial formula to `geom_smooth` like this:
|
||||||
|
|
||||||
|
```{r smooth curve}
|
||||||
|
# Make a scatter plot
|
||||||
|
poly_results %>%
|
||||||
|
ggplot(mapping = aes(x = package_integer, y = price)) +
|
||||||
|
geom_point(size = 1.6) +
|
||||||
|
# Overlay a line of best fit
|
||||||
|
geom_smooth(method = lm, formula = y ~ poly(x, degree = 4), color = "midnightblue", size = 1.2, se = FALSE) +
|
||||||
|
xlab("package")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Much like a smooth curve!🤩
|
||||||
|
|
||||||
|
Here's how you would make a new prediction:
|
||||||
|
|
||||||
|
```{r predict}
|
||||||
|
# Make a hypothetical data frame
|
||||||
|
hypo_tibble <- tibble(package = "bushel baskets")
|
||||||
|
|
||||||
|
# Make predictions using linear model
|
||||||
|
lm_pred <- lm_wf_fit %>% predict(new_data = hypo_tibble)
|
||||||
|
|
||||||
|
# Make predictions using polynomial model
|
||||||
|
poly_pred <- poly_wf_fit %>% predict(new_data = hypo_tibble)
|
||||||
|
|
||||||
|
# Return predictions in a list
|
||||||
|
list("linear model prediction" = lm_pred,
|
||||||
|
"polynomial model prediction" = poly_pred)
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
The `polynomial model` prediction does make sense, given the scatter plots of `price` and `package`! And, if this is a better model than the previous one, looking at the same data, you need to budget for these more expensive pumpkins!
|
||||||
|
|
||||||
|
🏆 Well done! You created two regression models in one lesson. In the final section on regression, you will learn about logistic regression to determine categories.
|
||||||
|
|
||||||
|
## **🚀Challenge**
|
||||||
|
|
||||||
|
Test several different variables in this notebook to see how correlation corresponds to model accuracy.
|
||||||
|
|
||||||
|
## [**Post-lecture quiz**](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/14/)
|
||||||
|
|
||||||
|
## **Review & Self Study**
|
||||||
|
|
||||||
|
In this lesson we learned about Linear Regression. There are other important types of Regression. Read about Stepwise, Ridge, Lasso and Elasticnet techniques. A good course to study to learn more is the [Stanford Statistical Learning course](https://online.stanford.edu/courses/sohs-ystatslearning-statistical-learning)
|
||||||
|
|
||||||
|
If you want to learn more about how to use the amazing Tidymodels framework, please check out the following resources:
|
||||||
|
|
||||||
|
- Tidymodels website: [Get started with Tidymodels](https://www.tidymodels.org/start/)
|
||||||
|
|
||||||
|
- Max Kuhn and Julia Silge, [*Tidy Modeling with R*](https://www.tmwr.org/)*.*
|
||||||
|
|
||||||
|
###### **THANK YOU TO:**
|
||||||
|
|
||||||
|
[Allison Horst](https://twitter.com/allison_horst?lang=en) for creating the amazing illustrations that make R more welcoming and engaging. Find more illustrations at her [gallery](https://www.google.com/url?q=https://github.com/allisonhorst/stats-illustrations&sa=D&source=editors&ust=1626380772530000&usg=AOvVaw3zcfyCizFQZpkSLzxiiQEM).
|
@ -0,0 +1,11 @@
|
|||||||
|
# Creare un Modello di Regressione
|
||||||
|
|
||||||
|
## Istruzioni
|
||||||
|
|
||||||
|
In questa lezione è stato mostrato come costruire un modello utilizzando sia la Regressione Lineare che Polinomiale. Usando questa conoscenza, trovare un insieme di dati o utilizzare uno degli insiemi integrati di Scikit-Learn per costruire un modello nuovo. Spiegare nel proprio notebook perché si è scelto una determinata tecnica e dimostrare la precisione del modello. Se non è accurato, spiegare perché.
|
||||||
|
|
||||||
|
## Rubrica
|
||||||
|
|
||||||
|
| Criteri | Ottimo | Adeguato | Necessita miglioramento |
|
||||||
|
| -------- | ------------------------------------------------------------ | -------------------------- | ------------------------------- |
|
||||||
|
| | presenta un notebook completo con una soluzione ben documentata | La soluzione è incompleta | La soluzione è difettosa o contiene bug |
|
@ -0,0 +1,12 @@
|
|||||||
|
# 创建自己的回归模型
|
||||||
|
|
||||||
|
## 说明
|
||||||
|
|
||||||
|
在这节课中你学到了如何用线性回归和多项式回归建立一个模型。利用这些只是,找到一个你感兴趣的数据集或者是 Scikit-learn 内置的数据集来建立一个全新的模型。用你的 notebook 来解释为什么用了这种技术来对这个数据集进行建模,并且证明出你的模型的准确度。如果它没你想象中准确,请思考一下并解释一下原因。
|
||||||
|
|
||||||
|
## 评判标准
|
||||||
|
|
||||||
|
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
|
||||||
|
| -------- | ------------------------------------------------------------ | -------------------------- | ------------------------------- |
|
||||||
|
| | 提交了一个完整的 notebook 工程文件,其中包含了解集,并且可读性良好 | 不完整的解集 | 解集是有缺陷或者有错误的 |
|
||||||
|
|
@ -0,0 +1,295 @@
|
|||||||
|
# Regressione logistica per prevedere le categorie
|
||||||
|
|
||||||
|

|
||||||
|
> Infografica di [Dasani Madipalli](https://twitter.com/dasani_decoded)
|
||||||
|
|
||||||
|
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/15/)
|
||||||
|
|
||||||
|
## Introduzione
|
||||||
|
|
||||||
|
In questa lezione finale sulla Regressione, una delle tecniche _classiche_ di base di machine learning, si darà un'occhiata alla Regressione Logistica. Si dovrebbe utilizzare questa tecnica per scoprire modelli per prevedere le categorie binarie. Questa caramella è al cioccolato o no? Questa malattia è contagiosa o no? Questo cliente sceglierà questo prodotto o no?
|
||||||
|
|
||||||
|
In questa lezione, si imparerà:
|
||||||
|
|
||||||
|
- Una nuova libreria per la visualizzazione dei dati
|
||||||
|
- Tecniche per la regressione logistica
|
||||||
|
|
||||||
|
✅ Con questo [modulo di apprendimento](https://docs.microsoft.com/learn/modules/train-evaluate-classification-models?WT.mc_id=academic-15963-cxa) si potrà approfondire la comprensione del lavoro con questo tipo di regressione
|
||||||
|
## Prerequisito
|
||||||
|
|
||||||
|
Avendo lavorato con i dati della zucca, ora si ha abbastanza familiarità con essi per rendersi conto che esiste una categoria binaria con cui è possibile lavorare: `Color` (Colore).
|
||||||
|
|
||||||
|
Si costruisce un modello di regressione logistica per prevedere, date alcune variabili, di _che colore sarà probabilmente una data zucca_ (arancione 🎃 o bianca 👻).
|
||||||
|
|
||||||
|
> Perché si parla di classificazione binaria in un gruppo di lezioni sulla regressione? Solo per comodità linguistica, poiché la regressione logistica è in [realtà un metodo di classificazione](https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression), anche se lineare. Si scopriranno altri modi per classificare i dati nel prossimo gruppo di lezioni.
|
||||||
|
|
||||||
|
## Definire la domanda
|
||||||
|
|
||||||
|
Allo scopo, verrà espressa come binaria: 'Arancio' o 'Non Arancio'. C'è anche una categoria "striped" (a strisce) nell'insieme di dati, ma ci sono pochi casi, quindi non verrà presa in considerazione. Comunque scompare una volta rimossi i valori null dall'insieme di dati.
|
||||||
|
|
||||||
|
> 🎃 Fatto divertente, a volte le zucche bianche vengono chiamate zucche "fantasma" Non sono molto facili da intagliare, quindi non sono così popolari come quelle arancioni ma hanno un bell'aspetto!
|
||||||
|
|
||||||
|
## Informazioni sulla regressione logistica
|
||||||
|
|
||||||
|
La regressione logistica differisce dalla regressione lineare, che si è appresa in precedenza, in alcuni importanti modi.
|
||||||
|
|
||||||
|
### Classificazione Binaria
|
||||||
|
|
||||||
|
La regressione logistica non offre le stesse caratteristiche della regressione lineare. La prima offre una previsione su una categoria binaria ("arancione o non arancione") mentre la seconda è in grado di prevedere valori continui, ad esempio data l'origine di una zucca e il momento del raccolto, di _quanto aumenterà il suo prezzo_.
|
||||||
|
|
||||||
|

|
||||||
|
> Infografica di [Dasani Madipalli](https://twitter.com/dasani_decoded)
|
||||||
|
### Altre classificazioni:
|
||||||
|
|
||||||
|
Esistono altri tipi di regressione logistica, inclusi multinomiale e ordinale:
|
||||||
|
|
||||||
|
- **Multinomiale**, che implica avere più di una categoria: "arancione, bianco e a strisce".
|
||||||
|
- **Ordinale**, che coinvolge categorie ordinate, utile se si volessero ordinare i risultati in modo logico, come le zucche che sono ordinate per un numero finito di dimensioni (mini,sm,med,lg,xl,xxl).
|
||||||
|
|
||||||
|

|
||||||
|
> Infografica di [Dasani Madipalli](https://twitter.com/dasani_decoded)
|
||||||
|
|
||||||
|
### È ancora lineare
|
||||||
|
|
||||||
|
Anche se questo tipo di Regressione riguarda le "previsioni di categoria", funziona ancora meglio quando esiste una chiara relazione lineare tra la variabile dipendente (colore) e le altre variabili indipendenti (il resto dell'insieme di dati, come il nome della città e le dimensioni) . È bene avere un'idea se c'è qualche linearità che divide queste variabili o meno.
|
||||||
|
|
||||||
|
### Le variabili NON devono essere correlate
|
||||||
|
|
||||||
|
Si ricorda come la regressione lineare ha funzionato meglio con più variabili correlate? La regressione logistica è l'opposto: le variabili non devono essere allineate. Funziona per questi dati che hanno correlazioni alquanto deboli.
|
||||||
|
|
||||||
|
### Servono molti dati puliti
|
||||||
|
|
||||||
|
La regressione logistica fornirà risultati più accurati se si utilizzano più dati; quindi si tenga a mente che, essendo l'insieme di dati sulla zucca piccolo, non è ottimale per questo compito
|
||||||
|
|
||||||
|
✅ Si pensi ai tipi di dati che si prestano bene alla regressione logistica
|
||||||
|
|
||||||
|
## Esercizio: riordinare i dati
|
||||||
|
|
||||||
|
Innanzitutto, si puliscono un po 'i dati, eliminando i valori null e selezionando solo alcune delle colonne:
|
||||||
|
|
||||||
|
1. Aggiungere il seguente codice:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.preprocessing import LabelEncoder
|
||||||
|
|
||||||
|
new_columns = ['Color','Origin','Item Size','Variety','City Name','Package']
|
||||||
|
|
||||||
|
new_pumpkins = pumpkins.drop([c for c in pumpkins.columns if c not in new_columns], axis=1)
|
||||||
|
|
||||||
|
new_pumpkins.dropna(inplace=True)
|
||||||
|
|
||||||
|
new_pumpkins = new_pumpkins.apply(LabelEncoder().fit_transform)
|
||||||
|
```
|
||||||
|
|
||||||
|
Si può sempre dare un'occhiata al nuovo dataframe:
|
||||||
|
|
||||||
|
```python
|
||||||
|
new_pumpkins.info
|
||||||
|
```
|
||||||
|
|
||||||
|
### Visualizzazione - griglia affiancata
|
||||||
|
|
||||||
|
A questo punto si è caricato di nuovo il [notebook iniziale](../notebook.ipynb) con i dati della zucca e lo si è pulito in modo da preservare un insieme di dati contenente alcune variabili, incluso `Color`. Si visualizza il dataframe nel notebook utilizzando una libreria diversa: [Seaborn](https://seaborn.pydata.org/index.html), che è costruita su Matplotlib, usata in precedenza.
|
||||||
|
|
||||||
|
Seaborn offre alcuni modi accurati per visualizzare i dati. Ad esempio, si possono confrontare le distribuzioni dei dati per ogni punto in una griglia affiancata.
|
||||||
|
|
||||||
|
1. Si crea una griglia di questo tipo istanziando `PairGrid`, usando i dati della zucca `new_pumpkins`, poi chiamando `map()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import seaborn as sns
|
||||||
|
|
||||||
|
g = sns.PairGrid(new_pumpkins)
|
||||||
|
g.map(sns.scatterplot)
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Osservando i dati fianco a fianco, si può vedere come i dati di Color si riferiscono alle altre colonne.
|
||||||
|
|
||||||
|
✅ Data questa griglia del grafico a dispersione, quali sono alcune esplorazioni interessanti che si possono immaginare?
|
||||||
|
|
||||||
|
### Usare un grafico a sciame
|
||||||
|
|
||||||
|
Poiché Color è una categoria binaria (arancione o no), viene chiamata "dati categoriali" e richiede "un [approccio più specializzato](https://seaborn.pydata.org/tutorial/categorical.html?highlight=bar) alla visualizzazione". Esistono altri modi per visualizzare la relazione di questa categoria con altre variabili.
|
||||||
|
|
||||||
|
È possibile visualizzare le variabili fianco a fianco con i grafici di Seaborn.
|
||||||
|
|
||||||
|
1. Si provi un grafico a "sciame" per mostrare la distribuzione dei valori:
|
||||||
|
|
||||||
|
```python
|
||||||
|
sns.swarmplot(x="Color", y="Item Size", data=new_pumpkins)
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
### Grafico violino
|
||||||
|
|
||||||
|
Un grafico di tipo "violino" è utile in quanto è possibile visualizzare facilmente il modo in cui sono distribuiti i dati nelle due categorie. I grafici di tipo violino non funzionano così bene con insieme di dati più piccoli poiché la distribuzione viene visualizzata in modo più "liscio".
|
||||||
|
|
||||||
|
1. Chiamare `catplot()` passando i parametri `x=Color`, `kind="violin"` :
|
||||||
|
|
||||||
|
```python
|
||||||
|
sns.catplot(x="Color", y="Item Size",
|
||||||
|
kind="violin", data=new_pumpkins)
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
✅ Provare a creare questo grafico e altri grafici Seaborn, utilizzando altre variabili.
|
||||||
|
|
||||||
|
Ora che si ha un'idea della relazione tra le categorie binarie di colore e il gruppo più ampio di dimensioni, si esplora la regressione logistica per determinare il probabile colore di una data zucca.
|
||||||
|
|
||||||
|
> **🧮 Mostrami la matematica**
|
||||||
|
>
|
||||||
|
> Si ricorda come la regressione lineare usava spesso i minimi quadrati ordinari per arrivare a un valore? La regressione logistica si basa sul concetto di "massima verosimiglianza" utilizzando [le funzioni sigmoidi](https://wikipedia.org/wiki/Sigmoid_function). Una "Funzione Sigmoide" su un grafico ha l'aspetto di una forma a "S". Prende un valore e lo mappa da qualche parte tra 0 e 1. La sua curva è anche chiamata "curva logistica". La sua formula si presenta così:
|
||||||
|
>
|
||||||
|
> 
|
||||||
|
>
|
||||||
|
> dove il punto medio del sigmoide si trova nel punto 0 di x, L è il valore massimo della curva e k è la pendenza della curva. Se l'esito della funzione è maggiore di 0,5, all'etichetta in questione verrà assegnata la classe '1' della scelta binaria. In caso contrario, sarà classificata come '0'.
|
||||||
|
|
||||||
|
## Costruire il modello
|
||||||
|
|
||||||
|
Costruire un modello per trovare queste classificazioni binarie è sorprendentemente semplice in Scikit-learn.
|
||||||
|
|
||||||
|
1. Si selezionano le variabili da utilizzare nel modello di classificazione e si dividono gli insiemi di training e test chiamando `train_test_split()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.model_selection import train_test_split
|
||||||
|
|
||||||
|
Selected_features = ['Origin','Item Size','Variety','City Name','Package']
|
||||||
|
|
||||||
|
X = new_pumpkins[Selected_features]
|
||||||
|
y = new_pumpkins['Color']
|
||||||
|
|
||||||
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Ora si può addestrare il modello, chiamando `fit()` con i dati di addestramento e stamparne il risultato:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.model_selection import train_test_split
|
||||||
|
from sklearn.metrics import accuracy_score, classification_report
|
||||||
|
from sklearn.linear_model import LogisticRegression
|
||||||
|
|
||||||
|
model = LogisticRegression()
|
||||||
|
model.fit(X_train, y_train)
|
||||||
|
predictions = model.predict(X_test)
|
||||||
|
|
||||||
|
print(classification_report(y_test, predictions))
|
||||||
|
print('Predicted labels: ', predictions)
|
||||||
|
print('Accuracy: ', accuracy_score(y_test, predictions))
|
||||||
|
```
|
||||||
|
|
||||||
|
Si dia un'occhiata al tabellone segnapunti del modello. Non è male, considerando che si hanno solo circa 1000 righe di dati:
|
||||||
|
|
||||||
|
```output
|
||||||
|
precision recall f1-score support
|
||||||
|
|
||||||
|
0 0.85 0.95 0.90 166
|
||||||
|
1 0.38 0.15 0.22 33
|
||||||
|
|
||||||
|
accuracy 0.82 199
|
||||||
|
macro avg 0.62 0.55 0.56 199
|
||||||
|
weighted avg 0.77 0.82 0.78 199
|
||||||
|
|
||||||
|
Predicted labels: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
|
||||||
|
0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
|
||||||
|
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
|
||||||
|
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
|
||||||
|
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
|
||||||
|
0 0 0 1 0 1 0 0 1 0 0 0 1 0]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migliore comprensione tramite una matrice di confusione
|
||||||
|
|
||||||
|
Sebbene si possano ottenere [i termini](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html?highlight=classification_report#sklearn.metrics.classification_report) del rapporto dei punteggi stampando gli elementi di cui sopra, si potrebbe essere in grado di comprendere più facilmente il modello utilizzando una [matrice di confusione](https://scikit-learn.org/stable/modules/model_evaluation.html#confusion-matrix) che aiuti a capire come lo stesso sta funzionando.
|
||||||
|
|
||||||
|
> 🎓 Una '[matrice di confusione](https://it.wikipedia.org/wiki/Matrice_di_confusione)' (o 'matrice di errore') è una tabella che esprime i veri contro i falsi positivi e negativi del modello, misurando così l'accuratezza delle previsioni.
|
||||||
|
|
||||||
|
1. Per utilizzare una metrica di confusione, si `chiama confusion_matrix()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.metrics import confusion_matrix
|
||||||
|
confusion_matrix(y_test, predictions)
|
||||||
|
```
|
||||||
|
|
||||||
|
Si dia un'occhiata alla matrice di confusione del modello:
|
||||||
|
|
||||||
|
```output
|
||||||
|
array([[162, 4],
|
||||||
|
[ 33, 0]])
|
||||||
|
```
|
||||||
|
|
||||||
|
Cosa sta succedendo qui? Si supponga che al modello venga chiesto di classificare gli elementi tra due categorie binarie, la categoria "zucca" e la categoria "non una zucca".
|
||||||
|
|
||||||
|
- Se il modello prevede qualcosa come una zucca e appartiene alla categoria 'zucca' in realtà lo si chiama un vero positivo, mostrato dal numero in alto a sinistra.
|
||||||
|
- Se il modello prevede qualcosa come non una zucca e appartiene alla categoria 'zucca' in realtà si chiama falso positivo, mostrato dal numero in alto a destra.
|
||||||
|
- Se il modello prevede qualcosa come una zucca e appartiene alla categoria 'non-una-zucca' in realtà si chiama falso negativo, mostrato dal numero in basso a sinistra.
|
||||||
|
- Se il modello prevede qualcosa come non una zucca e appartiene alla categoria 'non-una-zucca' in realtà lo si chiama un vero negativo, mostrato dal numero in basso a destra.
|
||||||
|
|
||||||
|
Come si sarà intuito, è preferibile avere un numero maggiore di veri positivi e veri negativi e un numero inferiore di falsi positivi e falsi negativi, il che implica che il modello funziona meglio.
|
||||||
|
|
||||||
|
✅ Domanda: Secondo la matrice di confusione, come si è comportato il modello? Risposta: Non male; ci sono un buon numero di veri positivi ma anche diversi falsi negativi.
|
||||||
|
|
||||||
|
I termini visti in precedenza vengono rivisitati con l'aiuto della mappatura della matrice di confusione di TP/TN e FP/FN:
|
||||||
|
|
||||||
|
🎓 Precisione: TP/(TP + FP) La frazione di istanze rilevanti tra le istanze recuperate (ad es. quali etichette erano ben etichettate)
|
||||||
|
|
||||||
|
🎓 Richiamo: TP/(TP + FN) La frazione di istanze rilevanti che sono state recuperate, ben etichettate o meno
|
||||||
|
|
||||||
|
🎓 f1-score: (2 * precisione * richiamo)/(precisione + richiamo) Una media ponderata della precisione e del richiamo, dove il migliore è 1 e il peggiore è 0
|
||||||
|
|
||||||
|
🎓 Supporto: il numero di occorrenze di ciascuna etichetta recuperata
|
||||||
|
|
||||||
|
🎓 Accuratezza: (TP + TN)/(TP + TN + FP + FN) La percentuale di etichette prevista accuratamente per un campione.
|
||||||
|
|
||||||
|
🎓 Macro Media: il calcolo delle metriche medie non ponderate per ciascuna etichetta, senza tener conto dello squilibrio dell'etichetta.
|
||||||
|
|
||||||
|
🎓 Media ponderata: il calcolo delle metriche medie per ogni etichetta, tenendo conto dello squilibrio dell'etichetta pesandole in base al loro supporto (il numero di istanze vere per ciascuna etichetta).
|
||||||
|
|
||||||
|
✅ Si riesce a pensare a quale metrica si dovrebbe guardare se si vuole che il modello riduca il numero di falsi negativi?
|
||||||
|
|
||||||
|
## Visualizzare la curva ROC di questo modello
|
||||||
|
|
||||||
|
Questo non è un cattivo modello; la sua precisione è nell'intervallo dell'80%, quindi idealmente si potrebbe usare per prevedere il colore di una zucca dato un insieme di variabili.
|
||||||
|
|
||||||
|
Si rende un'altra visualizzazione per vedere il cosiddetto punteggio 'ROC':
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.metrics import roc_curve, roc_auc_score
|
||||||
|
|
||||||
|
y_scores = model.predict_proba(X_test)
|
||||||
|
# calculate ROC curve
|
||||||
|
fpr, tpr, thresholds = roc_curve(y_test, y_scores[:,1])
|
||||||
|
sns.lineplot([0, 1], [0, 1])
|
||||||
|
sns.lineplot(fpr, tpr)
|
||||||
|
```
|
||||||
|
Usando di nuovo Seaborn, si traccia la [Caratteristica Operativa di Ricezione](https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html?highlight=roc) o il ROC del modello. Le curve ROC vengono spesso utilizzate per ottenere una visualizzazione dell'output di un classificatore in termini di veri e falsi positivi. "Le curve ROC in genere presentano un tasso di veri positivi sull'asse Y e un tasso di falsi positivi sull'asse X". Pertanto, la ripidità della curva e lo spazio tra la linea del punto medio e la curva contano: si vuole una curva che si sposti rapidamente verso l'alto e oltre la linea. In questo caso, ci sono falsi positivi con cui iniziare, quindi la linea si dirige correttamente:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Infine, si usa l'[`API roc_auc_score`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html?highlight=roc_auc#sklearn.metrics.roc_auc_score) di Scikit-learn per calcolare l'effettiva "Area sotto la curva" (AUC):
|
||||||
|
|
||||||
|
```python
|
||||||
|
auc = roc_auc_score(y_test,y_scores[:,1])
|
||||||
|
print(auc)
|
||||||
|
```
|
||||||
|
Il risultato è `0.6976998904709748`. Dato che l'AUC varia da 0 a 1, si desidera un punteggio elevato, poiché un modello corretto al 100% nelle sue previsioni avrà un AUC di 1; in questo caso, il modello è _abbastanza buono_.
|
||||||
|
|
||||||
|
Nelle lezioni future sulle classificazioni si imparerà come eseguire l'iterazione per migliorare i punteggi del modello. Ma per ora, congratulazioni! Si sono completate queste lezioni di regressione!
|
||||||
|
|
||||||
|
---
|
||||||
|
## 🚀 Sfida
|
||||||
|
|
||||||
|
C'è molto altro da svelare riguardo alla regressione logistica! Ma il modo migliore per imparare è sperimentare. Trovare un insieme di dati che si presti a questo tipo di analisi e costruire un modello con esso. Cosa si è appreso? suggerimento: provare [Kaggle](https://kaggle.com) per ottenere insiemi di dati interessanti.
|
||||||
|
|
||||||
|
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/16/)
|
||||||
|
|
||||||
|
## Revisione e Auto Apprendimento
|
||||||
|
|
||||||
|
Leggere le prime pagine di [questo articolo da Stanford](https://web.stanford.edu/~jurafsky/slp3/5.pdf) su alcuni usi pratici della regressione logistica. Si pensi alle attività più adatte per l'uno o l'altro tipo di attività di regressione studiate fino a questo punto. Cosa funzionerebbe meglio?
|
||||||
|
|
||||||
|
## Compito
|
||||||
|
|
||||||
|
[Ritentare questa regressione](assignment.it.md)
|
@ -0,0 +1,10 @@
|
|||||||
|
# Riprovare un po' di Regressione
|
||||||
|
|
||||||
|
## Istruzioni
|
||||||
|
|
||||||
|
Nella lezione è stato usato un sottoinsieme dei dati della zucca. Ora si torna ai dati originali e si prova a usarli tutti, puliti e standardizzati, per costruire un modello di regressione logistica.
|
||||||
|
## Rubrica
|
||||||
|
|
||||||
|
| Criteri | Ottimo | Adeguato | Necessita miglioramento |
|
||||||
|
| -------- | ----------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------- |
|
||||||
|
| | Un notebook viene presentato con un modello ben spiegato con buone prestazioni | Un notebook viene presentato con un modello dalle prestazioni minime | Un notebook viene presentato con un modello con scarse o nessuna prestazione |
|
@ -0,0 +1,11 @@
|
|||||||
|
# 回帰に再挑戦する
|
||||||
|
|
||||||
|
## 課題の指示
|
||||||
|
|
||||||
|
レッスンでは、カボチャのデータのサブセットを使用しました。今度は、元のデータに戻って、ロジスティック回帰モデルを構築するために、整形して標準化したデータをすべて使ってみましょう。
|
||||||
|
|
||||||
|
## ルーブリック
|
||||||
|
|
||||||
|
| 指標 | 模範的 | 適切 | 要改善 |
|
||||||
|
| -------- | ----------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------- |
|
||||||
|
| | 説明がわかりやすく、性能の良いモデルが含まれたノートブック| 最小限の性能しか発揮できないモデルが含まれたノートブック | 性能の劣るモデルや、何もないモデルが含まれたノートブック |
|
@ -0,0 +1,11 @@
|
|||||||
|
# 再探回归模型
|
||||||
|
|
||||||
|
## 说明
|
||||||
|
|
||||||
|
在这节课中,你使用了 pumpkin 数据集的子集。现在,让我们回到原始数据,并尝试使用所有数据。经过了数据清理和标准化,建立一个逻辑回归模型。
|
||||||
|
|
||||||
|
## 评判标准
|
||||||
|
|
||||||
|
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
|
||||||
|
| -------- | ----------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------- |
|
||||||
|
| | 用notebook呈现了一个解释性和性能良好的模型 | 用notebook呈现了一个性能一般的模型 | 用notebook呈现了一个性能差的模型或根本没有模型 |
|
@ -0,0 +1,33 @@
|
|||||||
|
# Modèles de régression pour le machine learning
|
||||||
|
## Sujet régional : Modèles de régression des prix des citrouilles en Amérique du Nord 🎃
|
||||||
|
|
||||||
|
En Amérique du Nord, les citrouilles sont souvent sculptées en visages effrayants pour Halloween. Découvrons-en plus sur ces légumes fascinants!
|
||||||
|
|
||||||
|

|
||||||
|
> Photo de <a href="https://unsplash.com/@teutschmann?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Beth Teutschmann</a> sur <a href="https://unsplash.com/s/photos/jack-o-lanterns?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
|
||||||
|
|
||||||
|
## Ce que vous apprendrez
|
||||||
|
|
||||||
|
Les leçons de cette section couvrent les types de régression dans le contexte du machine learning. Les modèles de régression peuvent aider à déterminer la _relation_ entre les variables. Ce type de modèle peut prédire des valeurs telles que la longueur, la température ou l'âge, découvrant ainsi les relations entre les variables lors de l'analyse des points de données.
|
||||||
|
|
||||||
|
Dans cette série de leçons, vous découvrirez la différence entre la régression linéaire et la régression logistique, et quand vous devriez utiliser l'une ou l'autre.
|
||||||
|
|
||||||
|
Dans ce groupe de leçons, vous serez préparé afin de commencer les tâches de machine learning, y compris la configuration de Visual Studio Code pour gérer les blocs-notes, l'environnement commun pour les scientifiques des données. Vous découvrirez Scikit-learn, une bibliothèque pour le machine learning, et vous construirez vos premiers modèles, en vous concentrant sur les modèles de régression dans ce chapitre.
|
||||||
|
|
||||||
|
> Il existe des outils low-code utiles qui peuvent vous aider à apprendre à travailler avec des modèles de régression. Essayez [Azure ML pour cette tâche](https://docs.microsoft.com/learn/modules/create-regression-model-azure-machine-learning-designer/?WT.mc_id=academic-15963-cxa)
|
||||||
|
|
||||||
|
### Cours
|
||||||
|
|
||||||
|
1. [Outils du métier](1-Tools/translations/README.fr.md)
|
||||||
|
2. [Gestion des données](2-Data/translations/README.fr.md)
|
||||||
|
3. [Régression linéaire et polynomiale](3-Linear/translations/README.fr.md)
|
||||||
|
4. [Régression logistique](4-Logistic/translations/README.fr.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
### Crédits
|
||||||
|
|
||||||
|
"ML avec régression" a été écrit avec ♥️ par [Jen Looper](https://twitter.com/jenlooper)
|
||||||
|
|
||||||
|
♥️ Les contributeurs du quiz incluent : [Muhammad Sakib Khan Inan](https://twitter.com/Sakibinan) et [Ornella Altunyan](https://twitter.com/ornelladotcom)
|
||||||
|
|
||||||
|
L'ensemble de données sur la citrouille est suggéré par [ce projet sur Kaggle](https://www.kaggle.com/usda/a-year-of-pumpkin-prices) et ses données proviennent des [Rapports standard des marchés terminaux des cultures spécialisées](https://www.marketnews.usda.gov/mnp/fv-report-config-step1?type=termPrice) distribué par le département américain de l'Agriculture. Nous avons ajouté quelques points autour de la couleur en fonction de la variété pour normaliser la distribution. Ces données sont dans le domaine public.
|
@ -0,0 +1,34 @@
|
|||||||
|
# Modelli di regressione per machine learning
|
||||||
|
|
||||||
|
## Argomento regionale: modelli di Regressione per i prezzi della zucca in Nord America 🎃
|
||||||
|
|
||||||
|
In Nord America, le zucche sono spesso intagliate in facce spaventose per Halloween. Si scoprirà di più su queste affascinanti verdure!
|
||||||
|
|
||||||
|

|
||||||
|
> Foto di <a href="https://unsplash.com/@teutschmann?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Beth Teutschmann</a> su <a href="https://unsplash.com/s/photos/jack-o-lanterns?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
|
||||||
|
|
||||||
|
## Cosa si imparerà
|
||||||
|
|
||||||
|
Le lezioni in questa sezione riguardano i tipi di regressione nel contesto di machine learning. I modelli di regressione possono aiutare a determinare la _relazione_ tra le variabili. Questo tipo di modello può prevedere valori come lunghezza, temperatura o età, scoprendo così le relazioni tra le variabili mentre analizza i punti dati.
|
||||||
|
|
||||||
|
In questa serie di lezioni si scoprirà la differenza tra regressione lineare e regressione logistica e quando si dovrebbe usare l'una o l'altra.
|
||||||
|
|
||||||
|
In questo gruppo di lezioni si imposterà una configurazione per iniziare le attività di machine learning, inclusa la configurazione di Visual Studio Code per gestire i notebook, l'ambiente comune per i data scientist. Si scoprirà Scikit-learn, una libreria per machine learning, e si creeranno i primi modelli, concentrandosi in questo capitolo sui modelli di Regressione.
|
||||||
|
|
||||||
|
> Esistono utili strumenti a basso codice che possono aiutare a imparare a lavorare con i modelli di regressione. Si provi [Azure Machine Learning per questa attività](https://docs.microsoft.com/learn/modules/create-regression-model-azure-machine-learning-designer/?WT.mc_id=academic-15963-cxa)
|
||||||
|
|
||||||
|
### Lezioni
|
||||||
|
|
||||||
|
1. [Gli Attrezzi Necessari](../1-Tools/translations/README.it.md)
|
||||||
|
2. [Gestione dati](../2-Data/translations/README.it.md)
|
||||||
|
3. [Regressione lineare e polinomiale](../3-Linear/translations/README.it.md)
|
||||||
|
4. [Regressione logistica](../4-Logistic/translations/README.it.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
### Crediti
|
||||||
|
|
||||||
|
"ML con regressione" scritto con ♥️ da [Jen Looper](https://twitter.com/jenlooper)
|
||||||
|
|
||||||
|
♥️ I collaboratori del quiz includono: [Muhammad Sakib Khan Inan](https://twitter.com/Sakibinan) e [Ornella Altunyan](https://twitter.com/ornelladotcom)
|
||||||
|
|
||||||
|
L'insieme di dati relativi alla zucca è suggerito da [questo progetto su](https://www.kaggle.com/usda/a-year-of-pumpkin-prices) Kaggle e i suoi dati provengono dai [Rapporti Standard sui Mercati Terminali delle Colture Speciali](https://www.marketnews.usda.gov/mnp/fv-report-config-step1?type=termPrice) distribuiti dal Dipartimento dell'Agricoltura degli Stati Uniti. Sono stati aggiunti alcuni punti intorno al colore in base alla varietà per normalizzare la distribuzione. Questi dati sono di pubblico dominio.
|
@ -0,0 +1,347 @@
|
|||||||
|
# Creare un'app web per utilizzare un modello ML
|
||||||
|
|
||||||
|
In questa lezione, si addestrerà un modello ML su un insieme di dati fuori dal mondo: _avvistamenti di UFO nel secolo scorso_, provenienti dal [database di NUFORC](https://www.nuforc.org).
|
||||||
|
|
||||||
|
Si imparerà:
|
||||||
|
|
||||||
|
- Come serializzare/deserializzare un modello addestrato
|
||||||
|
- Come usare quel modello in un'app Flask
|
||||||
|
|
||||||
|
Si continuerà a utilizzare il notebook per pulire i dati e addestrare il modello, ma si può fare un ulteriore passo avanti nel processo esplorando l'utilizzo del modello direttamente in un'app web.
|
||||||
|
|
||||||
|
Per fare ciò, è necessario creare un'app Web utilizzando Flask.
|
||||||
|
|
||||||
|
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/17/)
|
||||||
|
|
||||||
|
## Costruire un'app
|
||||||
|
|
||||||
|
Esistono diversi modi per creare app Web per utilizzare modelli di machine learning. L'architettura web può influenzare il modo in cui il modello viene addestrato. Si immagini di lavorare in un'azienda nella quale il gruppo di data science ha addestrato un modello che va utilizzato in un'app.
|
||||||
|
|
||||||
|
### Considerazioni
|
||||||
|
|
||||||
|
Ci sono molte domande da porsi:
|
||||||
|
|
||||||
|
- **È un'app web o un'app su dispositivo mobile?** Se si sta creando un'app su dispositivo mobile o si deve usare il modello in un contesto IoT, ci si può avvalere [di TensorFlow Lite](https://www.tensorflow.org/lite/) e usare il modello in un'app Android o iOS.
|
||||||
|
- **Dove risiederà il modello**? E' utilizzato in cloud o in locale?
|
||||||
|
- **Supporto offline**. L'app deve funzionare offline?
|
||||||
|
- **Quale tecnologia è stata utilizzata per addestrare il modello?** La tecnologia scelta può influenzare gli strumenti che è necessario utilizzare.
|
||||||
|
- **Utilizzare** TensorFlow. Se si sta addestrando un modello utilizzando TensorFlow, ad esempio, tale ecosistema offre la possibilità di convertire un modello TensorFlow per l'utilizzo in un'app Web utilizzando [TensorFlow.js](https://www.tensorflow.org/js/).
|
||||||
|
- **Utilizzare PyTorch**. Se si sta costruendo un modello utilizzando una libreria come PyTorch[,](https://pytorch.org/) si ha la possibilità di esportarlo in formato [ONNX](https://onnx.ai/) ( Open Neural Network Exchange) per l'utilizzo in app Web JavaScript che possono utilizzare il [motore di esecuzione Onnx](https://www.onnxruntime.ai/). Questa opzione verrà esplorata in una lezione futura per un modello addestrato da Scikit-learn
|
||||||
|
- **Utilizzo di Lobe.ai o Azure Custom vision**. Se si sta usando un sistema ML SaaS (Software as a Service) come [Lobe.ai](https://lobe.ai/) o [Azure Custom Vision](https://azure.microsoft.com/services/cognitive-services/custom-vision-service/?WT.mc_id=academic-15963-cxa) per addestrare un modello, questo tipo di software fornisce modi per esportare il modello per molte piattaforme, inclusa la creazione di un'API su misura da interrogare nel cloud dalla propria applicazione online.
|
||||||
|
|
||||||
|
Si ha anche l'opportunità di creare un'intera app Web Flask in grado di addestrare il modello stesso in un browser Web. Questo può essere fatto anche usando TensorFlow.js in un contesto JavaScript.
|
||||||
|
|
||||||
|
Per questo scopo, poiché si è lavorato con i notebook basati su Python, verranno esplorati i passaggi necessari per esportare un modello addestrato da tale notebook in un formato leggibile da un'app Web creata in Python.
|
||||||
|
|
||||||
|
## Strumenti
|
||||||
|
|
||||||
|
Per questa attività sono necessari due strumenti: Flask e Pickle, entrambi eseguiti su Python.
|
||||||
|
|
||||||
|
✅ Cos'è [Flask](https://palletsprojects.com/p/flask/)? Definito come un "micro-framework" dai suoi creatori, Flask fornisce le funzionalità di base dei framework web utilizzando Python e un motore di template per creare pagine web. Si dia un'occhiata a [questo modulo di apprendimento](https://docs.microsoft.com/learn/modules/python-flask-build-ai-web-app?WT.mc_id=academic-15963-cxa) per esercitarsi a sviluppare con Flask.
|
||||||
|
|
||||||
|
✅ Cos'è [Pickle](https://docs.python.org/3/library/pickle.html)? Pickle 🥒 è un modulo Python che serializza e de-serializza la struttura di un oggetto Python. Quando si utilizza pickle in un modello, si serializza o si appiattisce la sua struttura per l'uso sul web. Cautela: pickle non è intrinsecamente sicuro, quindi si faccia attenzione se viene chiesto di de-serializzare un file. Un file creato con pickle ha il suffisso `.pkl`.
|
||||||
|
|
||||||
|
## Esercizio: pulire i dati
|
||||||
|
|
||||||
|
In questa lezione verranno utilizzati i dati di 80.000 avvistamenti UFO, raccolti dal Centro Nazionale per gli Avvistamenti di UFO [NUFORC](https://nuforc.org) (The National UFO Reporting Center). Questi dati hanno alcune descrizioni interessanti di avvistamenti UFO, ad esempio:
|
||||||
|
|
||||||
|
- **Descrizione di esempio lunga**. "Un uomo emerge da un raggio di luce che di notte brilla su un campo erboso e corre verso il parcheggio della Texas Instruments".
|
||||||
|
- **Descrizione di esempio breve**. "le luci ci hanno inseguito".
|
||||||
|
|
||||||
|
Il foglio di calcolo [ufo.csv](../data/ufos.csv) include colonne su città (`city`), stato (`state`) e nazione (`country`) in cui è avvenuto l'avvistamento, la forma (`shape`) dell'oggetto e la sua latitudine (`latitude`) e longitudine (`longitude`).
|
||||||
|
|
||||||
|
Nel [notebook](../notebook.ipynb) vuoto incluso in questa lezione:
|
||||||
|
|
||||||
|
1. importare `pandas`, `matplotlib` e `numpy` come fatto nelle lezioni precedenti e importare il foglio di calcolo ufo.csv. Si può dare un'occhiata a un insieme di dati campione:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import pandas as pd
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
ufos = pd.read_csv('../data/ufos.csv')
|
||||||
|
ufos.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Convertire i dati ufos in un piccolo dataframe con nuove intestazioni Controllare i valori univoci nel campo `Country` .
|
||||||
|
|
||||||
|
```python
|
||||||
|
ufos = pd.DataFrame({'Seconds': ufos['duration (seconds)'], 'Country': ufos['country'],'Latitude': ufos['latitude'],'Longitude': ufos['longitude']})
|
||||||
|
|
||||||
|
ufos.Country.unique()
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Ora si può ridurre la quantità di dati da gestire eliminando qualsiasi valore nullo e importando solo avvistamenti tra 1-60 secondi:
|
||||||
|
|
||||||
|
```python
|
||||||
|
ufos.dropna(inplace=True)
|
||||||
|
|
||||||
|
ufos = ufos[(ufos['Seconds'] >= 1) & (ufos['Seconds'] <= 60)]
|
||||||
|
|
||||||
|
ufos.info()
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Importare la libreria `LabelEncoder` di Scikit-learn per convertire i valori di testo per le nazioni in un numero:
|
||||||
|
|
||||||
|
✅ LabelEncoder codifica i dati in ordine alfabetico
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.preprocessing import LabelEncoder
|
||||||
|
|
||||||
|
ufos['Country'] = LabelEncoder().fit_transform(ufos['Country'])
|
||||||
|
|
||||||
|
ufos.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
I dati dovrebbero assomigliare a questo:
|
||||||
|
|
||||||
|
```output
|
||||||
|
Seconds Country Latitude Longitude
|
||||||
|
2 20.0 3 53.200000 -2.916667
|
||||||
|
3 20.0 4 28.978333 -96.645833
|
||||||
|
14 30.0 4 35.823889 -80.253611
|
||||||
|
23 60.0 4 45.582778 -122.352222
|
||||||
|
24 3.0 3 51.783333 -0.783333
|
||||||
|
```
|
||||||
|
|
||||||
|
## Esercizio: costruire il proprio modello
|
||||||
|
|
||||||
|
Ora ci si può preparare per addestrare un modello portando i dati nei gruppi di addestramento e test.
|
||||||
|
|
||||||
|
1. Selezionare le tre caratteristiche su cui lo si vuole allenare come vettore X mentre il vettore y sarà `Country` Si deve essere in grado di inserire secondi (`Seconds`), latitudine (`Latitude`) e longitudine (`Longitude`) e ottenere un ID nazione da restituire.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.model_selection import train_test_split
|
||||||
|
|
||||||
|
Selected_features = ['Seconds','Latitude','Longitude']
|
||||||
|
|
||||||
|
X = ufos[Selected_features]
|
||||||
|
y = ufos['Country']
|
||||||
|
|
||||||
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Addestrare il modello usando la regressione logistica:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.metrics import accuracy_score, classification_report
|
||||||
|
from sklearn.linear_model import LogisticRegression
|
||||||
|
model = LogisticRegression()
|
||||||
|
model.fit(X_train, y_train)
|
||||||
|
predictions = model.predict(X_test)
|
||||||
|
|
||||||
|
print(classification_report(y_test, predictions))
|
||||||
|
print('Predicted labels: ', predictions)
|
||||||
|
print('Accuracy: ', accuracy_score(y_test, predictions))
|
||||||
|
```
|
||||||
|
|
||||||
|
La precisione non è male **(circa il 95%)**, non sorprende che `Country` e `Latitude/Longitude` siano correlati.
|
||||||
|
|
||||||
|
Il modello creato non è molto rivoluzionario in quanto si dovrebbe essere in grado di dedurre una nazione (`Country`) dalla sua latitudine e longitudine (`Latitude` e `Longitude`), ma è un buon esercizio provare ad allenare dai dati grezzi che sono stati puliti ed esportati, e quindi utilizzare questo modello in una app web.
|
||||||
|
|
||||||
|
## Esercizio: usare pickle con il modello
|
||||||
|
|
||||||
|
Ora è il momento di utilizzare _pickle_ con il modello! Lo si può fare in poche righe di codice. Una volta che è stato _serializzato con pickle_, caricare il modello e testarlo rispetto a un array di dati di esempio contenente valori per secondi, latitudine e longitudine,
|
||||||
|
|
||||||
|
```python
|
||||||
|
import pickle
|
||||||
|
model_filename = 'ufo-model.pkl'
|
||||||
|
pickle.dump(model, open(model_filename,'wb'))
|
||||||
|
|
||||||
|
model = pickle.load(open('ufo-model.pkl','rb'))
|
||||||
|
print(model.predict([[50,44,-12]]))
|
||||||
|
```
|
||||||
|
|
||||||
|
Il modello restituisce **"3"**, che è il codice nazione per il Regno Unito. Fantastico! 👽
|
||||||
|
|
||||||
|
## Esercizio: creare un'app Flask
|
||||||
|
|
||||||
|
Ora si può creare un'app Flask per chiamare il modello e restituire risultati simili, ma in un modo visivamente più gradevole.
|
||||||
|
|
||||||
|
1. Iniziare creando una cartella chiamata **web-app** a livello del file _notebook.ipynb_ dove risiede il file _ufo-model.pkl_.
|
||||||
|
|
||||||
|
1. In quella cartella creare altre tre cartelle: **static**, con una cartella **css** al suo interno e **templates**. Ora si dovrebbero avere i seguenti file e directory:
|
||||||
|
|
||||||
|
```output
|
||||||
|
web-app/
|
||||||
|
static/
|
||||||
|
css/
|
||||||
|
templates/
|
||||||
|
notebook.ipynb
|
||||||
|
ufo-model.pkl
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ Fare riferimento alla cartella della soluzione per una visualizzazione dell'app finita.
|
||||||
|
|
||||||
|
1. Il primo file da creare nella cartella _web-app_ è il file **requirements.txt**. Come _package.json_ in un'app JavaScript, questo file elenca le dipendenze richieste dall'app. In **requirements.txt** aggiungere le righe:
|
||||||
|
|
||||||
|
```text
|
||||||
|
scikit-learn
|
||||||
|
pandas
|
||||||
|
numpy
|
||||||
|
flask
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Ora, eseguire questo file portandosi su _web-app_:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd web-app
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Aprire una finestra di terminale dove risiede requirements.txt e digitare `pip install`, per installare le librerie elencate in _reuirements.txt_:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Ora si è pronti per creare altri tre file per completare l'app:
|
||||||
|
|
||||||
|
1. Creare **app.py** nella directory radice.
|
||||||
|
2. Creare **index.html** nella directory _templates_.
|
||||||
|
3. Creare **sytles.css** nella directory _static/css_.
|
||||||
|
|
||||||
|
1. Inserire nel file _styles.css_ alcuni stili:
|
||||||
|
|
||||||
|
```css
|
||||||
|
body {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
font-family: 'Helvetica';
|
||||||
|
background: black;
|
||||||
|
color: #fff;
|
||||||
|
text-align: center;
|
||||||
|
letter-spacing: 1.4px;
|
||||||
|
font-size: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
min-width: 150px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid {
|
||||||
|
width: 300px;
|
||||||
|
border: 1px solid #2d2d2d;
|
||||||
|
display: grid;
|
||||||
|
justify-content: center;
|
||||||
|
margin: 20px auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.box {
|
||||||
|
color: #fff;
|
||||||
|
background: #2d2d2d;
|
||||||
|
padding: 12px;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Quindi, creare il file _index.html_ :
|
||||||
|
|
||||||
|
```html
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>🛸 UFO Appearance Prediction! 👽</title>
|
||||||
|
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<div class="grid">
|
||||||
|
|
||||||
|
<div class="box">
|
||||||
|
|
||||||
|
<p>According to the number of seconds, latitude and longitude, which country is likely to have reported seeing a UFO?</p>
|
||||||
|
|
||||||
|
<form action="{{ url_for('predict')}}" method="post">
|
||||||
|
<input type="number" name="seconds" placeholder="Seconds" required="required" min="0" max="60" />
|
||||||
|
<input type="text" name="latitude" placeholder="Latitude" required="required" />
|
||||||
|
<input type="text" name="longitude" placeholder="Longitude" required="required" />
|
||||||
|
<button type="submit" class="btn">Predict country where the UFO is seen</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
|
||||||
|
<p>{{ prediction_text }}</p>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
```
|
||||||
|
|
||||||
|
Dare un'occhiata al template di questo file. Notare la sintassi con le parentesi graffe attorno alle variabili che verranno fornite dall'app, come il testo di previsione: `{{}}`. C'è anche un modulo che invia una previsione alla rotta `/predict`.
|
||||||
|
|
||||||
|
Infine, si è pronti per creare il file python che guida il consumo del modello e la visualizzazione delle previsioni:
|
||||||
|
|
||||||
|
1. In `app.py` aggiungere:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import numpy as np
|
||||||
|
from flask import Flask, request, render_template
|
||||||
|
import pickle
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
model = pickle.load(open("../ufo-model.pkl", "rb"))
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/")
|
||||||
|
def home():
|
||||||
|
return render_template("index.html")
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/predict", methods=["POST"])
|
||||||
|
def predict():
|
||||||
|
|
||||||
|
int_features = [int(x) for x in request.form.values()]
|
||||||
|
final_features = [np.array(int_features)]
|
||||||
|
prediction = model.predict(final_features)
|
||||||
|
|
||||||
|
output = prediction[0]
|
||||||
|
|
||||||
|
countries = ["Australia", "Canada", "Germany", "UK", "US"]
|
||||||
|
|
||||||
|
return render_template(
|
||||||
|
"index.html", prediction_text="Likely country: {}".format(countries[output])
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run(debug=True)
|
||||||
|
```
|
||||||
|
|
||||||
|
> 💡 Suggerimento: quando si aggiunge [`debug=True`](https://www.askpython.com/python-modules/flask/flask-debug-mode) durante l'esecuzione dell'app web utilizzando Flask, qualsiasi modifica apportata all'applicazione verrà recepita immediatamente senza la necessità di riavviare il server. Attenzione! Non abilitare questa modalità in un'app di produzione.
|
||||||
|
|
||||||
|
Se si esegue `python app.py` o `python3 app.py` , il server web si avvia, localmente, e si può compilare un breve modulo per ottenere una risposta alla domanda scottante su dove sono stati avvistati gli UFO!
|
||||||
|
|
||||||
|
Prima di farlo, dare un'occhiata alle parti di `app.py`:
|
||||||
|
|
||||||
|
1. Innanzitutto, le dipendenze vengono caricate e l'app si avvia.
|
||||||
|
1. Poi il modello viene importato.
|
||||||
|
1. Infine index.html viene visualizzato sulla rotta home.
|
||||||
|
|
||||||
|
Sulla rotta `/predict` , accadono diverse cose quando il modulo viene inviato:
|
||||||
|
|
||||||
|
1. Le variabili del modulo vengono raccolte e convertite in un array numpy. Vengono quindi inviate al modello e viene restituita una previsione.
|
||||||
|
2. Le nazioni che si vogliono visualizzare vengono nuovamente esposte come testo leggibile ricavato dal loro codice paese previsto e tale valore viene inviato a index.html per essere visualizzato nel template della pagina web.
|
||||||
|
|
||||||
|
Usare un modello in questo modo, con Flask e un modello serializzato è relativamente semplice. La cosa più difficile è capire che forma hanno i dati che devono essere inviati al modello per ottenere una previsione. Tutto dipende da come è stato addestrato il modello. Questo ha tre punti dati da inserire per ottenere una previsione.
|
||||||
|
|
||||||
|
In un ambiente professionale, si può vedere quanto sia necessaria una buona comunicazione tra le persone che addestrano il modello e coloro che lo consumano in un'app web o su dispositivo mobile. In questo caso, si ricoprono entrambi i ruoli!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Sfida
|
||||||
|
|
||||||
|
Invece di lavorare su un notebook e importare il modello nell'app Flask, si può addestrare il modello direttamente nell'app Flask! Provare a convertire il codice Python nel notebook, magari dopo che i dati sono stati puliti, per addestrare il modello dall'interno dell'app su un percorso chiamato `/train`. Quali sono i pro e i contro nel seguire questo metodo?
|
||||||
|
|
||||||
|
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/18/)
|
||||||
|
|
||||||
|
## Revisione e Auto Apprendimento
|
||||||
|
|
||||||
|
Esistono molti modi per creare un'app web per utilizzare i modelli ML. Elencare dei modi in cui si potrebbe utilizzare JavaScript o Python per creare un'app web per sfruttare machine learning. Considerare l'architettura: il modello dovrebbe rimanere nell'app o risiedere nel cloud? In quest'ultimo casi, come accedervi? Disegnare un modello architettonico per una soluzione web ML applicata.
|
||||||
|
|
||||||
|
## Compito
|
||||||
|
|
||||||
|
[Provare un modello diverso](assignment.it.md)
|
||||||
|
|
||||||
|
|
@ -0,0 +1,11 @@
|
|||||||
|
# Provare un modello diverso
|
||||||
|
|
||||||
|
## Istruzioni
|
||||||
|
|
||||||
|
Ora che si è creato un'app web utilizzando un modello di Regressione addestrato, usare uno dei modelli da una lezione precedente sulla Regressione per rifare questa app web. Si può mantenere lo stile o progettarla in modo diverso per riflettere i dati della zucca. Fare attenzione a modificare gli input in modo che riflettano il metodo di addestramento del proprio modello.
|
||||||
|
|
||||||
|
## Rubrica
|
||||||
|
|
||||||
|
| Criteri | Ottimo | Adeguato | Necessita miglioramento |
|
||||||
|
| -------------------------- | --------------------------------------------------------- | --------------------------------------------------------- | -------------------------------------- |
|
||||||
|
| | L'app web funziona come previsto e viene distribuita nel cloud | L'app web contiene difetti o mostra risultati imprevisti | L'app web non funziona correttamente |
|
@ -0,0 +1,22 @@
|
|||||||
|
# Creare un'app web per utilizzare il modello ML
|
||||||
|
|
||||||
|
In questa sezione del programma di studi, verrà presentato un argomento ML applicato: come salvare il modello di Scikit-learn come file che può essere utilizzato per fare previsioni all'interno di un'applicazione web. Una volta salvato il modello, si imparerà come utilizzarlo in un'app web sviluppata con Flask. Per prima cosa si creerà un modello utilizzando alcuni dati che riguardano gli avvistamenti di UFO! Quindi, si creerà un'app web che consentirà di inserire un numero di secondi con un valore di latitudine e longitudine per prevedere quale paese ha riferito di aver visto un UFO.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Foto di <a href="https://unsplash.com/@mdherren?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Michael Herren</a> su <a href="https://unsplash.com/s/photos/ufo?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
|
||||||
|
|
||||||
|
|
||||||
|
## Lezioni
|
||||||
|
|
||||||
|
1. [Costruire un'app web](../1-Web-App/translations/README.it.md)
|
||||||
|
|
||||||
|
## Crediti
|
||||||
|
|
||||||
|
"Costruire un'app web" è stato scritto con ♥️ da [Jen Looper](https://twitter.com/jenlooper).
|
||||||
|
|
||||||
|
♥️ I quiz sono stati scritti da Rohan Raj.
|
||||||
|
|
||||||
|
L'insieme di dati proviene da [Kaggle](https://www.kaggle.com/NUFORC/ufo-sightings).
|
||||||
|
|
||||||
|
L'architettura dell'app web è stata suggerita in parte da [questo articolo](https://towardsdatascience.com/how-to-easily-deploy-machine-learning-models-using-flask-b95af8fe34d4) e da [questo](https://github.com/abhinavsagar/machine-learning-deployment) repository di Abhinav Sagar.
|
@ -0,0 +1,297 @@
|
|||||||
|
# Introduzione alla classificazione
|
||||||
|
|
||||||
|
In queste quattro lezioni si esplorerà un focus fondamentale del machine learning classico: _la classificazione_. Verrà analizzato l'utilizzo di vari algoritmi di classificazione con un insieme di dati su tutte le brillanti cucine dell'Asia e dell'India. Si spera siate affamati!
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> In queste lezioni di celebrano le cucine panasiatiche! Immagine di [Jen Looper](https://twitter.com/jenlooper)
|
||||||
|
|
||||||
|
La classificazione è una forma di [apprendimento supervisionato](https://it.wikipedia.org/wiki/Apprendimento_supervisionato) che ha molto in comune con le tecniche di regressione. Se machine learning riguarda la previsione di valori o nomi di cose utilizzando insiemi di dati, la classificazione generalmente rientra in due gruppi: _classificazione binaria_ e _classificazione multiclasse_.
|
||||||
|
|
||||||
|
[](https://youtu.be/eg8DJYwdMyg "Introduzione alla classificazione")
|
||||||
|
|
||||||
|
> 🎥 Fare clic sull'immagine sopra per un video: John Guttag del MIT introduce la classificazione
|
||||||
|
|
||||||
|
Ricordare:
|
||||||
|
|
||||||
|
- La **regressione lineare** ha aiutato a prevedere le relazioni tra le variabili e a fare previsioni accurate su dove un nuovo punto dati si sarebbe posizionato in relazione a quella linea. Quindi, si potrebbe prevedere _quale prezzo avrebbe una zucca a settembre rispetto a dicembre_, ad esempio.
|
||||||
|
- La **regressione logistica** ha aiutato a scoprire le "categorie binarie": a questo prezzo, _questa zucca è arancione o non arancione_?
|
||||||
|
|
||||||
|
La classificazione utilizza vari algoritmi per determinare altri modi per definire l'etichetta o la classe di un punto dati. Si lavorerà con questi dati di cucina per vedere se, osservando un gruppo di ingredienti, è possibile determinarne la cucina di origine.
|
||||||
|
|
||||||
|
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/19/)
|
||||||
|
|
||||||
|
### Introduzione
|
||||||
|
|
||||||
|
La classificazione è una delle attività fondamentali del ricercatore di machine learning e data scientist. Dalla classificazione basica di un valore binario ("questa email è spam o no?"), alla complessa classificazione e segmentazione di immagini utilizzando la visione artificiale, è sempre utile essere in grado di ordinare i dati in classi e porre domande su di essi.
|
||||||
|
|
||||||
|
Per definire il processo in modo più scientifico, il metodo di classificazione crea un modello predittivo che consente di mappare la relazione tra le variabili di input e le variabili di output.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
> Problemi binari e multiclasse per la gestione di algoritmi di classificazione. Infografica di [Jen Looper](https://twitter.com/jenlooper)
|
||||||
|
|
||||||
|
Prima di iniziare il processo di pulizia dei dati, visualizzazione e preparazione per le attività di machine learning, si apprenderà qualcosa circa i vari modi in cui machine learning può essere sfruttato per classificare i dati.
|
||||||
|
|
||||||
|
Derivata dalla [statistica](https://it.wikipedia.org/wiki/Classificazione_statistica), la classificazione che utilizza machine learning classico utilizza caratteristiche come l'`essere fumatore`, il `peso` e l'`età` per determinare _la probabilità di sviluppare la malattia X._ Essendo una tecnica di apprendimento supervisionata simile agli esercizi di regressione eseguiti in precedenza, i dati vengono etichettati e gli algoritmi ML utilizzano tali etichette per classificare e prevedere le classi (o "caratteristiche") di un insieme di dati e assegnarle a un gruppo o risultato.
|
||||||
|
|
||||||
|
✅ Si prenda un momento per immaginare un insieme di dati sulle cucine. A cosa potrebbe rispondere un modello multiclasse? A cosa potrebbe rispondere un modello binario? Se si volesse determinare se una determinata cucina potrebbe utilizzare il fieno greco? Se si volesse vedere se, regalando una busta della spesa piena di anice stellato, carciofi, cavolfiori e rafano, si possa creare un piatto tipico indiano?
|
||||||
|
|
||||||
|
[](https://youtu.be/GuTeDbaNoEU " Cestini misteriosi pazzeschi")
|
||||||
|
|
||||||
|
> 🎥 Fare clic sull'immagine sopra per un video. L'intera premessa dello spettacolo 'Chopped' è il 'cesto misterioso' dove gli chef devono preparare un piatto con una scelta casuale di ingredienti. Sicuramente un modello ML avrebbe aiutato!
|
||||||
|
|
||||||
|
## Ciao 'classificatore'
|
||||||
|
|
||||||
|
La domanda che si vuole porre a questo insieme di dati sulla cucina è in realtà una **domanda multiclasse**, poiché ci sono diverse potenziali cucine nazionali con cui lavorare. Dato un lotto di ingredienti, in quale di queste molte classi si identificheranno i dati?
|
||||||
|
|
||||||
|
Scikit-learn offre diversi algoritmi da utilizzare per classificare i dati, a seconda del tipo di problema che si desidera risolvere. Nelle prossime due lezioni si impareranno a conoscere molti di questi algoritmi.
|
||||||
|
|
||||||
|
## Esercizio: pulire e bilanciare i dati
|
||||||
|
|
||||||
|
Il primo compito, prima di iniziare questo progetto, sarà pulire e **bilanciare** i dati per ottenere risultati migliori. Si inizia con il file vuoto _notebook.ipynb_ nella radice di questa cartella.
|
||||||
|
|
||||||
|
La prima cosa da installare è [imblearn](https://imbalanced-learn.org/stable/). Questo è un pacchetto di apprendimento di Scikit che consentirà di bilanciare meglio i dati (si imparerà di più su questa attività tra un minuto).
|
||||||
|
|
||||||
|
1. Per installare `imblearn`, eseguire `pip install`, in questo modo:
|
||||||
|
|
||||||
|
```python
|
||||||
|
pip install imblearn
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Importare i pacchetti necessari per caricare i dati e visualizzarli, importare anche `SMOTE` da `imblearn`.
|
||||||
|
|
||||||
|
```python
|
||||||
|
import pandas as pd
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import matplotlib as mpl
|
||||||
|
import numpy as np
|
||||||
|
from imblearn.over_sampling import SMOTE
|
||||||
|
```
|
||||||
|
|
||||||
|
Ora si è pronti per la successiva importazione dei dati.
|
||||||
|
|
||||||
|
1. Il prossimo compito sarà quello di importare i dati:
|
||||||
|
|
||||||
|
```python
|
||||||
|
df = pd.read_csv('../data/cuisines.csv')
|
||||||
|
```
|
||||||
|
|
||||||
|
Usando `read_csv()` si leggerà il contenuto del file csv _cusines.csv_ e lo posizionerà nella variabile `df`.
|
||||||
|
|
||||||
|
1. Controllare la forma dei dati:
|
||||||
|
|
||||||
|
```python
|
||||||
|
df.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
Le prime cinque righe hanno questo aspetto:
|
||||||
|
|
||||||
|
```output
|
||||||
|
| | Unnamed: 0 | cuisine | almond | angelica | anise | anise_seed | apple | apple_brandy | apricot | armagnac | ... | whiskey | white_bread | white_wine | whole_grain_wheat_flour | wine | wood | yam | yeast | yogurt | zucchini |
|
||||||
|
| --- | ---------- | ------- | ------ | -------- | ----- | ---------- | ----- | ------------ | ------- | -------- | --- | ------- | ----------- | ---------- | ----------------------- | ---- | ---- | --- | ----- | ------ | -------- |
|
||||||
|
| 0 | 65 | indian | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 1 | 66 | indian | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 2 | 67 | indian | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 3 | 68 | indian | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 4 | 69 | indian | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Si possono ottienere informazioni su questi dati chiamando `info()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
df.info()
|
||||||
|
```
|
||||||
|
|
||||||
|
Il risultato assomiglia a:
|
||||||
|
|
||||||
|
```output
|
||||||
|
<class 'pandas.core.frame.DataFrame'>
|
||||||
|
RangeIndex: 2448 entries, 0 to 2447
|
||||||
|
Columns: 385 entries, Unnamed: 0 to zucchini
|
||||||
|
dtypes: int64(384), object(1)
|
||||||
|
memory usage: 7.2+ MB
|
||||||
|
```
|
||||||
|
|
||||||
|
## Esercizio - conoscere le cucine
|
||||||
|
|
||||||
|
Ora il lavoro inizia a diventare più interessante. Si scoprirà la distribuzione dei dati, per cucina
|
||||||
|
|
||||||
|
1. Tracciare i dati come barre chiamando `barh()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
df.cuisine.value_counts().plot.barh()
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Esiste un numero finito di cucine, ma la distribuzione dei dati non è uniforme. Si può sistemare! Prima di farlo, occorre esplorare un po' di più.
|
||||||
|
|
||||||
|
1. Si deve scoprire quanti dati sono disponibili per cucina e stamparli:
|
||||||
|
|
||||||
|
```python
|
||||||
|
thai_df = df[(df.cuisine == "thai")]
|
||||||
|
japanese_df = df[(df.cuisine == "japanese")]
|
||||||
|
chinese_df = df[(df.cuisine == "chinese")]
|
||||||
|
indian_df = df[(df.cuisine == "indian")]
|
||||||
|
korean_df = df[(df.cuisine == "korean")]
|
||||||
|
|
||||||
|
print(f'thai df: {thai_df.shape}')
|
||||||
|
print(f'japanese df: {japanese_df.shape}')
|
||||||
|
print(f'chinese df: {chinese_df.shape}')
|
||||||
|
print(f'indian df: {indian_df.shape}')
|
||||||
|
print(f'korean df: {korean_df.shape}')
|
||||||
|
```
|
||||||
|
|
||||||
|
il risultato si presenta così:
|
||||||
|
|
||||||
|
```output
|
||||||
|
thai df: (289, 385)
|
||||||
|
japanese df: (320, 385)
|
||||||
|
chinese df: (442, 385)
|
||||||
|
indian df: (598, 385)
|
||||||
|
korean df: (799, 385)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Alla scoperta degli ingredienti
|
||||||
|
|
||||||
|
Ora si possono approfondire i dati e scoprire quali sono gli ingredienti tipici per cucina. Si dovrebbero ripulire i dati ricorrenti che creano confusione tra le cucine, quindi si affronterà questo problema.
|
||||||
|
|
||||||
|
1. Creare una funzione `create_ingredient()` in Python per creare un dataframe ingredient Questa funzione inizierà eliminando una colonna non utile e ordinando gli ingredienti in base al loro conteggio:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def create_ingredient_df(df):
|
||||||
|
ingredient_df = df.T.drop(['cuisine','Unnamed: 0']).sum(axis=1).to_frame('value')
|
||||||
|
ingredient_df = ingredient_df[(ingredient_df.T != 0).any()]
|
||||||
|
ingredient_df = ingredient_df.sort_values(by='value', ascending=False
|
||||||
|
inplace=False)
|
||||||
|
return ingredient_df
|
||||||
|
```
|
||||||
|
|
||||||
|
Ora si può usare questa funzione per farsi un'idea dei primi dieci ingredienti più popolari per cucina.
|
||||||
|
|
||||||
|
1. Chiamare `create_ingredient_df()` e tracciare il grafico chiamando `barh()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
thai_ingredient_df = create_ingredient_df(thai_df)
|
||||||
|
thai_ingredient_df.head(10).plot.barh()
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
1. Fare lo stesso per i dati giapponesi:
|
||||||
|
|
||||||
|
```python
|
||||||
|
japanese_ingredient_df = create_ingredient_df(japanese_df)
|
||||||
|
japanese_ingredient_df.head(10).plot.barh()
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
1. Ora per gli ingredienti cinesi:
|
||||||
|
|
||||||
|
```python
|
||||||
|
chinese_ingredient_df = create_ingredient_df(chinese_df)
|
||||||
|
chinese_ingredient_df.head(10).plot.barh()
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
1. Tracciare gli ingredienti indiani:
|
||||||
|
|
||||||
|
```python
|
||||||
|
indian_ingredient_df = create_ingredient_df(indian_df)
|
||||||
|
indian_ingredient_df.head(10).plot.barh()
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
1. Infine, tracciare gli ingredienti coreani:
|
||||||
|
|
||||||
|
```python
|
||||||
|
korean_ingredient_df = create_ingredient_df(korean_df)
|
||||||
|
korean_ingredient_df.head(10).plot.barh()
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
1. Ora, eliminare gli ingredienti più comuni che creano confusione tra le diverse cucine, chiamando `drop()`:
|
||||||
|
|
||||||
|
Tutti amano il riso, l'aglio e lo zenzero!
|
||||||
|
|
||||||
|
```python
|
||||||
|
feature_df= df.drop(['cuisine','Unnamed: 0','rice','garlic','ginger'], axis=1)
|
||||||
|
labels_df = df.cuisine #.unique()
|
||||||
|
feature_df.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bilanciare l'insieme di dati
|
||||||
|
|
||||||
|
Ora che i dati sono puliti, si usa [SMOTE](https://imbalanced-learn.org/dev/references/generated/imblearn.over_sampling.SMOTE.html) - "Tecnica di sovracampionamento della minoranza sintetica" - per bilanciarlo.
|
||||||
|
|
||||||
|
1. Chiamare `fit_resample()`, questa strategia genera nuovi campioni per interpolazione.
|
||||||
|
|
||||||
|
```python
|
||||||
|
oversample = SMOTE()
|
||||||
|
transformed_feature_df, transformed_label_df = oversample.fit_resample(feature_df, labels_df)
|
||||||
|
```
|
||||||
|
|
||||||
|
Bilanciando i dati, si otterranno risultati migliori quando si classificano. Si pensi a una classificazione binaria. Se la maggior parte dei dati è una classe, un modello ML prevederà quella classe più frequentemente, solo perché ci sono più dati per essa. Il bilanciamento dei dati prende tutti i dati distorti e aiuta a rimuovere questo squilibrio.
|
||||||
|
|
||||||
|
1. Ora si può controllare il numero di etichette per ingrediente:
|
||||||
|
|
||||||
|
```python
|
||||||
|
print(f'new label count: {transformed_label_df.value_counts()}')
|
||||||
|
print(f'old label count: {df.cuisine.value_counts()}')
|
||||||
|
```
|
||||||
|
|
||||||
|
il risultato si presenta così:
|
||||||
|
|
||||||
|
```output
|
||||||
|
new label count: korean 799
|
||||||
|
chinese 799
|
||||||
|
indian 799
|
||||||
|
japanese 799
|
||||||
|
thai 799
|
||||||
|
Name: cuisine, dtype: int64
|
||||||
|
old label count: korean 799
|
||||||
|
indian 598
|
||||||
|
chinese 442
|
||||||
|
japanese 320
|
||||||
|
thai 289
|
||||||
|
Name: cuisine, dtype: int64
|
||||||
|
```
|
||||||
|
|
||||||
|
I dati sono belli e puliti, equilibrati e molto deliziosi!
|
||||||
|
|
||||||
|
1. L'ultimo passaggio consiste nel salvare i dati bilanciati, incluse etichette e caratteristiche, in un nuovo dataframe che può essere esportato in un file:
|
||||||
|
|
||||||
|
```python
|
||||||
|
transformed_df = pd.concat([transformed_label_df,transformed_feature_df],axis=1, join='outer')
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Si può dare un'altra occhiata ai dati usando `transform_df.head()` e `transform_df.info()`. Salvare una copia di questi dati per utilizzarli nelle lezioni future:
|
||||||
|
|
||||||
|
```python
|
||||||
|
transformed_df.head()
|
||||||
|
transformed_df.info()
|
||||||
|
transformed_df.to_csv("../data/cleaned_cuisine.csv")
|
||||||
|
```
|
||||||
|
|
||||||
|
Questo nuovo CSV può ora essere trovato nella cartella data in radice.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 Sfida
|
||||||
|
|
||||||
|
Questo programma di studi contiene diversi insiemi di dati interessanti. Esaminare le cartelle `data` e vedere se contiene insiemi di dati che sarebbero appropriati per la classificazione binaria o multiclasse. Quali domande si farebbero a questo insieme di dati?
|
||||||
|
|
||||||
|
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/20/)
|
||||||
|
|
||||||
|
## Revisione e Auto Apprendimento
|
||||||
|
|
||||||
|
Esplorare l'API di SMOTE. Per quali casi d'uso è meglio usarla? Quali problemi risolve?
|
||||||
|
|
||||||
|
## Compito
|
||||||
|
|
||||||
|
[Esplorare i metodi di classificazione](assignment.it.md)
|
@ -0,0 +1,11 @@
|
|||||||
|
# Esplorare i metodi di classificazione
|
||||||
|
|
||||||
|
## Istruzioni
|
||||||
|
|
||||||
|
Nella [documentazione](https://scikit-learn.org/stable/supervised_learning.html) di Scikit-learn si troverà un ampio elenco di modi per classificare i dati. Fare una piccola caccia al tesoro in questi documenti: l'obiettivo è cercare metodi di classificazione e abbinare un insieme di dati in questo programma di studi, una domanda che si può porre e una tecnica di classificazione. Creare un foglio di calcolo o una tabella in un file .doc e spiegare come funzionerebbe l'insieme di dati con l'algoritmo di classificazione.
|
||||||
|
|
||||||
|
## Rubrica
|
||||||
|
|
||||||
|
| Criteri | Ottimo | Adeguato | Necessita miglioramento |
|
||||||
|
| -------- | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| | viene presentato un documento che riporta una panoramica di 5 algoritmi insieme a una tecnica di classificazione. La panoramica è ben spiegata e dettagliata. | viene presentato un documento che riporta una panoramica di 3 algoritmi insieme a una tecnica di classificazione. La panoramica è ben spiegata e dettagliata. | viene presentato un documento che riporta una panoramica di meno di tre algoritmi insieme a una tecnica di classificazione e la panoramica non è né ben spiegata né dettagliata. |
|
@ -0,0 +1,241 @@
|
|||||||
|
# Classificatori di cucina 1
|
||||||
|
|
||||||
|
In questa lezione, si utilizzerà l'insieme di dati salvati dall'ultima lezione, pieno di dati equilibrati e puliti relativi alle cucine.
|
||||||
|
|
||||||
|
Si utilizzerà questo insieme di dati con una varietà di classificatori per _prevedere una determinata cucina nazionale in base a un gruppo di ingredienti_. Mentre si fa questo, si imparerà di più su alcuni dei modi in cui gli algoritmi possono essere sfruttati per le attività di classificazione.
|
||||||
|
|
||||||
|
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/21/)
|
||||||
|
# Preparazione
|
||||||
|
|
||||||
|
Supponendo che la [Lezione 1](../1-Introduction/README.md) sia stata completata, assicurarsi che _esista_ un file clean_cuisines.csv nella cartella in radice `/data` per queste quattro lezioni.
|
||||||
|
|
||||||
|
## Esercizio - prevedere una cucina nazionale
|
||||||
|
|
||||||
|
1. Lavorando con il _notebook.ipynb_ di questa lezione nella cartella radice, importare quel file insieme alla libreria Pandas:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import pandas as pd
|
||||||
|
cuisines_df = pd.read_csv("../../data/cleaned_cuisine.csv")
|
||||||
|
cuisines_df.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
I dati si presentano così:
|
||||||
|
|
||||||
|
```output
|
||||||
|
| | Unnamed: 0 | cuisine | almond | angelica | anise | anise_seed | apple | apple_brandy | apricot | armagnac | ... | whiskey | white_bread | white_wine | whole_grain_wheat_flour | wine | wood | yam | yeast | yogurt | zucchini |
|
||||||
|
| --- | ---------- | ------- | ------ | -------- | ----- | ---------- | ----- | ------------ | ------- | -------- | --- | ------- | ----------- | ---------- | ----------------------- | ---- | ---- | --- | ----- | ------ | -------- |
|
||||||
|
| 0 | 0 | indian | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 1 | 1 | indian | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 2 | 2 | indian | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 3 | 3 | indian | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 4 | 4 | indian | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Ora importare molte altre librerie:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sklearn.linear_model import LogisticRegression
|
||||||
|
from sklearn.model_selection import train_test_split, cross_val_score
|
||||||
|
from sklearn.metrics import accuracy_score,precision_score,confusion_matrix,classification_report, precision_recall_curve
|
||||||
|
from sklearn.svm import SVC
|
||||||
|
import numpy as np
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Dividere le coordinate X e y in due dataframe per l'addestramento. `cuisine` può essere il dataframe delle etichette:
|
||||||
|
|
||||||
|
```python
|
||||||
|
cuisines_label_df = cuisines_df['cuisine']
|
||||||
|
cuisines_label_df.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
Apparirà così
|
||||||
|
|
||||||
|
```output
|
||||||
|
0 indian
|
||||||
|
1 indian
|
||||||
|
2 indian
|
||||||
|
3 indian
|
||||||
|
4 indian
|
||||||
|
Name: cuisine, dtype: object
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Scartare la colonna `Unnamed: 0` e la colonna `cuisine` , chiamando `drop()`. Salvare il resto dei dati come caratteristiche addestrabili:
|
||||||
|
|
||||||
|
```python
|
||||||
|
cuisines_feature_df = cuisines_df.drop(['Unnamed: 0', 'cuisine'], axis=1)
|
||||||
|
cuisines_feature_df.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
Le caratteristiche sono così:
|
||||||
|
|
||||||
|
| almond | angelica | anise | anise_seed | apple | apple_brandy | apricot | armagnac | artemisia | artichoke | ... | whiskey | white_bread | white_wine | whole_grain_wheat_flour | wine | wood | yam | yeast | yogurt | zucchini | |
|
||||||
|
| -----: | -------: | ----: | ---------: | ----: | -----------: | ------: | -------: | --------: | --------: | ---: | ------: | ----------: | ---------: | ----------------------: | ---: | ---: | ---: | ----: | -----: | -------: | --- |
|
||||||
|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||||
|
| 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | ... | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |
|
||||||
|
|
||||||
|
Ora si è pronti per addestrare il modello!
|
||||||
|
|
||||||
|
## Scegliere il classificatore
|
||||||
|
|
||||||
|
Ora che i dati sono puliti e pronti per l'addestramento, si deve decidere quale algoritmo utilizzare per il lavoro.
|
||||||
|
|
||||||
|
Scikit-learn raggruppa la classificazione in Supervised Learning, e in quella categoria si troveranno molti modi per classificare. [La varietà](https://scikit-learn.org/stable/supervised_learning.html) è piuttosto sconcertante a prima vista. I seguenti metodi includono tutti tecniche di classificazione:
|
||||||
|
|
||||||
|
- Modelli Lineari
|
||||||
|
- Macchine a Vettori di Supporto
|
||||||
|
- Discesa stocastica del gradiente
|
||||||
|
- Nearest Neighbors
|
||||||
|
- Processi Gaussiani
|
||||||
|
- Alberi di Decisione
|
||||||
|
- Apprendimento ensemble (classificatore di voto)
|
||||||
|
- Algoritmi multiclasse e multioutput (classificazione multiclasse e multietichetta, classificazione multiclasse-multioutput)
|
||||||
|
|
||||||
|
> Si possono anche usare [le reti neurali per classificare i dati](https://scikit-learn.org/stable/modules/neural_networks_supervised.html#classification), ma questo esula dall'ambito di questa lezione.
|
||||||
|
|
||||||
|
### Con quale classificatore andare?
|
||||||
|
|
||||||
|
Quale classificatore si dovrebbe scegliere? Spesso, scorrerne diversi e cercare un buon risultato è un modo per testare. Scikit-learn offre un [confronto fianco](https://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html) a fianco su un insieme di dati creato, confrontando KNeighbors, SVC in due modi, GaussianProcessClassifier, DecisionTreeClassifier, RandomForestClassifier, MLPClassifier, AdaBoostClassifier, GaussianNB e QuadraticDiscrinationAnalysis, mostrando i risultati visualizzati:
|
||||||
|
|
||||||
|

|
||||||
|
> Grafici generati sulla documentazione di Scikit-learn
|
||||||
|
|
||||||
|
> AutoML risolve questo problema in modo ordinato eseguendo questi confronti nel cloud, consentendo di scegliere l'algoritmo migliore per i propri dati. Si può provare [qui](https://docs.microsoft.com/learn/modules/automate-model-selection-with-azure-automl/?WT.mc_id=academic-15963-cxa)
|
||||||
|
|
||||||
|
### Un approccio migliore
|
||||||
|
|
||||||
|
Un modo migliore che indovinare a caso, tuttavia, è seguire le idee su questo [ML Cheat sheet](https://docs.microsoft.com/azure/machine-learning/algorithm-cheat-sheet?WT.mc_id=academic-15963-cxa) scaricabile. Qui si scopre che, per questo problema multiclasse, si dispone di alcune scelte:
|
||||||
|
|
||||||
|

|
||||||
|
> Una sezione dell'Algorithm Cheat Sheet di Microsoft, che descrive in dettaglio le opzioni di classificazione multiclasse
|
||||||
|
|
||||||
|
✅ Scaricare questo cheat sheet, stamparlo e appenderlo alla parete!
|
||||||
|
|
||||||
|
### Motivazione
|
||||||
|
|
||||||
|
Si prova a ragionare attraverso diversi approcci dati i vincoli presenti:
|
||||||
|
|
||||||
|
- **Le reti neurali sono troppo pesanti**. Dato l'insieme di dati pulito, ma minimo, e il fatto che si sta eseguendo l'addestramento localmente tramite notebook, le reti neurali sono troppo pesanti per questo compito.
|
||||||
|
- **Nessun classificatore a due classi**. Non si usa un classificatore a due classi, quindi questo esclude uno contro tutti.
|
||||||
|
- L'**albero decisionale o la regressione logistica potrebbero funzionare**. Potrebbe funzionare un albero decisionale o una regressione logistica per dati multiclasse.
|
||||||
|
- **Gli alberi decisionali potenziati multiclasse risolvono un problema diverso**. L'albero decisionale potenziato multiclasse è più adatto per attività non parametriche, ad esempio attività progettate per costruire classifiche, quindi non è utile in questo caso.
|
||||||
|
|
||||||
|
### Utilizzo di Scikit-learn
|
||||||
|
|
||||||
|
Si userà Scikit-learn per analizzare i dati. Tuttavia, ci sono molti modi per utilizzare la regressione logistica in Scikit-learn. Dare un'occhiata ai [parametri da passare](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html?highlight=logistic%20regressio#sklearn.linear_model.LogisticRegression).
|
||||||
|
|
||||||
|
Essenzialmente ci sono due importanti parametri `multi_class` e `solver`, che occorre specificare, quando si chiede a Scikit-learn di eseguire una regressione logistica. Il valore `multi_class` si applica un certo comportamento. Il valore del risolutore è quale algoritmo utilizzare. Non tutti i risolutori possono essere associati a tutti i valori `multi_class` .
|
||||||
|
|
||||||
|
Secondo la documentazione, nel caso multiclasse, l'algoritmo di addestramento:
|
||||||
|
|
||||||
|
- **Utilizza lo schema one-vs-rest (OvR)** - uno contro tutti, se l'opzione `multi_class` è impostata su `ovr`
|
||||||
|
- **Utilizza la perdita di entropia incrociata**, se l 'opzione `multi_class` è impostata su `multinomial`. (Attualmente l'opzione multinomiale è supportata solo dai solutori 'lbfgs', 'sag', 'saga' e 'newton-cg')."
|
||||||
|
|
||||||
|
> 🎓 Lo 'schema' qui può essere 'ovr' (one-vs-rest) - uno contro tutti - o 'multinomiale'. Poiché la regressione logistica è realmente progettata per supportare la classificazione binaria, questi schemi consentono di gestire meglio le attività di classificazione multiclasse. [fonte](https://machinelearningmastery.com/one-vs-rest-and-one-vs-one-for-multi-class-classification/)
|
||||||
|
|
||||||
|
> 🎓 Il 'solver' è definito come "l'algoritmo da utilizzare nel problema di ottimizzazione". [fonte](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html?highlight=logistic%20regressio#sklearn.linear_model.LogisticRegression).
|
||||||
|
|
||||||
|
Scikit-learn offre questa tabella per spiegare come i risolutori gestiscono le diverse sfide presentate da diversi tipi di strutture dati:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Esercizio: dividere i dati
|
||||||
|
|
||||||
|
Ci si può concentrare sulla regressione logistica per la prima prova di addestramento poiché di recente si è appreso di quest'ultima in una lezione precedente.
|
||||||
|
Dividere i dati in gruppi di addestramento e test chiamando `train_test_split()`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
X_train, X_test, y_train, y_test = train_test_split(cuisines_feature_df, cuisines_label_df, test_size=0.3)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Esercizio: applicare la regressione logistica
|
||||||
|
|
||||||
|
Poiché si sta utilizzando il caso multiclasse, si deve scegliere quale _schema_ utilizzare e quale _solutore_ impostare. Usare LogisticRegression con un'impostazione multiclasse e il solutore **liblinear** da addestrare.
|
||||||
|
|
||||||
|
1. Creare una regressione logistica con multi_class impostato su `ovr` e il risolutore impostato su `liblinear`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
lr = LogisticRegression(multi_class='ovr',solver='liblinear')
|
||||||
|
model = lr.fit(X_train, np.ravel(y_train))
|
||||||
|
|
||||||
|
accuracy = model.score(X_test, y_test)
|
||||||
|
print ("Accuracy is {}".format(accuracy))
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ Provare un risolutore diverso come `lbfgs`, che è spesso impostato come predefinito
|
||||||
|
|
||||||
|
> Nota, usare la funzione [`ravel`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ravel.html) di Pandas per appiattire i dati quando necessario.
|
||||||
|
|
||||||
|
La precisione è buona oltre l'**80%**!
|
||||||
|
|
||||||
|
1. Si può vedere questo modello in azione testando una riga di dati (#50):
|
||||||
|
|
||||||
|
```python
|
||||||
|
print(f'ingredients: {X_test.iloc[50][X_test.iloc[50]!=0].keys()}')
|
||||||
|
print(f'cuisine: {y_test.iloc[50]}')
|
||||||
|
```
|
||||||
|
|
||||||
|
Il risultato viene stampato:
|
||||||
|
|
||||||
|
```output
|
||||||
|
ingredients: Index(['cilantro', 'onion', 'pea', 'potato', 'tomato', 'vegetable_oil'], dtype='object')
|
||||||
|
cuisine: indian
|
||||||
|
```
|
||||||
|
|
||||||
|
✅ Provare un numero di riga diverso e controllare i risultati
|
||||||
|
|
||||||
|
1. Scavando più a fondo, si può verificare l'accuratezza di questa previsione:
|
||||||
|
|
||||||
|
```python
|
||||||
|
test= X_test.iloc[50].values.reshape(-1, 1).T
|
||||||
|
proba = model.predict_proba(test)
|
||||||
|
classes = model.classes_
|
||||||
|
resultdf = pd.DataFrame(data=proba, columns=classes)
|
||||||
|
|
||||||
|
topPrediction = resultdf.T.sort_values(by=[0], ascending = [False])
|
||||||
|
topPrediction.head()
|
||||||
|
```
|
||||||
|
|
||||||
|
Il risultato è stampato: la cucina indiana è la sua ipotesi migliore, con buone probabilità:
|
||||||
|
|
||||||
|
| | 0 | | | | | | | | | | | | | | | | | | | | |
|
||||||
|
| -------: | -------: | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||||
|
| indiano | 0,715851 | | | | | | | | | | | | | | | | | | | | |
|
||||||
|
| cinese | 0.229475 | | | | | | | | | | | | | | | | | | | | |
|
||||||
|
| Giapponese | 0,029763 | | | | | | | | | | | | | | | | | | | | |
|
||||||
|
| Coreano | 0.017277 | | | | | | | | | | | | | | | | | | | | |
|
||||||
|
| thai | 0.007634 | | | | | | | | | | | | | | | | | | | | |
|
||||||
|
|
||||||
|
✅ Si è in grado di spiegare perché il modello è abbastanza sicuro che questa sia una cucina indiana?
|
||||||
|
|
||||||
|
1. Ottenere maggiori dettagli stampando un rapporto di classificazione, come fatto nelle lezioni di regressione:
|
||||||
|
|
||||||
|
```python
|
||||||
|
y_pred = model.predict(X_test)
|
||||||
|
print(classification_report(y_test,y_pred))
|
||||||
|
```
|
||||||
|
|
||||||
|
| precisione | recall | punteggio f1 | supporto | | | | | | | | | | | | | | | | | | |
|
||||||
|
| ------------ | ------ | -------- | ------- | ---- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||||
|
| cinese | 0,73 | 0,71 | 0,72 | 229 | | | | | | | | | | | | | | | | | |
|
||||||
|
| indiano | 0,91 | 0,93 | 0,92 | 254 | | | | | | | | | | | | | | | | | |
|
||||||
|
| Giapponese | 0.70 | 0,75 | 0,72 | 220 | | | | | | | | | | | | | | | | | |
|
||||||
|
| Coreano | 0,86 | 0,76 | 0,81 | 242 | | | | | | | | | | | | | | | | | |
|
||||||
|
| thai | 0,79 | 0,85 | 0.82 | 254 | | | | | | | | | | | | | | | | | |
|
||||||
|
| accuratezza | 0,80 | 1199 | | | | | | | | | | | | | | | | | | | |
|
||||||
|
| macro media | 0,80 | 0,80 | 0,80 | 1199 | | | | | | | | | | | | | | | | | |
|
||||||
|
| Media ponderata | 0,80 | 0,80 | 0,80 | 1199 | | | | | | | | | | | | | | | | | |
|
||||||
|
|
||||||
|
## 🚀 Sfida
|
||||||
|
|
||||||
|
In questa lezione, sono stati utilizzati dati puliti per creare un modello di apprendimento automatico in grado di prevedere una cucina nazionale basata su una serie di ingredienti. Si prenda del tempo per leggere le numerose opzioni fornite da Scikit-learn per classificare i dati. Approfondire il concetto di "risolutore" per capire cosa succede dietro le quinte.
|
||||||
|
|
||||||
|
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/22/)
|
||||||
|
## Revisione e Auto Apprendimento
|
||||||
|
|
||||||
|
Approfondire un po' la matematica alla base della regressione logistica in [questa lezione](https://people.eecs.berkeley.edu/~russell/classes/cs194/f11/lectures/CS194%20Fall%202011%20Lecture%2006.pdf)
|
||||||
|
## Compito
|
||||||
|
|
||||||
|
[Studiare i risolutori](assignment.it.md)
|
@ -0,0 +1,10 @@
|
|||||||
|
# Studiare i risolutori
|
||||||
|
## Istruzioni
|
||||||
|
|
||||||
|
In questa lezione si è imparato a conoscere i vari risolutori che associano algoritmi a un processo di machine learning per creare un modello accurato. Esaminare i risolutori elencati nella lezione e sceglierne due. Con parole proprie, confrontare questi due risolutori. Che tipo di problema affrontano? Come funzionano con varie strutture di dati? Perché se ne dovrebbe sceglierne uno piuttosto che un altro?
|
||||||
|
|
||||||
|
## Rubrica
|
||||||
|
|
||||||
|
| Criteri | Ottimo | Adeguato | Necessita miglioramento |
|
||||||
|
| -------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------ | ---------------------------- |
|
||||||
|
| | Viene presentato un file .doc con due paragrafi, uno su ciascun risolutore, confrontandoli attentamente. | Un file .doc viene presentato con un solo paragrafo | Il compito è incompleto |
|