pull/380/head
Shimon Lyons 5 years ago
commit a8c2a08a48

@ -16,15 +16,15 @@ jobs:
submodules: true
- name: Build And Deploy
id: builddeploy
uses: Azure/static-web-apps-deploy@v0.0.1-preview
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_JOLLY_SEA_0A877260F }}
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_WHITE_WATER_09EC41F0F }}
repo_token: ${{ secrets.GITHUB_TOKEN }} # Used for Github integrations (i.e. PR comments)
action: "upload"
###### Repository/Build Configurations - These values can be configured to match you app requirements. ######
###### Repository/Build Configurations - These values can be configured to match your app requirements. ######
# For more information regarding Static Web App workflow configurations, please visit: https://aka.ms/swaworkflowconfig
app_location: "/quiz-app" # App source code path
api_location: "api" # Api source code path - optional
api_location: "" # Api source code path - optional
output_location: "dist" # Built app content directory - optional
###### End of Repository/Build Configurations ######
@ -35,7 +35,7 @@ jobs:
steps:
- name: Close Pull Request
id: closepullrequest
uses: Azure/static-web-apps-deploy@v0.0.1-preview
uses: Azure/static-web-apps-deploy@v1
with:
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_JOLLY_SEA_0A877260F }}
azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN_WHITE_WATER_09EC41F0F }}
action: "close"

2
.gitignore vendored

@ -33,6 +33,8 @@ bld/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Visual Studio Code cache/options directory
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

@ -4,7 +4,7 @@
> 🎥 Click the image above for a video discussing the difference between machine learning, AI, and deep learning.
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/1/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/1/)
### Introduction
@ -17,7 +17,7 @@ Welcome to this course on classical machine learning for beginners! Whether you'
Before starting with this curriculum, you need to have your computer set up and ready to run notebooks locally.
- **Configure your machine with these videos**. Learn more about how to set up your machine in this [set of videos](https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6).
- **Configure your machine with these videos**. Use the following links to learn [how to install Python](https://youtu.be/CXZYvNRIAKM) in your system and [setup a text editor](https://youtu.be/EU8eayHWoZg) for development.
- **Learn Python**. It's also recommended to have a basic understanding of [Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa), a programming language useful for data scientists that we use in this course.
- **Learn Node.js and JavaScript**. We also use JavaScript a few times in this course when building web apps, so you will need to have [node](https://nodejs.org) and [npm](https://www.npmjs.com/) installed, as well as [Visual Studio Code](https://code.visualstudio.com/) available for both Python and JavaScript development.
- **Create a GitHub account**. Since you found us here on [GitHub](https://github.com), you might already have an account, but if not, create one and then fork this curriculum to use on your own. (Feel free to give us a star, too 😊)
@ -35,7 +35,7 @@ We live in a universe full of fascinating mysteries. Great scientists such as St
A child's brain and senses perceive the facts of their surroundings and gradually learn the hidden patterns of life which help the child to craft logical rules to identify learned patterns. The learning process of the human brain makes humans the most sophisticated living creature of this world. Learning continuously by discovering hidden patterns and then innovating on those patterns enables us to make ourselves better and better throughout our lifetime. This learning capacity and evolving capability is related to a concept called [brain plasticity](https://www.simplypsychology.org/brain-plasticity.html). Superficially, we can draw some motivational similarities between the learning process of the human brain and the concepts of machine learning.
The [human brain](https://www.livescience.com/29365-human-brain.html) perceives things from the real world, processes the perceived information, makes rational decisions, and performs certain actions based on circumstances. This is what we called behaving intelligently. When we program a facsimile of the intelligent behavioral process to a machine, it is called artificial intelligence (AI).
The [human brain](https://www.livescience.com/29365-human-brain.html) perceives things from the real world, processes the perceived information, makes rational decisions, and performs certain actions based on circumstances. This is what we called behaving intelligently. When we program a facsimile of the intelligent behavioral process to a machine, it is called artificial intelligence (AI).
Although the terms can be confused, machine learning (ML) is an important subset of artificial intelligence. **ML is concerned with using specialized algorithms to uncover meaningful information and find hidden patterns from perceived data to corroborate the rational decision-making process**.
@ -45,7 +45,7 @@ Although the terms can be confused, machine learning (ML) is an important subset
## What you will learn in this course
In this curriculum, we are going to cover only the core concepts of machine learning that a beginner must know. We cover what we call 'classical machine learning' primarily using Scikit-learn, an excellent library many students use to learn the basics. To understand broader concepts of artificial intelligence or deep learning, a strong fundamental knowledge of machine learning is indispensable, and so we would like to offer it here.
In this curriculum, we are going to cover only the core concepts of machine learning that a beginner must know. We cover what we call 'classical machine learning' primarily using Scikit-learn, an excellent library many students use to learn the basics. To understand broader concepts of artificial intelligence or deep learning, a strong fundamental knowledge of machine learning is indispensable, and so we would like to offer it here.
In this course you will learn:
@ -64,7 +64,7 @@ In this course you will learn:
- deep learning
- neural networks
- AI
To make for a better learning experience, we will avoid the complexities of neural networks, 'deep learning' - many-layered model-building using neural networks - and AI, which we will discuss in a different curriculum. We also will offer a forthcoming data science curriculum to focus on that aspect of this larger field.
## Why study machine learning?
@ -96,12 +96,14 @@ In the near future, understanding the basics of machine learning is going to be
Sketch, on paper or using an online app like [Excalidraw](https://excalidraw.com/), your understanding of the differences between AI, ML, deep learning, and data science. Add some ideas of problems that each of these techniques are good at solving.
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/2/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/2/)
## Review & Self Study
To learn more about how you can work with ML algorithms in the cloud, follow this [Learning Path](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa).
Take a [Learning Path](https://docs.microsoft.com/learn/modules/introduction-to-machine-learning/?WT.mc_id=academic-15963-cxa) about the basics of ML.
## Assignment
[Get up and running](assignment.md)

@ -0,0 +1,113 @@
# Introducción al machine learning
[![ML, IA, deep learning - ¿Cuál es la diferencia?](https://img.youtube.com/vi/lTd9RSxS9ZE/0.jpg)](https://youtu.be/lTd9RSxS9ZE "ML, IA, deep learning - ¿Cuál es la diferencia?")
> 🎥 Haz clic en la imagen de arriba para ver un video donde se discuten las diferencias entre el machine learning, la inteligencia artificial, y el deep learning.
## [Cuestionario previo a la conferencia](https://white-water-09ec41f0f.azurestaticapps.net/quiz/1/)
### Introducción
Te damos la bienvenida a este curso acerca del machine learning (ML) clásico para principiantes! Así se trate de tu primera incursión en este tema, o cuentes con amplia experiencia en el ML y busques refrescar tus conocimientos en un área específica, ¡nos alegramos de que te nos unas! Queremos crear un punto de lanzamiento amigable para tus estudios de ML y nos encantaría evaluar, responder, e incorporar tu [retroalimentación](https://github.com/microsoft/ML-For-Beginners/discussions).
[![Introducción al ML](https://img.youtube.com/vi/h0e2HAPTGF4/0.jpg)](https://youtu.be/h0e2HAPTGF4 "Introducción al ML")
> Haz clic en la imagen de arriba para ver el video: John Guttag del MIT presenta el machine learning
### Empezando con el machine learning
Antes de comenzar con este currículum, debes tener tu computadora configurada y lista para ejecutar los notebooks localmente.
- **Configura tu equipo con estos videos**. Aprende más acerca de como configurar tu equipo con [estos videos](https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6).
- **Aprende Python**. También se recomienda que tengas un entendimiento básico de [Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa), un lenguaje de programación útil para practicantes de la ciencia de datos, y que se utiliza en este curso.
- **Aprende Node.js y JavaScript**. También usamos JavaScript unas cuantas veces en este curso cuando creamos aplicaciones web, así que necesitarás tener [node](https://nodejs.org) y [npm](https://www.npmjs.com/) instalados, así como [Visual Studio Code](https://code.visualstudio.com/) listo para el desarrollo con Python y JavaScript.
- **Crea una cuenta de GitHub**. Como nos encontraste aquí en [GitHub](https://github.com), puede que ya tengas una cuenta, pero si no, créate una y después haz un fork de este curriculum para usarlo en tu computadora personal. (Siéntete en libertad de regalarnos una estrella, también 😊)
- **Explora Scikit-learn**. Familiarízate con [Scikit-learn](https://scikit-learn.org/stable/user_guide.html), un juego de bibliotecas de ML que referenciamos en estas lecciones.
### ¿Qué es el machine learning?
El término "machine learning" es uno de los términos más frecuentemente usados y populares hoy en día. Es muy probable que hayas escuchado este término al menos una vez si tienes algún tipo de familiaridad con la tecnología, no importa el sector en que trabajes. Aún así, las mecánicas del machine learning son un misterio para la mayoría de la gente. Para un principiante en machine learning, el tema puede sentirse intimidante. Es por esto que es importante entender lo que realmente es el machine learning, y aprender sobre el tema poco a poco, a través de ejemplos prácticos.
![curva de interés en ml](../images/hype.png)
> Google Trends nos muestra la más reciente "curva de interés" para el término "machine learning"
Vivimos en un universo lleno de misterios fascinantes. Grandes científicos como Stephen Hawking, Albert Einstein, y muchos más han dedicado sus vidas a la búsqueda de información significativa que revela los misterios del mundo a nuestro alrededor. Esta es la condición humana del aprendizaje: un niño humano aprende cosas nuevas y descubre la estructura de su mundo año con año conforme se convierten en adultos.
El cerebro de un niño y sus sentidos perciben sus alrededores y van aprendiendo gradualmente los patrones escondidos de la vida, lo que le ayuda al niño a crear reglas lógicas para identificar los patrones aprendidos. El proceso de aprendizaje del cerebro humano nos vuelve las criaturas más sofisticadas del planeta. Aprender de forma continua al descubrir patrones ocultos e innovar sobre esos patrones nos permite seguir mejorando a lo largo de nuestras vidas. Esta capacidad de aprendizaje y la capacidad de evolución están relacionadas a un concepto llamado [plasticidad cerebral o neuroplasticidad](https://www.simplypsychology.org/brain-plasticity.html). Podemos trazar algunas similitudes superficiales en cuanto a la motivación entre el proceso de aprendizaje del cerebro humano y los conceptos de machine learning.
El [cerebro humano](https://www.livescience.com/29365-human-brain.html) percibe cosas del mundo real, procesa la información percibida, toma decisiones racionales, y realiza ciertas acciones basadas en las circunstancias. Esto es a lo que se le conoce como el comportamiento inteligente. Cuando programamos un facsímil (copia) del proceso del comportamiento inteligente, se le llama inteligencia artificial (IA).
Aunque los términos se suelen confundir, machine learning (ML) es un subconjunto importante de la inteligencia artificial. **El objetivo del ML es utilizar algoritmos especializados para descubrir información significativa y encontrar patrones ocultos de los datos percibidos para corroborar el proceso relacional de la toma de decisiones**.
![IA, ML, deep learning, ciencia de los datos](../images/ai-ml-ds.png)
> El diagrama muestra la relación entre IA, ML, deep learning y la ciencia de los datos. Infografía hecha por [Jen Looper](https://twitter.com/jenlooper) inspirada en [esta gráfica](https://softwareengineering.stackexchange.com/questions/366996/distinction-between-ai-ml-neural-networks-deep-learning-and-data-mining).
## Lo que aprenderás en el curso
En este currículum, vamos a cubrir solo los conceptos clave de machine learning que un principiante debería conocer. Cubrimos algo a lo que le llamamos "machine learning clásico" usando principalmente Scikit-learn, una biblioteca excelente que muchos estudiantes utilizan para aprender las bases. Para entender conteptos más amplios de la inteligencia artificial o deep learning, es indispensable tener un fuerte conocimiento de los fundamentos, y eso es lo que nos gustaría ofrecerte aquí.
En este curso aprenderás:
- conceptos clave del machine learning
- la historia de ML
- la justicia y el ML
- técnicas de regresión en ML
- técnicas de clasificación en ML
- técnicas de agrupamiento en ML
- técnicas de procesamiento del lenguaje natural en ML
- técnicas de previsión de series temporales en ML
- reforzamiento del aprendizaje
- ML aplicada al mundo real
## Lo que no cubriremos
- deep learning
- redes neuronales
- inteligencia artificial (IA)
Para tener una mejor experiencia de aprendizaje, vamos a evitar las complejidades de las redes neuronales, "deep learning" (construcción de modelos de muchas capas utilizando las redes neuronales) e inteligencia artificial, que se discutirá en un currículum diferente. En un futuro también ofreceremos un currículum acerca de la ciencia de datos para enfocarnos en ese aspecto de este campo.
## ¿Por qué estudiar machine learning?
Machine learning, desde una perspectiva de los sistemas, se define como la creación de sistemas automáticos que pueden aprender patrones ocultos a partir de datos para ayudar en tomar decisiones inteligentes.
Esta motivación está algo inspirada por como el cerebro humano aprende ciertas cosas basadas en los datos que percibe en el mundo real.
✅ Piensa por un minuto en porqué querría un negocio intentar implementar estrategias de machine learning vs. programar un motor basado en reglas.
### Aplicaciones del machine learning
Las aplicaciones del machine learning hoy en día están casi en todas partes, y son tan ubicuas como los datos que fluyen alrededor de nuestras sociedades, generados por nuestros teléfonos inteligentes, dispositivos conectados a internet, y otros sistemas. Considerando el inmenso potencial de los algoritmos estado del arte de machine learning, investigadores han estado explorando su capacidad de resolver problemas multidimensionales y multidisciplinarios de la vida real con resultados muy positivos.
**Tú puedes utilizar machine learning de muchas formas**:
- Para predecir la probabilidad de enfermedad a partir del historial médico o reportes de un paciente.
- Para aprovechar datos del clima y predecir eventos climatológicos.
- Para entender la intención de un texto.
- Para detectar noticias falsas y evitar la propagación de propaganda.
Finanzas, economía, ciencias de la Tierra, exploración espacial, ingeniería biomédica, ciencia cognitiva, e incluso campos en las humanidades han adaptado machine learning para solucionar los problemas más arduos y pesados en cuanto al procesamiento de datos.
Machine learning automatiza el proceso del descubrimiento de patrones al encontrar perspectivas significativas desde el mundo real o datos generados. Machine learning ha demostrado ser muy valioso en las aplicaciones del sector salud, negocios y finanzas, entre otros.
En el futuro próximo, entender las bases de machine learning va a ser una necesidad para la gente en cualquier sector debido a su alta adopción.
---
## 🚀 Desafío
Dibuja, en papel o usando una aplicación como [Excalidraw](https://excalidraw.com/), como tú entiendes las diferencias entre inteligencia artificial, ML, deep learning, y la ciencia de datos. Agrega algunas ideas o problemas que cada una de estas técnicas son buenas en resolver.
## [Cuestionario después de la conferencia](https://white-water-09ec41f0f.azurestaticapps.net/quiz/2/)
## Revisión y autoestudio
Para aprender más sobre como puedes trabajar con algoritmos de ML en la nube, sigue esta [Ruta de Aprendizaje](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa).
Toma esta [Ruta de Aprendizaje](https://docs.microsoft.com/learn/modules/introduction-to-machine-learning/?WT.mc_id=academic-15963-cxa) sobre las bases de ML.
## Asignación
[Ponte en marcha](assignment.md)

@ -0,0 +1,109 @@
# Introduction au machine learning
[![ML, AI, deep learning - Quelle est la différence ?](https://img.youtube.com/vi/lTd9RSxS9ZE/0.jpg)](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://white-water-09ec41f0f.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).
[![Introduction au ML](https://img.youtube.com/vi/h0e2HAPTGF4/0.jpg)](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.
![ml hype curve](../images/hype.png)
> 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**.
![AI, ML, deep learning, data science](../images/ai-ml-ds.png)
> 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://white-water-09ec41f0f.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
[![ML, AI, deep learning - Apa perbedaannya?](https://img.youtube.com/vi/lTd9RSxS9ZE/0.jpg)](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://white-water-09ec41f0f.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.
[![Pengantar Machine Learning](https://img.youtube.com/vi/h0e2HAPTGF4/0.jpg)](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.
![kurva tren ml](../images/hype.png)
> 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**.
![AI, ML, deep learning, data science](../images/ai-ml-ds.png)
> 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://white-water-09ec41f0f.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)

@ -4,7 +4,7 @@
> 🎥 Fare clic sull'immagine sopra per un video che illustra la differenza tra machine learning, intelligenza artificiale (AI) e deep learning.
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/1/)
## [Quiz pre-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/1/?loc=it)
### Introduzione
@ -97,7 +97,7 @@ Nel prossimo futuro, comprendere le basi di machine learning sarà un must per l
Disegnare, su carta o utilizzando un'app online come [Excalidraw](https://excalidraw.com/), la propria comprensione delle differenze tra AI, ML, deep learning e data science. Aggiungere alcune idee sui problemi che ciascuna di queste tecniche è in grado di risolvere.
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/2/)
## [Quiz post-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/2/?loc=it)
## Revisione e Auto Apprendimento

@ -4,7 +4,7 @@
> 🎥 上の画像をクリックすると、機械学習、AI、深層学習の違いについて説明した動画が表示されます。
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/1/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/1?loc=ja)
### イントロダクション
@ -94,12 +94,12 @@
## 🚀 Challenge
AI、ML、深層学習、データサイエンスの違いについて理解していることを、紙や[Excalidraw](https://excalidraw.com/)などのオンラインアプリを使ってスケッチしてください。また、それぞれの技術が得意とする問題のアイデアを加えてみてください。
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/2/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/2?loc=ja)
## 振り返りと自習
クラウド上でMLアルゴリズムをどのように扱うことができるかについては、この[ラーニングパス](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa)に従ってください。.
クラウド上でMLアルゴリズムをどのように扱うことができるかについては、この[ラーニングパス](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa)に従ってください。
## 課題
[起動し、実行してください。](assignment.md)
[稼働させる](assignment.ja.md)

@ -0,0 +1,110 @@
# 머신러닝 소개
[![ML, AI, deep learning - What's the difference?](https://img.youtube.com/vi/lTd9RSxS9ZE/0.jpg)](https://youtu.be/lTd9RSxS9ZE "ML, AI, deep learning - What's the difference?")
> 🎥 머신러닝, AI 그리고 딥러닝의 차이를 설명하는 영상을 보려면 위 이미지를 클릭합니다.
## [강의 전 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/1/)
### 소개
입문자를 위한 classical 머신러닝 코스에 오신 것을 환영합니다! 이 토픽에 완벽하게 새로 접해보거나, 한 분야에 완벽해지고 싶어하는 ML 실무자도 저희와 함께하게 되면 좋습니다! ML 연구를 위한 친숙한 시작점을 만들고 싶고, 당신의 [feedback](https://github.com/microsoft/ML-For-Beginners/discussions)을 평가, 응답하고 반영하겠습니다.
[![Introduction to ML](https://img.youtube.com/vi/h0e2HAPTGF4/0.jpg)](https://youtu.be/h0e2HAPTGF4 "Introduction to ML")
> 🎥 동영상을 보려면 위 이미지 클릭: MIT의 John Guttag가 머신러닝을 소개합니다.
### 머신러닝 시작하기
이 커리큘럼을 시작하기 전, 컴퓨터를 세팅하고 노트북을 로컬에서 실행할 수 있게 준비해야 합니다.
- **이 영상으로 컴퓨터 세팅하기**. [set of videos](https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6)에서 컴퓨터를 세팅하는 방법에 대하여 자세히 알아봅니다.
- **Python 배우기**. 이 코스에서 사용할 데이터 사이언티스트에게 유용한 프로그래밍 언어인 [Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa)에 대한 기본적인 이해를 해야 좋습니다.
- **Node.js 와 JavaScript 배우기**. 이 코스에서 웹앱을 빌드할 때 몇 번 JavaScript를 사용하므로, [node](https://nodejs.org) 와 [npm](https://www.npmjs.com/)을 설치해야 합니다, Python 과 JavaScript를 개발하며 모두 쓸 수 있는 [Visual Studio Code](https://code.visualstudio.com/)도 있습니다.
- **GitHub 계정 만들기**. [GitHub](https://github.com)에서 찾았으므로, 이미 계정이 있을 수 있습니다, 혹시 없다면, 계정을 만든 뒤에 이 커리큘럼을 포크해서 직접 쓸 수 있습니다. (star 주셔도 됩니다 😊)
- **Scikit-learn 찾아보기**. 이 강의에서 참조하고 있는 ML 라이브러리 셋인 [Scikit-learn](https://scikit-learn.org/stable/user_guide.html)을 숙지합니다.
### 머신러닝은 무엇인가요?
'머신러닝'은 최근 가장 인기있고 자주 언급되는 용어입니다. 어떤 분야든 기술에 어느 정도 익숙해지면 이러한 용어를 한 번즈음 들어본 적이 있었을 것입니다, 그러나, 머신러닝의 구조는 대부분의 사람들에겐 미스테리입니다. 머신러닝 입문자에겐 주제가 때때로 숨막힐 수 있습니다, 그래서 머신러닝이 실제로 어떤 지 이해하고, 실제 적용된 예시로, 단계별 학습을 진행하는 것이 중요합니다.
![ml hype curve](../images/hype.png)
> Google Trends는 '머신러닝' 용어의 최근 'hype curve'로 보여줍니다
우리는 매우 신비한 우주에 살고 있습니다. Stephen Hawking, Albert Einstein과 같은 위대한 과학자들은 주변 세계의 신비를 밝혀낼 의미있는 정보를 찾는 데 일생을 바쳤습니다. 이건 사람의 학습 조건입니다: 아이는 자라면서 해마다 새로운 것을 배우고 세계 구조를 발견합니다.
어린이의 뇌와 센스는 주변의 사실을 인식하고 점차 숨겨진 생활 패턴을 학습하여 학습된 패턴을 식별할 논리 규칙을 만드는 데 도움을 줍니다. 뇌의 논리 프로세스는 사람을 가장 정교한 생명체로 만듭니다. 숨겨진 패턴을 발견하고 개선하여 지속해서 학습하면 평생 발전할 수 있습니다. 이런 학습 능력과 진화력은 [brain plasticity](https://www.simplypsychology.org/brain-plasticity.html)로 불리는 컨셉과 관련있습니다. 표면적으로, 뇌의 학습 과정과 머신러닝의 개념 사이에 motivational similarities를 그릴 수 있습니다.
[human brain](https://www.livescience.com/29365-human-brain.html)은 실제 세계에서 사물을 인식하고, 인식된 정보를 처리하며, 합리적인 결정과, 상황에 따른 행동을 합니다. 이걸 지능적으로 행동한다고 합니다. 기계에 지능적인 행동 복사본를 프로그래밍할 때, 인공 지능 (AI)라고 부릅니다.
용어가 햇갈릴 수 있지만, 머신러닝(ML)은 중요한 인공 지능의 서브넷입니다. **ML은 특수한 알고리즘을 써서 의미있는 정보를 찾고 인식한 데이터에서 숨겨진 패턴을 찾아 합리적으로 판단할 프로세스를 확실하게 수행하는 것에 관심있습니다**.
![AI, ML, deep learning, data science](../images/ai-ml-ds.png)
> AI, ML, 딥러닝, 그리고 데이터 사이언티스트 간의 관계를 보여주는 다이어그램. [this graphic](https://softwareengineering.stackexchange.com/questions/366996/distinction-between-ai-ml-neural-networks-deep-learning-and-data-mining)에서 영감을 받은 [Jen Looper](https://twitter.com/jenlooper)의 인포그래픽
## 이 코스에서 배우는 것
이 커리큘럼에서, 입문자가 반드시 알아야 할 머신러닝의 핵심적인 개념만 다룰 것입니다. 많은 학생들이 기초를 배우기 위해 사용하는 훌륭한 라이브러리인, Scikit-learn으로 'classical machine learning'이라고 부르는 것을 다룹니다. 인공 지능 또는 딥러닝의 대략적인 개념을 이해하려면, 머신러닝에 대한 강력한 기초 지식이 꼭 필요하므로, 여기에서 제공하고자 합니다.
이 코스에서 다음 사항을 배웁니다:
- 머신러닝의 핵심 컨셉
- ML 의 역사
- ML 과 공정성
- regression ML 기술
- classification ML 기술
- clustering ML 기술
- natural language processing ML 기술
- time series forecasting ML 기술
- 강화 학습
- real-world 애플리케이션 for ML
## 다루지 않는 것
- 딥러닝
- 신경망
- AI
더 좋은 학습 환경을 만들기 위해서, 신경망, '딥러닝' - many-layered model-building using neural networks - 과 AI의 복잡도를 피할 것이며, 다른 커리큘럼에서 논의할 것입니다. 또한 더 큰 필드에 초점을 맞추기 위하여 향후 데이터 사이언스 커리큘럼을 제공할 예정입니다.
## 왜 머신러닝을 배우나요?
시스템 관점에서 보는 머신러닝은, 지능적인 결정하도록 데이터에서 숨겨진 패턴을 학습할 수 있는 자동화 시스템 생성으로 정의합니다.
동기 부여는 뇌가 다른 세계에서 보는 데이터를 기반으로 특정한 무언가들을 학습하는 방식에서 살짝 영감을 받았습니다.
✅ 비지니스에서 머신러닝 전략 대신 하드-코딩된 룰-베이스 엔진을 만드려는 이유를 잠시 생각해봅시다.
### 머신러닝의 애플리케이션
머신러닝의 애플리케이션은 이제 거의 모든 곳에서, 스마트 폰, 연결된 기기, 그리고 다른 시스템에 의하여 생성된 주변의 흐르는 데이터만큼 어디에나 존재합니다. 첨단 머신러닝 알고리즘의 큰 잠재력을 고려한, 연구원들은 긍정적인 결과로 multi-dimensional과 multi-disciplinary적인 실-생활 문제를 해결하는 능력을 찾고 있습니다.
**다양한 방식으로 머신러닝을 사용할 수 있습니다**:
- 환자의 병력이나 보고서를 기반으로 질병 가능성을 예측합니다.
- 날씨 데이터로 계절 이벤트를 예측합니다.
- 문장의 감정을 이해합니다.
- 가짜 뉴스를 감지하고 선동을 막습니다.
금융, 경제학, 지구 과학, 우주 탐험, 생물 공학, 인지 과학, 그리고 인문학까지 머신러닝을 적용하여 힘들고, 데이터 처리가 버거운 이슈를 해결했습니다.
머신러닝은 실제-환경이거나 생성된 데이터에서 의미를 찾아 패턴-발견하는 프로세스를 자동화합니다. 비즈니스, 건강과 금용 애플리케이션에서 높은 가치가 있다고 증명되었습니다.
가까운 미래에, 머신러닝의 기본을 이해하는 건 광범위한 선택으로 인하여 모든 분야의 사람들에게 필수적으로 다가올 것 입니다.
---
## 🚀 도전
종이에 그리거나, [Excalidraw](https://excalidraw.com/)처럼 온라인 앱을 이용하여 AI, ML, 딥러닝, 그리고 데이터 사이언스의 차이를 이해합시다. 각 기술들이 잘 해결할 수 있는 문제에 대해 아이디어를 합쳐보세요.
## [강의 후 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/2/)
## 리뷰 & 자기주도 학습
클라우드에서 ML 알고리즘을 어떻게 사용하는 지 자세히 알아보려면, [Learning Path](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa)를 따릅니다.
ML의 기초에 대한 [Learning Path](https://docs.microsoft.com/learn/modules/introduction-to-machine-learning/?WT.mc_id=academic-15963-cxa)를 봅니다.
## 과제
[Get up and running](../assignment.md)

@ -4,7 +4,7 @@
> 🎥 Makine öğrenimi, yapay zeka ve derin öğrenme arasındaki farkı tartışan bir video için yukarıdaki resme tıklayın.
## [Ders öncesi sınav](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/1?loc=tr)
## [Ders öncesi sınav](https://white-water-09ec41f0f.azurestaticapps.net/quiz/1?loc=tr)
### Introduction
@ -103,7 +103,7 @@ Yakın gelecekte, yaygın olarak benimsenmesi nedeniyle makine öğreniminin tem
Kağıt üzerinde veya [Excalidraw](https://excalidraw.com/) gibi çevrimiçi bir uygulama kullanarak AI, makine öğrenimi, derin öğrenme ve veri bilimi arasındaki farkları anladığınızdan emin olun. Bu tekniklerin her birinin çözmede iyi olduğu bazı problem fikirleri ekleyin.
## [Ders sonrası test](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/2?loc=tr)
## [Ders sonrası test](https://white-water-09ec41f0f.azurestaticapps.net/quiz/2?loc=tr)
## İnceleme ve Bireysel Çalışma

@ -4,24 +4,24 @@
> 🎥 点击上面的图片观看讨论机器学习、人工智能和深度学习之间区别的视频。
## [课前测验](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/1/)
## [课前测验](https://white-water-09ec41f0f.azurestaticapps.net/quiz/1/)
### 介绍
欢迎来到这个经典机器学习的初学者课程!无论你是这个主题的新手,还是一个有经验的ML从业者,我们都很高兴你能加入我们!我们希望为你的ML研究创建一个好的开始,并很乐意评估、回应和接受你的[反馈](https://github.com/microsoft/ML-For-Beginners/discussions)。
欢迎来到这个经典机器学习的初学者课程!无论你是这个主题的新手,还是一个有经验的 ML 从业者,我们都很高兴你能加入我们!我们希望为你的 ML 研究创建一个好的开始,并很乐意评估、回应和接受你的[反馈](https://github.com/microsoft/ML-For-Beginners/discussions)。
[![机器学习简介](https://img.youtube.com/vi/h0e2HAPTGF4/0.jpg)](https://youtu.be/h0e2HAPTGF4 "Introduction to ML")
> 🎥 单击上图观看视频:麻省理工学院的 John Guttag 介绍机器学习
### 机器学习入门
在开始本课程之前,你需要设置计算机能在本地运行Jupyter Notebooks。
在开始本课程之前,你需要设置计算机能在本地运行 Jupyter Notebooks。
- **按照这些视频里的讲解配置你的计算机**。了解有关如何在此[视频集](https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6)中设置计算机的更多信息。
- **学习Python**. 还建议你对[Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa),我们在本课程中使用的一种对数据科学家有用的编程语言,有一个基本的了解。
- **学习Node.js和JavaScript**。在本课程中,我们在构建web应用程序时也使用过几次JavaScript,因此你需要有[node](https://nodejs.org)和[npm](https://www.npmjs.com/) 以及[Visual Studio Code](https://code.visualstudio.com/)用于Python和JavaScript开发。
- **创建GitHub帐户**。既然你在[GitHub](https://github.com)上找到我们,你可能已经有了一个帐户,但如果没有,请创建一个帐户,然后fork此课程自己使用(也给我们一颗星星吧😊)
- **探索Scikit-learn**. 熟悉[Scikit-learn]([https://scikit-learn.org/stable/user_guide.html),我们在这些课程中引用的一组ML库。
- **学习 Python**。 还建议你对 [Python](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa) 有一个基本的了解。这是我们在本课程中使用的一种对数据科学家有用的编程语言。
- **学习 Node.js 和 JavaScript**。在本课程中,我们在构建 web 应用程序时也使用过几次 JavaScript,因此你需要有 [Node.js](https://nodejs.org) 和 [npm](https://www.npmjs.com/) 以及 [Visual Studio Code](https://code.visualstudio.com/) 用于 Python 和 JavaScript 开发。
- **创建 GitHub 帐户**。既然你在 [GitHub](https://github.com) 上找到我们,你可能已经有了一个帐户,但如果没有,请创建一个帐户,然后 fork 此课程自己使用(也给我们一颗星星吧😊)
- **探索 Scikit-learn**. 熟悉 [Scikit-learn]([https://scikit-learn.org/stable/user_guide.html),我们在这些课程中引用的一组 ML 库。
### 什么是机器学习?
@ -41,11 +41,11 @@
![人工智能、机器学习、深度学习、数据科学](../images/ai-ml-ds.png)
> 显示AI、ML、深度学习和数据科学之间关系的图表。图片作者[Jen Looper](https://twitter.com/jenlooper),灵感来自[这张图](https://softwareengineering.stackexchange.com/questions/366996/distinction-between-ai-ml-neural-networks-deep-learning-and-data-mining)
> 显示 AI、ML、深度学习和数据科学之间关系的图表。图片作者 [Jen Looper](https://twitter.com/jenlooper),灵感来自[这张图](https://softwareengineering.stackexchange.com/questions/366996/distinction-between-ai-ml-neural-networks-deep-learning-and-data-mining)
## 你将在本课程中学到什么
在本课程中,我们将仅涵盖初学者必须了解的机器学习的核心概念。 我们主要使用Scikit-learn来介绍我们所谓的“经典机器学习”,这是一个许多学生用来学习基础知识的优秀库。要理解更广泛的人工智能或深度学习的概念,机器学习的基础知识是必不可少的,所以我们想在这里提供它。
在本课程中,我们将仅涵盖初学者必须了解的机器学习的核心概念。 我们主要使用 Scikit-learn 来介绍我们所谓的“经典机器学习”,这是一个许多学生用来学习基础知识的优秀库。要理解更广泛的人工智能或深度学习的概念,机器学习的基础知识是必不可少的,所以我们想在这里提供它。
在本课程中,你将学习:
@ -94,14 +94,14 @@
---
## 🚀 挑战
在纸上或使用[Excalidraw](https://excalidraw.com/)等在线应用程序绘制草图,了解你对AI、ML、深度学习和数据科学之间差异的理解。添加一些关于这些技术擅长解决的问题的想法。
在纸上或使用 [Excalidraw](https://excalidraw.com/) 等在线应用程序绘制草图,了解你对 AI、ML、深度学习和数据科学之间差异的理解。添加一些关于这些技术擅长解决的问题的想法。
## [阅读后测验](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/2/)
## [阅读后测验](https://white-water-09ec41f0f.azurestaticapps.net/quiz/2/)
## 复习与自学
要了解有关如何在云中使用ML算法的更多信息,请遵循以下[学习路径](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa)。
要了解有关如何在云中使用 ML 算法的更多信息,请遵循以下[学习路径](https://docs.microsoft.com/learn/paths/create-no-code-predictive-models-azure-machine-learning/?WT.mc_id=academic-15963-cxa)。
## 任务
[启动并运行](../assignment.md)
[启动并运行](assignment.zh-cn.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,9 @@
# 稼働させる
## 指示
この評価のない課題では、Pythonについて復習し、環境を稼働させてノートブックを実行できるようにする必要があります。
この[Pythonラーニングパス](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa)を受講し、次の入門用ビデオに従ってシステムをセットアップしてください。
https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6

@ -0,0 +1,9 @@
# 启动和运行
## 说明
在这个不评分的作业中,你应该温习一下 Python,将 Python 环境能够运行起来,并且可以运行 notebooks。
学习这个 [Python 学习路径](https://docs.microsoft.com/learn/paths/python-language/?WT.mc_id=academic-15963-cxa),然后通过这些介绍性的视频将你的系统环境设置好:
https://www.youtube.com/playlist?list=PLlrxD0HtieHhS8VzuMCfQD4uJ9yne1mE6

@ -3,7 +3,7 @@
![Summary of History of machine learning in a sketchnote](../../sketchnotes/ml-history.png)
> Sketchnote by [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/3/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/3/)
In this lesson, we will walk through the major milestones in the history of machine learning and artificial intelligence.
@ -101,7 +101,7 @@ It remains to be seen what the future holds, but it is important to understand t
Dig into one of these historical moments and learn more about the people behind them. There are fascinating characters, and no scientific discovery was ever created in a cultural vacuum. What do you discover?
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/4/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/4/)
## Review & Self Study

@ -0,0 +1,117 @@
# Historia del machine learning
![Resumen de la historoia del machine learning en un boceto](../../sketchnotes/ml-history.png)
> Boceto por [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Cuestionario previo a la conferencia](https://white-water-09ec41f0f.azurestaticapps.net/quiz/3/)
En esta lección, analizaremos los principales hitos en la historia del machine learning y la inteligencia artificial.
La historia de la inteligencia artificial, AI, como campo está entrelazada con la historia del machine learning, ya que los algoritmos y avances computacionales que sustentan el ML se incorporaron al desarrollo de la inteligencia artificial. Es útil recordar que, si bien, estos campos como áreas distintas de investigación comenzaron a cristalizar en la década de 1950, importantes [desubrimientos algorítmicos, estadísticos, matemáticos, computacionales y técnicos](https://wikipedia.org/wiki/Timeline_of_machine_learning) predecieronn y superpusieron a esta era. De hecho, las personas han estado pensando en estas preguntas durante [cientos de años](https://wikipedia.org/wiki/History_of_artificial_intelligence): este artículo analiza los fundamentos intelectuales históricos de la idea de una 'máquina pensante.'
## Descubrimientos notables
- 1763, 1812 [Teorema de Bayes](https://wikipedia.org/wiki/Bayes%27_theorem) y sus predecesores. Este teorema y sus aplicaciones son la base de la inferencia, describiendo la probabilidad de que ocurra un evento basado en el concimiento previo.
- 1805 [Teoría de mínimos cuadrados](https://wikipedia.org/wiki/Least_squares) por el matemático francés Adrien-Marie Legendre. Esta teoría, que aprenderá en nuestra unidad de Regresión, ayuda en el data fitting.
- 1913 [Cadenas de Markov](https://wikipedia.org/wiki/Markov_chain) el nombre del matemático ruso Andrey Markov es utilizado para describir una secuencia de eventos basados en su estado anterior.
- 1957 [Perceptron](https://wikipedia.org/wiki/Perceptron) es un tipo de clasificador lineal inventado por el psicólogo Frank Rosenblatt que subyace a los avances en el deep learning.
- 1967 [Nearest Neighbor (Vecino más cercano)](https://wikipedia.org/wiki/Nearest_neighbor) es un algoritmo diseñado originalmente para trazar rutas. En un contexto de ML, se utiliza para detectar patrones.
- 1970 [Backpropagation](https://wikipedia.org/wiki/Backpropagation) es usado para entrenar [feedforward neural networks](https://wikipedia.org/wiki/Feedforward_neural_network).
- 1982 [Recurrent Neural Networks](https://wikipedia.org/wiki/Recurrent_neural_network) son redes neuronales artificiales derivadas de redes neuronales feedforward que crean grafos temporales.
✅ Investigue un poco. ¿Qué otras fechas se destacan como fundamentales en la historia del machine learning (ML) y la inteligencia artificial (AI)?
## 1950: Máquinas que piensan
Alan Turing, una persona verdaderamente notable que fue votada [por el público en 2019](https://wikipedia.org/wiki/Icons:_The_Greatest_Person_of_the_20th_Century) como el científico más grande del siglo XX, se le atribuye haber ayudado a sentar las bases del concepto de una 'máquina que puede pensar.' Lidió con los detractores y su propia necesidad de evidencia empírica de este concepto en parte mediante la creación de la [prueba de Turing](https://www.bbc.com/news/technology-18475646, que explorarás en nuestras lecciones de NLP.
## 1956: Dartmouth Summer Research Project
"The Dartmouth Summer Research Project sobre inteligencia artificial fuer un evento fundamental para la inteligencia artificial como campo," y fue aquí donde el se acuñó el término 'inteligencia artificial' ([fuente](https://250.dartmouth.edu/highlights/artificial-intelligence-ai-coined-dartmouth)).
> Todos los aspectos del aprendizaje y cualquier otra característica de la inteligencia pueden, en principio, describirse con tanta precisión que se puede hacer una máquina para simularlos.
El investigador principal, el profesor de matemáticas John McCarthy, esperaba "proceder sobre las bases de la conjetura que cada aspecto del aprendizaje o cualquier otra característica de la inteligencia pueden, en principio, describirse con tanta precición que se se puede hacer una máquina para simularlos." Los participantes, incluyeron otra luminaria en el campo, Marvin Minsky.
El taller tiene el mérito de haber iniciado y alentado varias discusiones que incluyen "el surgimiento de métodos simbólicos, systemas en dominios limitados (primeros sistemas expertos), y sistemas deductivos versus sistemas inductivos." ([fuente](https://wikipedia.org/wiki/Dartmouth_workshop)).
## 1956 - 1974: "Los años dorados"
Desde la década de 1950, hasta mediados de la de 1970, el optimismo se elevó con la esperanza de que la AI pudiera resolver muchos problemas. En 1967, Marvin Minsky declaró con seguridad que "dentro de una generación ... el problema de crear 'inteligencia artificial' se resolverá sustancialemte." (Minsky, Marvin (1967), Computation: Finite and Infinite Machines, Englewood Cliffs, N.J.: Prentice-Hall)
La investigación del procesamiento del lenguaje natural floreció, la búsqueda se refinó y se hizo más poderosa, y el concepto de 'micro-worlds' fue creado, donde se completaban tareas simples utilizando instrucciones en lenguaje sencillo.
La investigación estuvo bien financiado por agencias gubernamentales, se realizaron avances en computación y algoritmos, y se construyeron prototipos de máquinas inteligentes.Algunas de esta máquinas incluyen:
* [Shakey la robot](https://wikipedia.org/wiki/Shakey_the_robot), que podría maniobrar y decidir cómo realizar las tares de forma 'inteligente'.
![Shakey, un robot inteligente](images/shakey.jpg)
> Shakey en 1972
* Eliza, unas de las primeras 'chatterbot', podía conversar con las personas y actuar como un 'terapeuta' primitivo. Aprenderá más sobre ELiza en las lecciones de NLP.
![Eliza, un bot](images/eliza.png)
> Una versión de Eliza, un chatbot
* "Blocks world" era un ejemplo de micro-world donde los bloques se podían apilar y ordenar, y se podían probar experimentos en máquinas de enseñanza para tomar decisiones. Los avances creados con librerías como [SHRDLU](https://wikipedia.org/wiki/SHRDLU) ayudaron a inpulsar el procesamiento del lenguaje natural.
[![blocks world con SHRDLU](https://img.youtube.com/vi/QAJz4YKUwqw/0.jpg)](https://www.youtube.com/watch?v=QAJz4YKUwqw "blocks world con SHRDLU")
> 🎥 Haga click en la imagen de arriba para ver un video: Blocks world con SHRDLU
## 1974 - 1980: "Invierno de la AI"
A mediados de la década de 1970, se hizo evidente que la complejidad de la fabricación de 'máquinas inteligentes' se había subestimado y que su promesa, dado la potencia computacional disponible, había sido exagerada. La financiación se agotó y la confianza en el campo se ralentizó. Algunos problemas que impactaron la confianza incluyeron:
- **Limitaciones**. La potencia computacional era demasiado limitada.
- **Explosión combinatoria**. La cantidad de parámetros necesitados para entrenar creció exponencialmente a medida que se pedía más a las computadoras sin una evolución paralela de la potencia y la capacidad de cómputo.
- **Escasez de datos**. Hubo una escasez de datos que obstaculizó el proceso de pruebas, desarrollo y refinamiento de algoritmos.
- **¿Estamos haciendo las preguntas correctas?**. Las mismas preguntas que se estaban formulando comenzaron a cuestionarse. Los investigadores comenzaron a criticar sus aproches:
- Las pruebas de Turing se cuestionaron por medio, entre otras ideas, de la 'teoría de la habitación china' que postulaba que "progrmar una computadora digital puede hacerse que parezca que entiende el lenguaje, pero no puede producir una comprensión real" ([fuente](https://plato.stanford.edu/entries/chinese-room/))
- Se cuestionó la ética de introducir inteligencias artificiales como la "terapeuta" Eliza en la sociedad.
Al mismo tiempo, comenzaron a formarse varia escuelas de pensamiento de AI. Se estableció una dicotomía entre las prácticas ["scruffy" vs. "neat AI"](https://wikipedia.org/wiki/Neats_and_scruffies). _Scruffy_ labs modificó los programas durante horas hasta que obtuvieron los objetivos deseados. _Neat_ labs "centrados en la lógica y la resolución de problemas formales". ELIZA y SHRDLU eran systemas _scruffy_ bien conocidos. En la década de 1980, cuando surgió la demanda para hacer que los sistemas de aprendizaje fueran reproducibles, el enfoque _neat_ gradualmente tomó la vanguardia a medidad que sus resultados eran más explicables.
## Systemas expertos de la década de 1980
A medida que el campo creció, su beneficio para las empresas se hizo más claro, y en la década de 1980 también lo hizo la proliferación de 'sistemas expertos'. "Los sistemas expertos estuvieron entre las primeras formas verdaderamente exitosas de software de inteligencia artificial (IA)." ([fuente](https://wikipedia.org/wiki/Expert_system)).
Este tipo de sistemas es en realidad _híbrido_, que consta parcialmente de un motor de reglas que define los requisitos comerciales, y un motor de inferencia que aprovechó el sistema de reglas para deducir nuevos hechos.
En esta era también se prestó mayor atención a las redes neuronales.
## 1987 - 1993: AI 'Chill'
La prolifercaión de hardware de sistemas expertos especializados tuvo el desafortunado efecto de volverse demasiado especializado. El auge de las computadoras personales también compitió con estos grandes sistemas centralizados especializados. La democratización de la informática había comenzado, y finalmente, allanó el camino para la explosión moderna del big data.
## 1993 - 2011
Esta época vió una nueva era para el ML y la IA para poder resolver problemas que habían sido causados anteriormente for la falta de datos y poder de cómputo. La cantidad de datos comenzó a aumentar rápidamente y a estar más disponible, para bien o para mal, especialmente con la llegada del smartphone alrededor del 2007. El poder computacional se expandió exponencialmente y los algoritmos evolucionaron al mismo tiempo. El campo comenzó a ganar madurez a medida que los días libres del pasado comenzaron a cristalizar en un verdadera disciplina.
## Ahora
Hoy en día, machine learning y la inteligencia artificial tocan casi todos los aspectos de nuestras vidas. Esta era requiere una comprensión cuidadosa de los riesgos y los efectos potenciales de estos algoritmos en las vidas humanas. Como ha dicho Brad Smith de Microsoft, "La tecnología de la información plantea problemas que van al corazón de las protecciones fundamentales de los derechos humanos, como la privacidad y la libertad de expresión. Esos problemas aumentan las responsabilidades de las empresas de tecnología que crean estos productos. En nuestra opinión, también exige regulación gubernamental reflexiva y para el desarrollo de normas sobre usos aceptables" ([fuente](https://www.technologyreview.com/2019/12/18/102365/the-future-of-ais-impact-on-society/)).
Queda por ver qué depara el futuro, pero es importante entender estos sistemas informáticos y el software y algortimos que ejecutan. Esperamos que este plan de estudios le ayude a comprender mejor para que pueda decidir por si mismo.
[![La historia del deep learning](https://img.youtube.com/vi/mTtDfKgLm54/0.jpg)](https://www.youtube.com/watch?v=mTtDfKgLm54 "The history of deep learning")
> 🎥 Haga Click en la imagen de arriba para ver un video: Yann LeCun analiza la historia del deep learning en esta conferencia
---
## 🚀Desafío
Sumérjase dentro de unos de estos momentos históricos y aprenda más sobre las personas detrás de ellos. Hay personajes fascinantes y nunca se creó ningún descubrimiento científico en un vacío cultural. ¿Qué descubres?
## [Cuestionario posterior a la conferencia](https://white-water-09ec41f0f.azurestaticapps.net/quiz/4/)
## Revisión y autoestudio
Aquí hay elementos para ver y escuchar:
[Este podcast donde Amy Boyd habla sobre la evolución de la IA](http://runasradio.com/Shows/Show/739)
[![La historia de la IA por Amy Boyd](https://img.youtube.com/vi/EJt3_bFYKss/0.jpg)](https://www.youtube.com/watch?v=EJt3_bFYKss "La historia de la IA por Amy Boyd")
## Asignación
[Crea un timeline](assignment.md)

@ -0,0 +1,117 @@
# Histoire du Machine Learning (apprentissage automatique)
![Résumé de l'histoire du machine learning dans un sketchnote](../../../sketchnotes/ml-history.png)
> Sketchnote de [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Quizz préalable](https://white-water-09ec41f0f.azurestaticapps.net/quiz/3?loc=fr)
Dans cette leçon, nous allons parcourir les principales étapes de l'histoire du machine learning et de l'intelligence artificielle.
L'histoire de l'intelligence artificielle, l'IA, en tant que domaine est étroitement liée à l'histoire du machine learning, car les algorithmes et les avancées informatiques qui sous-tendent le ML alimentent le développement de l'IA. Bien que ces domaines en tant que domaines de recherches distincts ont commencé à se cristalliser dans les années 1950, il est important de rappeler que les [découvertes algorithmiques, statistiques, mathématiques, informatiques et techniques](https://wikipedia.org/wiki/Timeline_of_machine_learning) ont précédé et chevauchait cette époque. En fait, le monde réfléchit à ces questions depuis [des centaines d'années](https://fr.wikipedia.org/wiki/Histoire_de_l%27intelligence_artificielle) : cet article traite des fondements intellectuels historiques de l'idée d'une « machine qui pense ».
## Découvertes notables
- 1763, 1812 [théorème de Bayes](https://wikipedia.org/wiki/Bayes%27_theorem) et ses prédécesseurs. Ce théorème et ses applications sous-tendent l'inférence, décrivant la probabilité qu'un événement se produise sur la base de connaissances antérieures.
- 1805 [Théorie des moindres carrés](https://wikipedia.org/wiki/Least_squares) par le mathématicien français Adrien-Marie Legendre. Cette théorie, que vous découvrirez dans notre unité Régression, aide à l'ajustement des données.
- 1913 [Chaînes de Markov](https://wikipedia.org/wiki/Markov_chain) du nom du mathématicien russe Andrey Markov sont utilisées pour décrire une séquence d'événements possibles basée sur un état antérieur.
- 1957 [Perceptron](https://wikipedia.org/wiki/Perceptron) est un type de classificateur linéaire inventé par le psychologue américain Frank Rosenblatt qui sous-tend les progrès de l'apprentissage en profondeur.
- 1967 [Nearest Neighbor](https://wikipedia.org/wiki/Nearest_neighbor) est un algorithme conçu à l'origine pour cartographier les itinéraires. Dans un contexte ML, il est utilisé pour détecter des modèles.
- 1970 [Backpropagation](https://wikipedia.org/wiki/Backpropagation) est utilisé pour former des [réseaux de neurones feedforward (propagation avant)](https://fr.wikipedia.org/wiki/R%C3%A9seau_de_neurones_%C3%A0_propagation_avant).
- 1982 [Réseaux de neurones récurrents](https://wikipedia.org/wiki/Recurrent_neural_network) sont des réseaux de neurones artificiels dérivés de réseaux de neurones à réaction qui créent des graphes temporels.
✅ Faites une petite recherche. Quelles autres dates sont marquantes dans l'histoire du ML et de l'IA ?
## 1950 : Des machines qui pensent
Alan Turing, une personne vraiment remarquable qui a été élue [par le public en 2019](https://wikipedia.org/wiki/Icons:_The_Greatest_Person_of_the_20th_Century) comme le plus grand scientifique du 20e siècle, est reconnu pour avoir aidé à jeter les bases du concept d'une "machine qui peut penser". Il a lutté avec ses opposants et son propre besoin de preuves empiriques de sa théorie en créant le [Test de Turing] (https://www.bbc.com/news/technology-18475646), que vous explorerez dans nos leçons de NLP (TALN en français).
## 1956 : Projet de recherche d'été à Dartmouth
« Le projet de recherche d'été de Dartmouth sur l'intelligence artificielle a été un événement fondateur pour l'intelligence artificielle en tant que domaine », et c'est ici que le terme « intelligence artificielle » a été inventé ([source](https://250.dartmouth.edu/highlights/artificial-intelligence-ai-coined-dartmouth)).
> Chaque aspect de l'apprentissage ou toute autre caractéristique de l'intelligence peut en principe être décrit si précisément qu'une machine peut être conçue pour les simuler.
Le chercheur en tête, le professeur de mathématiques John McCarthy, espérait « procéder sur la base de la conjecture selon laquelle chaque aspect de l'apprentissage ou toute autre caractéristique de l'intelligence peut en principe être décrit avec une telle précision qu'une machine peut être conçue pour les simuler ». Les participants comprenaient une autre sommité dans le domaine, Marvin Minsky.
L'atelier est crédité d'avoir initié et encouragé plusieurs discussions, notamment « l'essor des méthodes symboliques, des systèmes spécialisés sur des domaines limités (premiers systèmes experts) et des systèmes déductifs par rapport aux systèmes inductifs ». ([source](https://fr.wikipedia.org/wiki/Conf%C3%A9rence_de_Dartmouth)).
## 1956 - 1974 : "Les années d'or"
Des années 50 au milieu des années 70, l'optimisme était au rendez-vous en espérant que l'IA puisse résoudre de nombreux problèmes. En 1967, Marvin Minsky a déclaré avec assurance que « Dans une génération... le problème de la création d'"intelligence artificielle" sera substantiellement résolu. » (Minsky, Marvin (1967), Computation: Finite and Infinite Machines, Englewood Cliffs, N.J.: Prentice-Hall)
La recherche sur le Natural Language Processing (traitement du langage naturel en français) a prospéré, la recherche a été affinée et rendue plus puissante, et le concept de « micro-mondes » a été créé, où des tâches simples ont été effectuées en utilisant des instructions en langue naturelle.
La recherche a été bien financée par les agences gouvernementales, des progrès ont été réalisés dans le calcul et les algorithmes, et des prototypes de machines intelligentes ont été construits. Certaines de ces machines incluent :
* [Shakey le robot](https://fr.wikipedia.org/wiki/Shakey_le_robot), qui pouvait manœuvrer et décider comment effectuer des tâches « intelligemment ».
![Shakey, un robot intelligent](../images/shakey.jpg)
> Shaky en 1972
* Eliza, une des premières « chatbot », pouvait converser avec les gens et agir comme une « thérapeute » primitive. Vous en apprendrez plus sur Eliza dans les leçons de NLP.
![Eliza, un bot](../images/eliza.png)
> Une version d'Eliza, un chatbot
* Le « monde des blocs » était un exemple de micro-monde où les blocs pouvaient être empilés et triés, et où des expériences d'apprentissages sur des machines, dans le but qu'elles prennent des décisions, pouvaient être testées. Les avancées réalisées avec des bibliothèques telles que [SHRDLU](https://fr.wikipedia.org/wiki/SHRDLU) ont contribué à faire avancer le natural language processing.
[![Monde de blocs avec SHRDLU](https://img.youtube.com/vi/QAJz4YKUwqw/0.jpg)](https://www.youtube.com/watch?v=QAJz4YKUwqw "Monde de blocs avec SHRDLU" )
> 🎥 Cliquez sur l'image ci-dessus pour une vidéo : Blocks world with SHRDLU
## 1974 - 1980 : « l'hiver de l'IA »
Au milieu des années 1970, il était devenu évident que la complexité de la fabrication de « machines intelligentes » avait été sous-estimée et que sa promesse, compte tenu de la puissance de calcul disponible, avait été exagérée. Les financements se sont taris et la confiance dans le domaine s'est ralentie. Parmi les problèmes qui ont eu un impact sur la confiance, citons :
- **Restrictions**. La puissance de calcul était trop limitée.
- **Explosion combinatoire**. Le nombre de paramètres à former augmentait de façon exponentielle à mesure que l'on en demandait davantage aux ordinateurs, sans évolution parallèle de la puissance et de la capacité de calcul.
- **Pénurie de données**. Il y avait un manque de données qui a entravé le processus de test, de développement et de raffinement des algorithmes.
- **Posions-nous les bonnes questions ?**. Les questions mêmes, qui étaient posées, ont commencé à être remises en question. Les chercheurs ont commencé à émettre des critiques sur leurs approches :
- Les tests de Turing ont été remis en question au moyen, entre autres, de la « théorie de la chambre chinoise » qui postulait que « la programmation d'un ordinateur numérique peut faire croire qu'il comprend le langage mais ne peut pas produire une compréhension réelle ». ([source](https://plato.stanford.edu/entries/chinese-room/))
- L'éthique de l'introduction d'intelligences artificielles telles que la "thérapeute" ELIZA dans la société a été remise en cause.
Dans le même temps, diverses écoles de pensée sur l'IA ont commencé à se former. Une dichotomie a été établie entre les pratiques IA ["scruffy" et "neat"](https://wikipedia.org/wiki/Neats_and_scruffies). Les laboratoires _Scruffy_ peaufinaient leurs programmes pendant des heures jusqu'à ce qu'ils obtiennent les résultats souhaités. Les laboratoires _Neat_ "se concentraient sur la logique et la résolution formelle de problèmes". ELIZA et SHRDLU étaient des systèmes _scruffy_ bien connus. Dans les années 1980, alors qu'émergeait la demande de rendre les systèmes ML reproductibles, l'approche _neat_ a progressivement pris le devant de la scène car ses résultats sont plus explicables.
## 1980 : Systèmes experts
Au fur et à mesure que le domaine s'est développé, ses avantages pour les entreprises sont devenus plus clairs, particulièrement via les « systèmes experts » dans les années 1980. "Les systèmes experts ont été parmi les premières formes vraiment réussies de logiciels d'intelligence artificielle (IA)." ([source](https://fr.wikipedia.org/wiki/Syst%C3%A8me_expert)).
Ce type de système est en fait _hybride_, composé en partie d'un moteur de règles définissant les exigences métier et d'un moteur d'inférence qui exploite le système de règles pour déduire de nouveaux faits.
Cette époque a également vu une attention croissante accordée aux réseaux de neurones.
## 1987 - 1993 : IA « Chill »
La prolifération du matériel spécialisé des systèmes experts a eu pour effet malheureux de devenir trop spécialisée. L'essor des ordinateurs personnels a également concurrencé ces grands systèmes spécialisés et centralisés. La démocratisation de l'informatique a commencé et a finalement ouvert la voie à l'explosion des mégadonnées.
## 1993 - 2011
Cette époque a vu naître une nouvelle ère pour le ML et l'IA afin de résoudre certains des problèmes qui n'avaient pu l'être plus tôt par le manque de données et de puissance de calcul. La quantité de données a commencé à augmenter rapidement et à devenir plus largement disponibles, pour le meilleur et pour le pire, en particulier avec l'avènement du smartphone vers 2007. La puissance de calcul a augmenté de façon exponentielle et les algorithmes ont évolué parallèlement. Le domaine a commencé à gagner en maturité alors que l'ingéniosité a commencé à se cristalliser en une véritable discipline.
## À présent
Aujourd'hui, le machine learning et l'IA touchent presque tous les aspects de notre vie. Cette ère nécessite une compréhension approfondie des risques et des effets potentiels de ces algorithmes sur les vies humaines. Comme l'a déclaré Brad Smith de Microsoft, « les technologies de l'information soulèvent des problèmes qui vont au cœur des protections fondamentales des droits de l'homme comme la vie privée et la liberté d'expression. Ces problèmes accroissent la responsabilité des entreprises technologiques qui créent ces produits. À notre avis, ils appellent également à une réglementation gouvernementale réfléchie et au développement de normes autour des utilisations acceptables" ([source](https://www.technologyreview.com/2019/12/18/102365/the-future-of-ais-impact-on-society/)).
Reste à savoir ce que l'avenir nous réserve, mais il est important de comprendre ces systèmes informatiques ainsi que les logiciels et algorithmes qu'ils exécutent. Nous espérons que ce programme vous aidera à mieux les comprendre afin que vous puissiez décider par vous-même.
[![L'histoire du Deep Learning](https://img.youtube.com/vi/mTtDfKgLm54/0.jpg)](https://www.youtube.com/watch?v=mTtDfKgLm54 "L'histoire du Deep Learning")
> 🎥 Cliquez sur l'image ci-dessus pour une vidéo : Yann LeCun discute de l'histoire du deep learning dans cette conférence
---
## 🚀Challenge
Plongez dans l'un de ces moments historiques et apprenez-en plus sur les personnes derrière ceux-ci. Il y a des personnalités fascinantes, et aucune découverte scientifique n'a jamais été créée avec un vide culturel. Que découvrez-vous ?
## [Quiz de validation des connaissances](https://white-water-09ec41f0f.azurestaticapps.net/quiz/4?loc=fr)
## Révision et auto-apprentissage
Voici quelques articles à regarder et à écouter :
[Ce podcast où Amy Boyd discute de l'évolution de l'IA](http://runasradio.com/Shows/Show/739)
[![L'histoire de l'IA par Amy Boyd](https://img.youtube.com/vi/EJt3_bFYKss/0.jpg)](https://www.youtube.com/watch?v=EJt3_bFYKss "L'histoire de l'IA par Amy Boyd")
## Devoir
[Créer une frise chronologique](assignment.fr.md)

@ -0,0 +1,116 @@
# Sejarah Machine Learning
![Ringkasan dari Sejarah Machine Learning dalam sebuah catatan sketsa](../../../sketchnotes/ml-history.png)
> Catatan sketsa oleh [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Quiz Pra-Pelajaran](https://white-water-09ec41f0f.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, an intelligent robot](../images/shakey.jpg)
> 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.
![Eliza, a bot](../images/eliza.png)
> 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.
[![blocks world dengan SHRDLU](https://img.youtube.com/vi/QAJz4YKUwqw/0.jpg)](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.
[![Sejarah Deep Learning](https://img.youtube.com/vi/mTtDfKgLm54/0.jpg)](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://white-water-09ec41f0f.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)
[![Sejarah AI oleh Amy Boyd](https://img.youtube.com/vi/EJt3_bFYKss/0.jpg)](https://www.youtube.com/watch?v=EJt3_bFYKss "Sejarah AI oleh Amy Boyd")
## Tugas
[Membuat sebuah *timeline*](assignment.id.md)

@ -1,118 +1,118 @@
# Storia di machine learning
![Riepilogo della storia di machine learning in uno sketchnote](../../../sketchnotes/ml-history.png)
> Sketchnote di [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/3/)
In questa lezione, si camminerà attraverso le principali pietre miliari nella storia di machine learning e dell'intelligenza artificiale.
La storia dell'intelligenza artificiale, AI, come campo è intrecciata con la storia di machine learning, poiché gli algoritmi e i progressi computazionali alla base di machine learning hanno contribuito allo sviluppo dell'intelligenza artificiale. È utile ricordare che, mentre questi campi come distinte aree di indagine hanno cominciato a cristallizzarsi negli anni '50, importanti [scoperte algoritmiche, statistiche, matematiche, computazionali e tecniche](https://wikipedia.org/wiki/Timeline_of_machine_learning) hanno preceduto e si sono sovrapposte a questa era. In effetti, le persone hanno riflettuto su queste domande per [centinaia di anni](https://wikipedia.org/wiki/History_of_artificial_intelligence); questo articolo discute le basi intellettuali storiche dell'idea di una "macchina pensante".
## Scoperte rilevanti
- 1763, 1812 [Teorema di Bayes](https://it.wikipedia.org/wiki/Teorema_di_Bayes) e suoi predecessori. Questo teorema e le sue applicazioni sono alla base dell'inferenza, descrivendo la probabilità che un evento si verifichi in base alla conoscenza precedente.
- 1805 [Metodo dei Minimi Quadrati](https://it.wikipedia.org/wiki/Metodo_dei_minimi_quadrati) del matematico francese Adrien-Marie Legendre. Questa teoria, che verrà trattata nell'unità Regressione, aiuta nell'adattamento dei dati.
- 1913 [Processo Markoviano](https://it.wikipedia.org/wiki/Processo_markoviano) dal nome del matematico russo Andrey Markov è usato per descrivere una sequenza di possibili eventi basati su uno stato precedente.
- 1957 [Percettrone](https://it.wikipedia.org/wiki/Percettrone) è un tipo di classificatore lineare inventato dallo psicologo americano Frank Rosenblatt che sta alla base dei progressi nel deep learning.
- 1967 [Nearest Neighbor](https://wikipedia.org/wiki/Nearest_neighbor) è un algoritmo originariamente progettato per mappare i percorsi. In un contesto ML viene utilizzato per rilevare i modelli.
- 1970 [La Retropropagazione dell'Errore](https://it.wikipedia.org/wiki/Retropropagazione_dell'errore) viene utilizzata per addestrare [le reti neurali feed-forward](https://it.wikipedia.org/wiki/Rete_neurale_feed-forward).
- Le [Reti Neurali Ricorrenti](https://it.wikipedia.org/wiki/Rete_neurale_ricorrente) del 1982 sono reti neurali artificiali derivate da reti neurali feedforward che creano grafici temporali.
✅ Fare una piccola ricerca. Quali altre date si distinguono come fondamentali nella storia del machine learning e dell'intelligenza artificiale?
## 1950: Macchine che pensano
Alan Turing, una persona davvero notevole che è stata votata [dal pubblico nel 2019](https://wikipedia.org/wiki/Icons:_The_Greatest_Person_of_the_20th_Century) come il più grande scienziato del XX secolo, è accreditato per aver contribuito a gettare le basi per il concetto di "macchina in grado di pensare". Ha affrontato gli oppositori e il suo stesso bisogno di prove empiriche di questo concetto in parte creando il [Test di Turing](https://www.bbc.com/news/technology-18475646), che verrà esplorato nelle lezioni di NLP (elaborazione del linguaggio naturale).
## 1956: Progetto di Ricerca Estivo Dartmouth
"Il Dartmouth Summer Research Project sull'intelligenza artificiale è stato un evento seminale per l'intelligenza artificiale come campo", qui è stato coniato il termine "intelligenza artificiale" ([fonte](https://250.dartmouth.edu/highlights/artificial-intelligence-ai-coined-dartmouth)).
> In linea di principio, ogni aspetto dell'apprendimento o qualsiasi altra caratteristica dell'intelligenza può essere descritto in modo così preciso che si può costruire una macchina per simularlo.
Il ricercatore capo, il professore di matematica John McCarthy, sperava "di procedere sulla base della congettura che ogni aspetto dell'apprendimento o qualsiasi altra caratteristica dell'intelligenza possa in linea di principio essere descritta in modo così preciso che si possa costruire una macchina per simularlo". I partecipanti includevano un altro luminare nel campo, Marvin Minsky.
Il workshop è accreditato di aver avviato e incoraggiato diverse discussioni tra cui "l'ascesa di metodi simbolici, sistemi focalizzati su domini limitati (primi sistemi esperti) e sistemi deduttivi contro sistemi induttivi". ([fonte](https://wikipedia.org/wiki/Dartmouth_workshop)).
## 1956 - 1974: "Gli anni d'oro"
Dagli anni '50 fino alla metà degli anni '70, l'ottimismo era alto nella speranza che l'AI potesse risolvere molti problemi. Nel 1967, Marvin Minsky dichiarò con sicurezza che "Entro una generazione... il problema della creazione di 'intelligenza artificiale' sarà sostanzialmente risolto". (Minsky, Marvin (1967), Computation: Finite and Infinite Machines, Englewood Cliffs, N.J.: Prentice-Hall)
La ricerca sull'elaborazione del linguaggio naturale è fiorita, la ricerca è stata perfezionata e resa più potente ed è stato creato il concetto di "micro-mondi", in cui compiti semplici sono stati completati utilizzando istruzioni in linguaggio semplice.
La ricerca è stata ben finanziata dalle agenzie governative, sono stati fatti progressi nel calcolo e negli algoritmi e sono stati costruiti prototipi di macchine intelligenti. Alcune di queste macchine includono:
* [Shakey il robot](https://wikipedia.org/wiki/Shakey_the_robot), che poteva manovrare e decidere come eseguire i compiti "intelligentemente".
![Shakey, un robot intelligente](../images/shakey.jpg)
> Shakey nel 1972
* Eliza, una delle prime "chatterbot", poteva conversare con le persone e agire come una "terapeuta" primitiva. Si Imparerà di più su Eliza nelle lezioni di NLP.
![Eliza, un bot](../images/eliza.png)
> Una versione di Eliza, un chatbot
* Il "mondo dei blocchi" era un esempio di un micromondo in cui i blocchi potevano essere impilati e ordinati e si potevano testare esperimenti su macchine per insegnare a prendere decisioni. I progressi realizzati con librerie come [SHRDLU](https://it.wikipedia.org/wiki/SHRDLU) hanno contribuito a far progredire l'elaborazione del linguaggio.
[![Il mondo dei blocchi con SHRDLU](https://img.youtube.com/vi/QAJz4YKUwqw/0.jpg)](https://www.youtube.com/watch?v=QAJz4YKUwqw "Il mondo dei blocchi con SHRDLU")
> 🎥 Fare clic sull'immagine sopra per un video: Blocks world con SHRDLU
## 1974 - 1980: "L'inverno dell'AI"
Verso la metà degli anni '70, era diventato evidente che la complessità della creazione di "macchine intelligenti" era stata sottovalutata e che la sua promessa, data la potenza di calcolo disponibile, era stata esagerata. I finanziamenti si sono prosciugati e la fiducia nel settore è rallentata. Alcuni problemi che hanno influito sulla fiducia includono:
- **Limitazioni**. La potenza di calcolo era troppo limitata.
- **Esplosione combinatoria**. La quantità di parametri necessari per essere addestrati è cresciuta in modo esponenziale man mano che veniva chiesto di più ai computer, senza un'evoluzione parallela della potenza e delle capacità di calcolo.
- **Scarsità di dati**. C'era una scarsità di dati che ostacolava il processo di test, sviluppo e perfezionamento degli algoritmi.
- **Stiamo facendo le domande giuste?**. Le stesse domande che venivano poste cominciarono ad essere messe in discussione. I ricercatori hanno iniziato a criticare i loro approcci:
- I test di Turing furono messi in discussione attraverso, tra le altre idee, la "teoria della stanza cinese" che postulava che "la programmazione di un computer digitale può far sembrare che capisca il linguaggio ma non potrebbe produrre una vera comprensione". ([fonte](https://plato.stanford.edu/entries/chinese-room/))
- L'etica dell'introduzione di intelligenze artificiali come la "terapeuta" ELIZA nella società è stata messa in discussione.
Allo stesso tempo, iniziarono a formarsi varie scuole di pensiero sull'AI. È stata stabilita una dicotomia tra pratiche ["scruffy" contro "neat AI"](https://wikipedia.org/wiki/Neats_and_scruffies). I laboratori _scruffy_ ottimizzavano i programmi per ore fino a quando non ottenevano i risultati desiderati. I laboratori _Neat_ "si focalizzavano sulla logica e sulla risoluzione formale dei problemi". ELIZA e SHRDLU erano ben noti _sistemi scruffy_. Negli anni '80, quando è emersa la richiesta di rendere riproducibili i sistemi ML, l'_approccio neat_ ha gradualmente preso il sopravvento in quanto i suoi risultati sono più spiegabili.
## Sistemi esperti degli anni '80
Man mano che il settore cresceva, i suoi vantaggi per le imprese diventavano più chiari e negli anni '80 lo stesso accadeva con la proliferazione di "sistemi esperti". "I sistemi esperti sono stati tra le prime forme di software di intelligenza artificiale (AI) di vero successo". ([fonte](https://wikipedia.org/wiki/Expert_system)).
Questo tipo di sistema è in realtà _ibrido_, costituito in parte da un motore di regole che definisce i requisiti aziendali e un motore di inferenza che sfrutta il sistema di regole per dedurre nuovi fatti.
Questa era ha visto anche una crescente attenzione rivolta alle reti neurali.
## 1987 - 1993: AI 'Chill'
La proliferazione di hardware specializzato per sistemi esperti ha avuto lo sfortunato effetto di diventare troppo specializzato. L'ascesa dei personal computer ha anche gareggiato con questi grandi sistemi centralizzati specializzati. La democratizzazione dell'informatica era iniziata e alla fine ha spianato la strada alla moderna esplosione dei big data.
## 1993 - 2011
Questa epoca ha visto una nuova era per ML e AI per essere in grado di risolvere alcuni dei problemi che erano stati causati in precedenza dalla mancanza di dati e potenza di calcolo. La quantità di dati ha iniziato ad aumentare rapidamente e a diventare più ampiamente disponibile, nel bene e nel male, soprattutto con l'avvento degli smartphone intorno al 2007. La potenza di calcolo si è ampliata in modo esponenziale e gli algoritmi si sono evoluti di pari passo. Il campo ha iniziato a maturare quando i giorni a ruota libera del passato hanno iniziato a cristallizzarsi in una vera disciplina.
## Adesso
Oggi, machine learning e intelligenza artificiale toccano quasi ogni parte della nostra vita. Questa era richiede un'attenta comprensione dei rischi e dei potenziali effetti di questi algoritmi sulle vite umane. Come ha affermato Brad Smith di Microsoft, "La tecnologia dell'informazione solleva questioni che vanno al cuore delle protezioni fondamentali dei diritti umani come la privacy e la libertà di espressione. Questi problemi aumentano la responsabilità delle aziende tecnologiche che creano questi prodotti. A nostro avviso, richiedono anche un'attenta regolamentazione del governo e lo sviluppo di norme sugli usi accettabili" ([fonte](https://www.technologyreview.com/2019/12/18/102365/the-future-of-ais-impact-on-society/)).
Resta da vedere cosa riserva il futuro, ma è importante capire questi sistemi informatici e il software e gli algoritmi che eseguono. Ci si augura che questo programma di studi aiuti ad acquisire una migliore comprensione in modo che si possa decidere in autonomia.
[![La storia del deeplearningLa](https://img.youtube.com/vi/mTtDfKgLm54/0.jpg)](https://www.youtube.com/watch?v=mTtDfKgLm54 " storia del deep learning")
> 🎥 Fare clic sull'immagine sopra per un video: Yann LeCun discute la storia del deep learning in questa lezione
---
## 🚀 Sfida
Approfondire uno di questi momenti storici e scoprire
di più sulle persone che stanno dietro ad essi. Ci sono personaggi affascinanti e nessuna scoperta scientifica è mai stata creata in un vuoto culturale. Cosa si è scoperto?
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/4/)
## Revisione e Auto Apprendimento
Ecco gli elementi da guardare e ascoltare:
[Questo podcast in cui Amy Boyd discute l'evoluzione dell'AI](http://runasradio.com/Shows/Show/739)
[![La storia dell'AI di Amy Boyd](https://img.youtube.com/vi/EJt3_bFYKss/0.jpg)](https://www.youtube.com/watch?v=EJt3_bFYKss "La storia dell'AI di Amy Boyd")
## Compito
[Creare una sequenza temporale](assignment.it.md)
# Storia di machine learning
![Riepilogo della storia di machine learning in uno sketchnote](../../../sketchnotes/ml-history.png)
> Sketchnote di [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Quiz pre-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/3/?loc=it)
In questa lezione, si camminerà attraverso le principali pietre miliari nella storia di machine learning e dell'intelligenza artificiale.
La storia dell'intelligenza artificiale, AI, come campo è intrecciata con la storia di machine learning, poiché gli algoritmi e i progressi computazionali alla base di machine learning hanno contribuito allo sviluppo dell'intelligenza artificiale. È utile ricordare che, mentre questi campi come distinte aree di indagine hanno cominciato a cristallizzarsi negli anni '50, importanti [scoperte algoritmiche, statistiche, matematiche, computazionali e tecniche](https://wikipedia.org/wiki/Timeline_of_machine_learning) hanno preceduto e si sono sovrapposte a questa era. In effetti, le persone hanno riflettuto su queste domande per [centinaia di anni](https://wikipedia.org/wiki/History_of_artificial_intelligence); questo articolo discute le basi intellettuali storiche dell'idea di una "macchina pensante".
## Scoperte rilevanti
- 1763, 1812 [Teorema di Bayes](https://it.wikipedia.org/wiki/Teorema_di_Bayes) e suoi predecessori. Questo teorema e le sue applicazioni sono alla base dell'inferenza, descrivendo la probabilità che un evento si verifichi in base alla conoscenza precedente.
- 1805 [Metodo dei Minimi Quadrati](https://it.wikipedia.org/wiki/Metodo_dei_minimi_quadrati) del matematico francese Adrien-Marie Legendre. Questa teoria, che verrà trattata nell'unità Regressione, aiuta nell'adattamento dei dati.
- 1913 [Processo Markoviano](https://it.wikipedia.org/wiki/Processo_markoviano) dal nome del matematico russo Andrey Markov è usato per descrivere una sequenza di possibili eventi basati su uno stato precedente.
- 1957 [Percettrone](https://it.wikipedia.org/wiki/Percettrone) è un tipo di classificatore lineare inventato dallo psicologo americano Frank Rosenblatt che sta alla base dei progressi nel deep learning.
- 1967 [Nearest Neighbor](https://wikipedia.org/wiki/Nearest_neighbor) è un algoritmo originariamente progettato per mappare i percorsi. In un contesto ML viene utilizzato per rilevare i modelli.
- 1970 [La Retropropagazione dell'Errore](https://it.wikipedia.org/wiki/Retropropagazione_dell'errore) viene utilizzata per addestrare [le reti neurali feed-forward](https://it.wikipedia.org/wiki/Rete_neurale_feed-forward).
- Le [Reti Neurali Ricorrenti](https://it.wikipedia.org/wiki/Rete_neurale_ricorrente) del 1982 sono reti neurali artificiali derivate da reti neurali feedforward che creano grafici temporali.
✅ Fare una piccola ricerca. Quali altre date si distinguono come fondamentali nella storia del machine learning e dell'intelligenza artificiale?
## 1950: Macchine che pensano
Alan Turing, una persona davvero notevole che è stata votata [dal pubblico nel 2019](https://wikipedia.org/wiki/Icons:_The_Greatest_Person_of_the_20th_Century) come il più grande scienziato del XX secolo, è accreditato per aver contribuito a gettare le basi per il concetto di "macchina in grado di pensare". Ha affrontato gli oppositori e il suo stesso bisogno di prove empiriche di questo concetto in parte creando il [Test di Turing](https://www.bbc.com/news/technology-18475646), che verrà esplorato nelle lezioni di NLP (elaborazione del linguaggio naturale).
## 1956: Progetto di Ricerca Estivo Dartmouth
"Il Dartmouth Summer Research Project sull'intelligenza artificiale è stato un evento seminale per l'intelligenza artificiale come campo", qui è stato coniato il termine "intelligenza artificiale" ([fonte](https://250.dartmouth.edu/highlights/artificial-intelligence-ai-coined-dartmouth)).
> In linea di principio, ogni aspetto dell'apprendimento o qualsiasi altra caratteristica dell'intelligenza può essere descritto in modo così preciso che si può costruire una macchina per simularlo.
Il ricercatore capo, il professore di matematica John McCarthy, sperava "di procedere sulla base della congettura che ogni aspetto dell'apprendimento o qualsiasi altra caratteristica dell'intelligenza possa in linea di principio essere descritta in modo così preciso che si possa costruire una macchina per simularlo". I partecipanti includevano un altro luminare nel campo, Marvin Minsky.
Il workshop è accreditato di aver avviato e incoraggiato diverse discussioni tra cui "l'ascesa di metodi simbolici, sistemi focalizzati su domini limitati (primi sistemi esperti) e sistemi deduttivi contro sistemi induttivi". ([fonte](https://wikipedia.org/wiki/Dartmouth_workshop)).
## 1956 - 1974: "Gli anni d'oro"
Dagli anni '50 fino alla metà degli anni '70, l'ottimismo era alto nella speranza che l'AI potesse risolvere molti problemi. Nel 1967, Marvin Minsky dichiarò con sicurezza che "Entro una generazione... il problema della creazione di 'intelligenza artificiale' sarà sostanzialmente risolto". (Minsky, Marvin (1967), Computation: Finite and Infinite Machines, Englewood Cliffs, N.J.: Prentice-Hall)
La ricerca sull'elaborazione del linguaggio naturale è fiorita, la ricerca è stata perfezionata e resa più potente ed è stato creato il concetto di "micro-mondi", in cui compiti semplici sono stati completati utilizzando istruzioni in linguaggio semplice.
La ricerca è stata ben finanziata dalle agenzie governative, sono stati fatti progressi nel calcolo e negli algoritmi e sono stati costruiti prototipi di macchine intelligenti. Alcune di queste macchine includono:
* [Shakey il robot](https://wikipedia.org/wiki/Shakey_the_robot), che poteva manovrare e decidere come eseguire i compiti "intelligentemente".
![Shakey, un robot intelligente](../images/shakey.jpg)
> Shakey nel 1972
* Eliza, una delle prime "chatterbot", poteva conversare con le persone e agire come una "terapeuta" primitiva. Si Imparerà di più su Eliza nelle lezioni di NLP.
![Eliza, un bot](../images/eliza.png)
> Una versione di Eliza, un chatbot
* Il "mondo dei blocchi" era un esempio di un micromondo in cui i blocchi potevano essere impilati e ordinati e si potevano testare esperimenti su macchine per insegnare a prendere decisioni. I progressi realizzati con librerie come [SHRDLU](https://it.wikipedia.org/wiki/SHRDLU) hanno contribuito a far progredire l'elaborazione del linguaggio.
[![Il mondo dei blocchi con SHRDLU](https://img.youtube.com/vi/QAJz4YKUwqw/0.jpg)](https://www.youtube.com/watch?v=QAJz4YKUwqw "Il mondo dei blocchi con SHRDLU")
> 🎥 Fare clic sull'immagine sopra per un video: Blocks world con SHRDLU
## 1974 - 1980: "L'inverno dell'AI"
Verso la metà degli anni '70, era diventato evidente che la complessità della creazione di "macchine intelligenti" era stata sottovalutata e che la sua promessa, data la potenza di calcolo disponibile, era stata esagerata. I finanziamenti si sono prosciugati e la fiducia nel settore è rallentata. Alcuni problemi che hanno influito sulla fiducia includono:
- **Limitazioni**. La potenza di calcolo era troppo limitata.
- **Esplosione combinatoria**. La quantità di parametri necessari per essere addestrati è cresciuta in modo esponenziale man mano che veniva chiesto di più ai computer, senza un'evoluzione parallela della potenza e delle capacità di calcolo.
- **Scarsità di dati**. C'era una scarsità di dati che ostacolava il processo di test, sviluppo e perfezionamento degli algoritmi.
- **Stiamo facendo le domande giuste?**. Le stesse domande che venivano poste cominciarono ad essere messe in discussione. I ricercatori hanno iniziato a criticare i loro approcci:
- I test di Turing furono messi in discussione attraverso, tra le altre idee, la "teoria della stanza cinese" che postulava che "la programmazione di un computer digitale può far sembrare che capisca il linguaggio ma non potrebbe produrre una vera comprensione". ([fonte](https://plato.stanford.edu/entries/chinese-room/))
- L'etica dell'introduzione di intelligenze artificiali come la "terapeuta" ELIZA nella società è stata messa in discussione.
Allo stesso tempo, iniziarono a formarsi varie scuole di pensiero sull'AI. È stata stabilita una dicotomia tra pratiche ["scruffy" contro "neat AI"](https://wikipedia.org/wiki/Neats_and_scruffies). I laboratori _scruffy_ ottimizzavano i programmi per ore fino a quando non ottenevano i risultati desiderati. I laboratori _Neat_ "si focalizzavano sulla logica e sulla risoluzione formale dei problemi". ELIZA e SHRDLU erano ben noti _sistemi scruffy_. Negli anni '80, quando è emersa la richiesta di rendere riproducibili i sistemi ML, l'_approccio neat_ ha gradualmente preso il sopravvento in quanto i suoi risultati sono più spiegabili.
## Sistemi esperti degli anni '80
Man mano che il settore cresceva, i suoi vantaggi per le imprese diventavano più chiari e negli anni '80 lo stesso accadeva con la proliferazione di "sistemi esperti". "I sistemi esperti sono stati tra le prime forme di software di intelligenza artificiale (AI) di vero successo". ([fonte](https://wikipedia.org/wiki/Expert_system)).
Questo tipo di sistema è in realtà _ibrido_, costituito in parte da un motore di regole che definisce i requisiti aziendali e un motore di inferenza che sfrutta il sistema di regole per dedurre nuovi fatti.
Questa era ha visto anche una crescente attenzione rivolta alle reti neurali.
## 1987 - 1993: AI 'Chill'
La proliferazione di hardware specializzato per sistemi esperti ha avuto lo sfortunato effetto di diventare troppo specializzato. L'ascesa dei personal computer ha anche gareggiato con questi grandi sistemi centralizzati specializzati. La democratizzazione dell'informatica era iniziata e alla fine ha spianato la strada alla moderna esplosione dei big data.
## 1993 - 2011
Questa epoca ha visto una nuova era per ML e AI per essere in grado di risolvere alcuni dei problemi che erano stati causati in precedenza dalla mancanza di dati e potenza di calcolo. La quantità di dati ha iniziato ad aumentare rapidamente e a diventare più ampiamente disponibile, nel bene e nel male, soprattutto con l'avvento degli smartphone intorno al 2007. La potenza di calcolo si è ampliata in modo esponenziale e gli algoritmi si sono evoluti di pari passo. Il campo ha iniziato a maturare quando i giorni a ruota libera del passato hanno iniziato a cristallizzarsi in una vera disciplina.
## Adesso
Oggi, machine learning e intelligenza artificiale toccano quasi ogni parte della nostra vita. Questa era richiede un'attenta comprensione dei rischi e dei potenziali effetti di questi algoritmi sulle vite umane. Come ha affermato Brad Smith di Microsoft, "La tecnologia dell'informazione solleva questioni che vanno al cuore delle protezioni fondamentali dei diritti umani come la privacy e la libertà di espressione. Questi problemi aumentano la responsabilità delle aziende tecnologiche che creano questi prodotti. A nostro avviso, richiedono anche un'attenta regolamentazione del governo e lo sviluppo di norme sugli usi accettabili" ([fonte](https://www.technologyreview.com/2019/12/18/102365/the-future-of-ais-impact-on-society/)).
Resta da vedere cosa riserva il futuro, ma è importante capire questi sistemi informatici e il software e gli algoritmi che eseguono. Ci si augura che questo programma di studi aiuti ad acquisire una migliore comprensione in modo che si possa decidere in autonomia.
[![La storia del deeplearningLa](https://img.youtube.com/vi/mTtDfKgLm54/0.jpg)](https://www.youtube.com/watch?v=mTtDfKgLm54 " storia del deep learning")
> 🎥 Fare clic sull'immagine sopra per un video: Yann LeCun discute la storia del deep learning in questa lezione
---
## 🚀 Sfida
Approfondire uno di questi momenti storici e scoprire
di più sulle persone che stanno dietro ad essi. Ci sono personaggi affascinanti e nessuna scoperta scientifica è mai stata creata in un vuoto culturale. Cosa si è scoperto?
## [Quiz post-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/4/?loc=it)
## Revisione e Auto Apprendimento
Ecco gli elementi da guardare e ascoltare:
[Questo podcast in cui Amy Boyd discute l'evoluzione dell'AI](http://runasradio.com/Shows/Show/739)
[![La storia dell'AI di Amy Boyd](https://img.youtube.com/vi/EJt3_bFYKss/0.jpg)](https://www.youtube.com/watch?v=EJt3_bFYKss "La storia dell'AI di Amy Boyd")
## Compito
[Creare una sequenza temporale](assignment.it.md)

@ -3,7 +3,7 @@
![機械学習の歴史をまとめたスケッチ](../../../sketchnotes/ml-history.png)
> [Tomomi Imura](https://www.twitter.com/girlie_mac)によるスケッチ
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/3/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/3?loc=ja)
この授業では、機械学習と人工知能の歴史における主要な出来事を紹介します。
@ -99,7 +99,7 @@
これらの歴史的瞬間の1つを掘り下げて、その背後にいる人々について学びましょう。魅力的な人々がいますし、文化的に空白の状態で科学的発見がなされたことはありません。どういったことが見つかるでしょうか?
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/4/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/4?loc=ja)
## 振り返りと自習
@ -111,4 +111,4 @@
## 課題
[時系列を制作してください](../assignment.md)
[年表を作成する](./assignment.ja.md)

@ -0,0 +1,118 @@
# 머신러닝의 역사
![Summary of History of machine learning in a sketchnote](../../../sketchnotes/ml-history.png)
> Sketchnote by [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [강의 전 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/3/)
이 강의에서, 머신러닝과 인공 지능의 역사에서 주요 마일스톤을 살펴보려 합니다.
인공 지능, AI의 역사는 머신러닝의 역사와 서로 엮여 있으며, ML을 받쳐주는 알고리즘과 계산 기술이 AI의 개발에 기여했습니다. 독특한 탐구 영역으로 이런 분야는 1950년에 구체적으로 시작했지만, 중요한 [algorithmical, statistical, mathematical, computational and technical discoveries](https://wikipedia.org/wiki/Timeline_of_machine_learning)로 이 시대를 오버랩했다고 생각하는 게 유용합니다. 실제로, 사람들은 [hundreds of years](https://wikipedia.org/wiki/History_of_artificial_intelligence)동안 이 질문을 생각해왔습니다: 이 아티클은 'thinking machine'라는 개념의 역사적 지적 토대에 대하여 이야기 합니다.
## 주목할 발견
- 1763, 1812 [Bayes Theorem](https://wikipedia.org/wiki/Bayes%27_theorem)과 전임자. 이 정리와 적용은 사전지식 기반으로 이벤트가 발생할 확률을 설명할 추론의 기초가 됩니다.
- 1805 [Least Square Theory](https://wikipedia.org/wiki/Least_squares) by 프랑스 수학자 Adrien-Marie Legendre. Regression 단위에서 배울 이 이론은, 데이터 피팅에 도움이 됩니다.
- 1913 러시아 수학자 Andrey Markov의 이름에서 유래된 [Markov Chains](https://wikipedia.org/wiki/Markov_chain)는 이전 상태를 기반으로 가능한 이벤트의 시퀀스를 설명하는 데 사용됩니다.
- 1957 [Perceptron](https://wikipedia.org/wiki/Perceptron)은 미국 심리학자 Frank Rosenblatt이 개발한 linear classifier의 한 타입으로 딥러닝 발전을 뒷받칩니다.
- 1967 [Nearest Neighbor](https://wikipedia.org/wiki/Nearest_neighbor)는 원래 경로를 맵핑하기 위한 알고리즘입니다. ML context에서 패턴을 감지할 때 사용합니다.
- 1970 [Backpropagation](https://wikipedia.org/wiki/Backpropagation)은 [feedforward neural networks](https://wikipedia.org/wiki/Feedforward_neural_network)를 학습할 때 사용합니다.
- 1982 [Recurrent Neural Networks](https://wikipedia.org/wiki/Recurrent_neural_network)는 시간 그래프를 생성하는 feedforward neural networks에서 파생한 인공 신경망입니다.
✅ 조금 조사해보세요. ML과 AI의 역사에서 중요한 다른 날짜는 언제인가요?
## 1950: 생각하는 기계
20세기의 최고 과학자로 [by the public in 2019](https://wikipedia.org/wiki/Icons:_The_Greatest_Person_of_the_20th_Century)에 선택된, Alan Turing은, 'machine that can think.'라는 개념의 기반을 구축하는 데에 기여한 것으로 평가되고 있습니다.
NLP 강의에서 살필 [Turing Test](https://www.bbc.com/news/technology-18475646)를 만들어서 부분적으로 이 개념에 대한 경험적인 반대하는 사람들과 대립했습니다.
## 1956: Dartmouth 여름 연구 프로젝트
"The Dartmouth Summer Research Project on artificial intelligence was a seminal event for artificial intelligence as a field," ([source](https://250.dartmouth.edu/highlights/artificial-intelligence-ai-coined-dartmouth))에서 "인공 지능"이라는 용어가 만들어졌습니다.
> 학습의 모든 측면이나 지능의 다른 기능은 원칙적으로 정확하게 서술할 수 있어서 이를 따라 할 기계를 만들 수 있습니다.
수석 연구원인, 수학 교수 John McCarthy는, "to proceed on the basis of the conjecture that every aspect of learning or any other feature of intelligence can in principle be so precisely described that a machine can be made to simulate it."이라고 희망했습니다. 참가한 사람들 중에서는 Marvin Minsky도 있었습니다.
이 워크숍은 "the rise of symbolic methods, systems focussed on limited domains (early expert systems), and deductive systems versus inductive systems." ([source](https://wikipedia.org/wiki/Dartmouth_workshop))을 포함해서 여러 토론을 시작하고 장려한 것으로 평가됩니다.
## 1956 - 1974: "The golden years"
1950년대부터 70년대 중순까지 AI로 많은 문제를 해결할 수 있다고 믿은 낙관주의가 커졌습니다. 1967년 Marvin Minsky는 "Within a generation ... the problem of creating 'artificial intelligence' will substantially be solved." (Minsky, Marvin (1967), Computation: Finite and Infinite Machines, Englewood Cliffs, N.J.: Prentice-Hall)이라고 자신있게 말했습니다.
natural language processing 연구가 발전하고, 검색이 개선되어 더 강력해졌으며, 단순한 언어 지침으로 간단한 작업을 완료하는 'micro-worlds'라는 개념이 생겼습니다.
정부 지원을 받으며 연구했으며, 계산과 알고리즘이 발전하면서, 지능적 기계의 프로토 타입이 만들어졌습니다. 이런 기계 중에 일부는 아래와 같습니다:
* [Shakey the robot](https://wikipedia.org/wiki/Shakey_the_robot), '지능적'으로 작업하는 방법을 조종하고 결정할 수 있습니다.
![Shakey, an intelligent robot](../images/shakey.jpg)
> Shakey in 1972
* 초기 'chatterbot'인, Eliza는, 사람들과 이야기하고 원시적 '치료사' 역할을 할 수 있었습니다. NLP 강의에서 Eliza에 대하여 자세히 알아봅시다.
![Eliza, a bot](../images/eliza.png)
> A version of Eliza, a chatbot
* "Blocks world"는 블록을 쌓고 분류할 수 있는 마이크로-월드의 예시이며, 결정하는 기계를 가르칠 실험을 테스트할 수 있었습니다. [SHRDLU](https://wikipedia.org/wiki/SHRDLU)와 같은 라이브러리로 만들어진 발명은 language processing를 발전시키는 데 도움이 되었습니다.
[![blocks world with SHRDLU](https://img.youtube.com/vi/QAJz4YKUwqw/0.jpg)](https://www.youtube.com/watch?v=QAJz4YKUwqw "blocks world with SHRDLU")
> 🎥 영상을 보려면 이미지 클릭: Blocks world with SHRDLU
## 1974 - 1980: "AI Winter"
1970년 중순에, '인공 기계'를 만드는 복잡도가 과소 평가되면서, 주어진 컴퓨터 파워를 고려해보니, 그 약속은 과장된 것이 분명해졌습니다. 자금이 고갈되고 현장에 대한 자신감도 느려졌습니다. 신뢰에 영향을 준 이슈는 아래에 있습니다:
- **제한**. 컴퓨터 성능이 너무 제한되었습니다.
- **결합 파열**. 훈련에 필요한 파라미터의 양이 컴퓨터 성능, 기능과 별개로 컴퓨터의 요청에 따라 늘어났습니다.
- **데이터 부족**. 알고리즘을 테스트, 개발, 그리고 개선할 수 없게 데이터가 부족했습니다.
- **올바른 질문인가요?**. 질문받은 그 질문에 바로 물었습니다. 연구원들은 그 접근 방식에 비판했습니다:
- 튜링 테스트는 "programming a digital computer may make it appear to understand language but could not produce real understanding." ([source](https://plato.stanford.edu/entries/chinese-room/))하다고 가정한, 'chinese room theory'의 다른 아이디어에 의해 의문이 생겼습니다.
- "치료사" ELIZA와 같은 인공 지능을 사회에 도입하며 윤리에 도전했습니다.
동 시간대에, 다양한 AI 학교가 형성되기 시작했습니다. ["scruffy" vs. "neat AI"](https://wikipedia.org/wiki/Neats_and_scruffies) 사이에 이분법이 확립되었습니다. _Scruffy_ 연구실은 원하는 결과를 얻을 때까지 몇 시간 동안 프로그램을 트윅했습니다. _Neat_ 연구실은 논리와 공식적 문제를 해결하는 데에 초점을 맞추었습니다. ELIZA와 SHRDLU는 잘 알려진 _scruffy_ 시스템입니다. 1980년대에, ML 시스템을 재현할 수 있어야 된다는 요구사항이 생겼고, _neat_ 방식이 더 결과를 설명할 수 있어서 점차 선두를 차지했습니다.
## 1980s 전문가 시스템
이 분야가 성장하며, 비즈니스에 대한 이점이 명확해졌고, 1980년대에 '전문가 시스템'이 확산되었습니다. "Expert systems were among the first truly successful forms of artificial intelligence (AI) software." ([source](https://wikipedia.org/wiki/Expert_system)).
이 시스템의 타입은, 실제로 비즈니스 요구사항을 정의하는 룰 엔진과 새로운 사실 추론하는 룰 시스템을 활용한 추론 엔진으로 부분적 구성된 _hybrid_ 입니다.
이런 시대에도 neural networks에 대한 관심이 늘어났습니다.
## 1987 - 1993: AI 'Chill'
전문화된 전문가 시스템 하드웨어의 확산은 너무나도 고차원되는 불운한 결과를 가져왔습니다. 개인용 컴퓨터의 부상은 크고, 전문화된, 중앙화 시스템과 경쟁했습니다. 컴퓨팅의 민주화가 시작되었고, 결국 현대의 빅 데이터 폭발을 위한 길을 열었습니다.
## 1993 - 2011
이 시대에는 ML과 AI가 과거 데이터와 컴퓨터 파워 부족으로 인해 발생했던 문제 중 일부 해결할 수 있는 새로운 시대가 열렸습니다. 데이터의 양은 급격히 늘어나기 시작했고, 2007년에 스마트폰이 나오면서 좋든 나쁘든 더 넓게 사용할 수 있게 되었습니다. 컴퓨터 파워는 크게 확장되었고, 알고리즘도 함께 발전했습니다. 과거 자유롭던 시대에서 진정한 규율로 이 분야는 성숙해지기 시작했습니다.
## 현재
오늘 날, 머신러닝과 AI는 인생의 대부분에 영향을 미칩니다. 이 시대에는 이러한 알고리즘이 인간의 인생에 미치는 위험과 잠재적인 영향에 대한 주의깊은 이해도가 요구됩니다. Microsoft의 Brad Smith가 언급합니다 "Information technology raises issues that go to the heart of fundamental human-rights protections like privacy and freedom of expression. These issues heighten responsibility for tech companies that create these products. In our view, they also call for thoughtful government regulation and for the development of norms around acceptable uses" ([source](https://www.technologyreview.com/2019/12/18/102365/the-future-of-ais-impact-on-society/)).
미래가 어떻게 변할지 알 수 없지만, 컴퓨터 시스템과 이를 실행하는 소프트웨어와 알고리즘을 이해하는 것은 중요합니다. 이 커리큘럼으로 더 잘 이해하고 스스로 결정할 수 있게 되기를 바랍니다.
[![The history of deep learning](https://img.youtube.com/vi/mTtDfKgLm54/0.jpg)](https://www.youtube.com/watch?v=mTtDfKgLm54 "The history of deep learning")
> 🎥 영상 보려면 위 이미지 클릭: Yann LeCun이 강의에서 딥러닝의 역사를 이야기 합니다.
---
## 🚀 도전
역사적인 순간에 사람들 뒤에서 한 가지를 집중적으로 파고 있는 자를 자세히 알아보세요. 매력있는 캐릭터가 있으며, 문화가 사라진 곳에서는 과학적인 발견을 하지 못합니다. 당신은 어떤 발견을 해보았나요?
## [강의 후 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/4/)
## 검토 & 자기주도 학습
보고 들을 수 있는 항목은 아래와 같습니다:
[This podcast where Amy Boyd discusses the evolution of AI](http://runasradio.com/Shows/Show/739)
[![The history of AI by Amy Boyd](https://img.youtube.com/vi/EJt3_bFYKss/0.jpg)](https://www.youtube.com/watch?v=EJt3_bFYKss "The history of AI by Amy Boyd")
## 과제
[Create a timeline](../assignment.md)

@ -3,7 +3,7 @@
![Bir taslak-notta makine öğrenimi geçmişinin özeti](../../../sketchnotes/ml-history.png)
> [Tomomi Imura](https://www.twitter.com/girlie_mac) tarafından hazırlanan taslak-not
## [Ders öncesi test](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/3?loc=tr)
## [Ders öncesi test](https://white-water-09ec41f0f.azurestaticapps.net/quiz/3?loc=tr)
Bu derste, makine öğrenimi ve yapay zeka tarihindeki önemli kilometre taşlarını inceleyeceğiz.
@ -102,7 +102,7 @@ Geleceğin neler getireceğini birlikte göreceğiz, ancak bu bilgisayar sisteml
Bu tarihi anlardan birine girin ve arkasındaki insanlar hakkında daha fazla bilgi edinin. Büyüleyici karakterler var ve kültürel bir boşlukta hiçbir bilimsel keşif yaratılmadı. Ne keşfedersiniz?
## [Ders sonrası test](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/4?loc=tr)
## [Ders sonrası test](https://white-water-09ec41f0f.azurestaticapps.net/quiz/4?loc=tr)
## İnceleme ve Bireysel Çalışma

@ -1,116 +1,116 @@
# 机器学习的历史
![机器学习历史概述](../../../sketchnotes/ml-history.png)
> 作者[Tomomi Imura](https://www.twitter.com/girlie_mac)
> 作者 [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [课前测验](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/3/)
## [课前测验](https://white-water-09ec41f0f.azurestaticapps.net/quiz/3/)
在本课中,我们将走过机器学习和人工智能历史上的主要里程碑。
人工智能(AI)作为一个领域的历史与机器学习的历史交织在一起,因为支持机器学习的算法和计算能力的进步推动了AI的发展。记住,虽然这些领域作为不同研究领域在20世纪50年代才开始具体化,但重要的[算法、统计、数学、计算和技术发现](https://wikipedia.org/wiki/Timeline_of_machine_learning) 要早于和重叠了这个时代。 事实上,[数百年来](https://wikipedia.org/wiki/History_of_artificial_intelligence)人们一直在思考这些问题:本文讨论了“思维机器”这一概念的历史知识基础。
人工智能(AI)作为一个领域的历史与机器学习的历史交织在一起,因为支持机器学习的算法和计算能力的进步推动了AI的发展。记住,虽然这些领域作为不同研究领域在 20 世纪 50 年代才开始具体化,但重要的[算法、统计、数学、计算和技术发现](https://wikipedia.org/wiki/Timeline_of_machine_learning) 要早于和重叠了这个时代。 事实上,[数百年来](https://wikipedia.org/wiki/History_of_artificial_intelligence)人们一直在思考这些问题:本文讨论了“思维机器”这一概念的历史知识基础。
## 主要发现
- 1763, 1812 [贝叶斯定理](https://wikipedia.org/wiki/Bayes%27_theorem) 及其前身。该定理及其应用是推理的基础,描述了基于先验知识的事件发生的概率。
- 1805 [最小二乘理论](https://wikipedia.org/wiki/Least_squares)由法国数学家Adrien-Marie Legendre提出。 你将在我们的回归单元中了解这一理论,它有助于数据拟合。
- 1913 [马尔可夫链](https://wikipedia.org/wiki/Markov_chain)以俄罗斯数学家Andrey Markov的名字命名,用于描述基于先前状态的一系列可能事件。
- 1957 [感知器](https://wikipedia.org/wiki/Perceptron)是美国心理学家Frank Rosenblatt发明的一种线性分类器,是深度学习发展的基础。
- 1967 [最近邻](https://wikipedia.org/wiki/Nearest_neighbor)是一种最初设计用于映射路线的算法。 在ML中,它用于检测模式。
- 1805 [最小二乘理论](https://wikipedia.org/wiki/Least_squares)由法国数学家 Adrien-Marie Legendre 提出。 你将在我们的回归单元中了解这一理论,它有助于数据拟合。
- 1913 [马尔可夫链](https://wikipedia.org/wiki/Markov_chain)以俄罗斯数学家 Andrey Markov 的名字命名,用于描述基于先前状态的一系列可能事件。
- 1957 [感知器](https://wikipedia.org/wiki/Perceptron)是美国心理学家 Frank Rosenblatt 发明的一种线性分类器,是深度学习发展的基础。
- 1967 [最近邻](https://wikipedia.org/wiki/Nearest_neighbor)是一种最初设计用于映射路线的算法。 在 ML 中,它用于检测模式。
- 1970 [反向传播](https://wikipedia.org/wiki/Backpropagation)用于训练[前馈神经网络](https://wikipedia.org/wiki/Feedforward_neural_network)。
- 1982 [循环神经网络](https://wikipedia.org/wiki/Recurrent_neural_network) 是源自产生时间图的前馈神经网络的人工神经网络。
✅ 做点调查。在ML和AI的历史上,还有哪些日期是重要的?
✅ 做点调查。在 ML 和 AI 的历史上,还有哪些日期是重要的?
## 1950: 会思考的机器
Alan Turing,一个真正杰出的人,[在2019年被公众投票选出](https://wikipedia.org/wiki/Icons:_The_Greatest_Person_of_the_20th_Century) 作为20世纪最伟大的科学家,他认为有助于为“会思考的机器”的概念打下基础。他通过创建 [图灵测试](https://www.bbc.com/news/technology-18475646)来解决反对者和他自己对这一概念的经验证据的需求,你将在我们的 NLP 课程中进行探索。
Alan Turing,一个真正杰出的人,[在 2019 年被公众投票选出](https://wikipedia.org/wiki/Icons:_The_Greatest_Person_of_the_20th_Century) 作为 20 世纪最伟大的科学家,他认为有助于为“会思考的机器”的概念打下基础。他通过创建 [图灵测试](https://www.bbc.com/news/technology-18475646)来解决反对者和他自己对这一概念的经验证据的需求,你将在我们的 NLP 课程中进行探索。
## 1956: 达特茅斯夏季研究项目
“达特茅斯夏季人工智能研究项目是人工智能领域的一个开创性事件,”正是在这里,人们创造了“人工智能”一词([来源](https://250.dartmouth.edu/highlights/artificial-intelligence-ai-coined-dartmouth))。
“达特茅斯夏季人工智能研究项目是人工智能领域的一个开创性事件,”正是在这里,人们创造了“人工智能”一词([来源](https://250.dartmouth.edu/highlights/artificial-intelligence-ai-coined-dartmouth))。
> 原则上,学习的每个方面或智能的任何其他特征都可以被精确地描述,以至于可以用机器来模拟它。
首席研究员、数学教授John McCarthy希望“基于这样一种猜想,即学习的每个方面或智能的任何其他特征原则上都可以如此精确地描述,以至于可以制造出一台机器来模拟它。” 参与者包括该领域的另一位杰出人物Marvin Minsky。
首席研究员、数学教授 John McCarthy 希望“基于这样一种猜想,即学习的每个方面或智能的任何其他特征原则上都可以如此精确地描述,以至于可以制造出一台机器来模拟它。” 参与者包括该领域的另一位杰出人物 Marvin Minsky。
研讨会被认为发起并鼓励了一些讨论,包括“符号方法的兴起、专注于有限领域的系统(早期专家系统),以及演绎系统与归纳系统的对比。”([来源](https://wikipedia.org/wiki/Dartmouth_workshop))。
研讨会被认为发起并鼓励了一些讨论,包括“符号方法的兴起、专注于有限领域的系统(早期专家系统),以及演绎系统与归纳系统的对比。”([来源](https://wikipedia.org/wiki/Dartmouth_workshop))。
## 1956 - 1974: “黄金岁月”
从20世纪50年代到70年代中期,乐观情绪高涨,希望人工智能能够解决许多问题。1967年,Marvin Minsky自信地说,“一代人之内。。。创造‘人工智能’的问题将得到实质性的解决。”(Minsky,Marvin(1967),《计算:有限和无限机器》,新泽西州恩格伍德克利夫斯:Prentice Hall)
从 20 世纪 50 年代到 70 年代中期,乐观情绪高涨,希望人工智能能够解决许多问题。1967 年,Marvin Minsky 自信地说,“一代人之内...创造‘人工智能’的问题将得到实质性的解决。”(Minsky,Marvin(1967),《计算:有限和无限机器》,新泽西州恩格伍德克利夫斯:Prentice Hall)
自然语言处理研究蓬勃发展,搜索被提炼并变得更加强大,创造了“微观世界”的概念,在这个概念中,简单的任务是用简单的语言指令完成的。
这项研究得到了政府机构的充分资助,在计算和算法方面取得了进展,并建造了智能机器的原型。其中一些机器包括:
* [机器人Shakey](https://wikipedia.org/wiki/Shakey_the_robot),他们可以“聪明地”操纵和决定如何执行任务。
* [机器人 Shakey](https://wikipedia.org/wiki/Shakey_the_robot),他们可以“聪明地”操纵和决定如何执行任务。
![Shakey, 智能机器人](../images/shakey.jpg)
> 1972 年的Shakey
> 1972 年的 Shakey
* Eliza,一个早期的“聊天机器人”,可以与人交谈并充当原始的“治疗师”。 你将在NLP课程中了解有关Eliza的更多信息。
* Eliza,一个早期的“聊天机器人”,可以与人交谈并充当原始的“治疗师”。 你将在 NLP 课程中了解有关 Eliza 的更多信息。
![Eliza, 机器人](../images/eliza.png)
> Eliza的一个版本,一个聊天机器人
> Eliza 的一个版本,一个聊天机器人
* “积木世界”是一个微观世界的例子,在那里积木可以堆叠和分类,并且可以测试教机器做出决策的实验。 使用[SHRDLU](https://wikipedia.org/wiki/SHRDLU)等库构建的高级功能有助于推动语言处理向前发展。
* “积木世界”是一个微观世界的例子,在那里积木可以堆叠和分类,并且可以测试教机器做出决策的实验。 使用 [SHRDLU](https://wikipedia.org/wiki/SHRDLU) 等库构建的高级功能有助于推动语言处理向前发展。
[![积木世界与SHRDLU](https://img.youtube.com/vi/QAJz4YKUwqw/0.jpg)](https://www.youtube.com/watch?v=QAJz4YKUwqw "积木世界与SHRDLU")
[![积木世界与 SHRDLU](https://img.youtube.com/vi/QAJz4YKUwqw/0.jpg)](https://www.youtube.com/watch?v=QAJz4YKUwqw "积木世界与SHRDLU")
> 🎥 点击上图观看视频: 积木世界与SHRDLU
> 🎥 点击上图观看视频: 积木世界与 SHRDLU
## 1974 - 1980: AI的寒冬
## 1974 - 1980: AI 的寒冬
到了20世纪70年代中期,很明显制造“智能机器”的复杂性被低估了,而且考虑到可用的计算能力,它的前景被夸大了。资金枯竭,市场信心放缓。影响信心的一些问题包括:
到了 20 世纪 70 年代中期,很明显制造“智能机器”的复杂性被低估了,而且考虑到可用的计算能力,它的前景被夸大了。资金枯竭,市场信心放缓。影响信心的一些问题包括:
- **限制**。计算能力太有限了
- **组合爆炸**。随着对计算机的要求越来越高,需要训练的参数数量呈指数级增长,而计算能力却没有平行发展。
- **缺乏数据**。 缺乏数据阻碍了测试、开发和改进算法的过程。
- **我们是否在问正确的问题?**。 被问到的问题也开始受到质疑。 研究人员开始对他们的方法提出批评:
- 图灵测试受到质疑的方法之一是“中国房间理论”,该理论认为,“对数字计算机进行编程可能使其看起来能理解语言,但不能产生真正的理解。” ([来源](https://plato.stanford.edu/entries/chinese-room/))
- 将“治疗师”ELIZA这样的人工智能引入社会的伦理受到了挑战。
- 将“治疗师”ELIZA 这样的人工智能引入社会的伦理受到了挑战。
与此同时,各种人工智能学派开始形成。 在[“scruffy”与“neat AI”](https://wikipedia.org/wiki/Neats_and_scruffies)之间建立了二分法。 _Scruffy_ 实验室对程序进行了数小时的调整,直到获得所需的结果。 _Neat_ 实验室“专注于逻辑和形式问题的解决”。 ELIZA 和 SHRDLU 是众所周知的 _scruffy_ 系统。 在 1980 年代,随着使 ML 系统可重现的需求出现,_neat_ 方法逐渐走上前沿,因为其结果更易于解释。
与此同时,各种人工智能学派开始形成。 在 [“scruffy” 与 “neat AI”](https://wikipedia.org/wiki/Neats_and_scruffies) 之间建立了二分法。 _Scruffy_ 实验室对程序进行了数小时的调整,直到获得所需的结果。 _Neat_ 实验室“专注于逻辑和形式问题的解决”。 ELIZA 和 SHRDLU 是众所周知的 _scruffy_ 系统。 在 1980 年代,随着使 ML 系统可重现的需求出现,_neat_ 方法逐渐走上前沿,因为其结果更易于解释。
## 1980s 专家系统
随着这个领域的发展,它对商业的好处变得越来越明显,在20世纪80年代,‘专家系统’的泛滥也是如此。“专家系统是首批真正成功的人工智能 (AI) 软件形式之一。” ([来源](https://wikipedia.org/wiki/Expert_system))。
随着这个领域的发展,它对商业的好处变得越来越明显,在 20 世纪 80 年代,‘专家系统’的泛滥也是如此。“专家系统是首批真正成功的人工智能 (AI) 软件形式之一。” ([来源](https://wikipedia.org/wiki/Expert_system))。
这种类型的系统实际上是混合系统,部分由定义业务需求的规则引擎和利用规则系统推断新事实的推理引擎组成。
在这个时代,神经网络也越来越受到重视。
## 1987 - 1993: AI的冷静期
## 1987 - 1993: AI 的冷静期
专业的专家系统硬件的激增造成了过于专业化的不幸后果。个人电脑的兴起也与这些大型、专业化、集中化系统展开了竞争。计算机的平民化已经开始,它最终为大数据的现代爆炸铺平了道路。
## 1993 - 2011
这个时代见证了一个新的时代,ML和AI能够解决早期由于缺乏数据和计算能力而导致的一些问题。数据量开始迅速增加,变得越来越广泛,无论好坏,尤其是2007年左右智能手机的出现,计算能力呈指数级增长,算法也随之发展。这个领域开始变得成熟,因为过去那些随心所欲的日子开始具体化为一种真正的纪律。
这个时代见证了一个新的时代,ML 和 AI 能够解决早期由于缺乏数据和计算能力而导致的一些问题。数据量开始迅速增加,变得越来越广泛,无论好坏,尤其是 2007 年左右智能手机的出现,计算能力呈指数级增长,算法也随之发展。这个领域开始变得成熟,因为过去那些随心所欲的日子开始具体化为一种真正的纪律。
## 现在
今天,机器学习和人工智能几乎触及我们生活的每一个部分。这个时代要求仔细了解这些算法对人类生活的风险和潜在影响。正如微软的Brad Smith所言,“信息技术引发的问题触及隐私和言论自由等基本人权保护的核心。这些问题加重了制造这些产品的科技公司的责任。在我们看来,它们还呼吁政府进行深思熟虑的监管,并围绕可接受的用途制定规范”([来源](https://www.technologyreview.com/2019/12/18/102365/the-future-of-ais-impact-on-society/))。
今天,机器学习和人工智能几乎触及我们生活的每一个部分。这个时代要求仔细了解这些算法对人类生活的风险和潜在影响。正如微软的 Brad Smith 所言,“信息技术引发的问题触及隐私和言论自由等基本人权保护的核心。这些问题加重了制造这些产品的科技公司的责任。在我们看来,它们还呼吁政府进行深思熟虑的监管,并围绕可接受的用途制定规范”([来源](https://www.technologyreview.com/2019/12/18/102365/the-future-of-ais-impact-on-society/))。
未来的情况还有待观察,但了解这些计算机系统以及它们运行的软件和算法是很重要的。我们希望这门课程能帮助你更好的理解,以便你自己决定。
[![深度学习的历史](https://img.youtube.com/vi/mTtDfKgLm54/0.jpg)](https://www.youtube.com/watch?v=mTtDfKgLm54 "深度学习的历史")
> 🎥 点击上图观看视频:Yann LeCun在本次讲座中讨论深度学习的历史
> 🎥 点击上图观看视频:Yann LeCun 在本次讲座中讨论深度学习的历史
---
## 🚀挑战
深入了解这些历史时刻之一,并更多地了解它们背后的人。这里有许多引人入胜的人物,没有一项科学发现是在文化真空中创造出来的。你发现了什么?
## [课后测验](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/4/)
## [课后测验](https://white-water-09ec41f0f.azurestaticapps.net/quiz/4/)
## 复习与自学
以下是要观看和收听的节目:
[这是Amy Boyd讨论人工智能进化的播客](http://runasradio.com/Shows/Show/739)
[这是 Amy Boyd 讨论人工智能进化的播客](http://runasradio.com/Shows/Show/739)
[![Amy Boyd的《人工智能史》](https://img.youtube.com/vi/EJt3_bFYKss/0.jpg)](https://www.youtube.com/watch?v=EJt3_bFYKss "Amy Boyd的《人工智能史》")
## 任务
[创建时间线](../assignment.md)
[创建时间线](assignment.zh-cn.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 | 代码还不完整并且没有部署 | 时间线不完整,没有经过充分的研究,并且没有部署 |

@ -3,7 +3,7 @@
![Summary of Fairness in Machine Learning in a sketchnote](../../sketchnotes/ml-fairness.png)
> Sketchnote by [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/5/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/5/)
## Introduction
@ -184,7 +184,7 @@ To prevent biases from being introduced in the first place, we should:
Think about real-life scenarios where unfairness is evident in model-building and usage. What else should we consider?
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/6/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/6/)
## Review & Self Study
In this lesson, you have learned some basics of the concepts of fairness and unfairness in machine learning.

@ -0,0 +1,213 @@
# Keadilan dalam Machine Learning
![Ringkasan dari Keadilan dalam Machine Learning dalam sebuah catatan sketsa](../../../sketchnotes/ml-fairness.png)
> Catatan sketsa oleh [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Quiz Pra-Pelajaran](https://white-water-09ec41f0f.azurestaticapps.net/quiz/5/)
## Pengantar
Dalam kurikulum ini, kamu akan mulai mengetahui bagaimana Machine Learning bisa memengaruhi kehidupan kita sehari-hari. Bahkan sekarang, sistem dan model terlibat dalam tugas pengambilan keputusan sehari-hari, seperti diagnosis kesehatan atau mendeteksi penipuan. Jadi, penting bahwa model-model ini bekerja dengan baik untuk memberikan hasil yang adil bagi semua orang.
Bayangkan apa yang bisa terjadi ketika data yang kamu gunakan untuk membangun model ini tidak memiliki demografi tertentu, seperti ras, jenis kelamin, pandangan politik, agama, atau secara tidak proporsional mewakili demografi tersebut. Bagaimana jika keluaran dari model diinterpretasikan lebih menyukai beberapa demografis tertentu? Apa konsekuensi untuk aplikasinya?
Dalam pelajaran ini, kamu akan:
- Meningkatkan kesadaran dari pentingnya keadilan dalam Machine Learning.
- Mempelajari tentang berbagai kerugian terkait keadilan.
- Learn about unfairness assessment and mitigation.
- Mempelajari tentang mitigasi dan penilaian ketidakadilan.
## Prasyarat
Sebagai prasyarat, silakan ikuti jalur belajar "Prinsip AI yang Bertanggung Jawab" dan tonton video di bawah ini dengan topik:
Pelajari lebih lanjut tentang AI yang Bertanggung Jawab dengan mengikuti [Jalur Belajar](https://docs.microsoft.com/learn/modules/responsible-ai-principles/?WT.mc_id=academic-15963-cxa) ini
[![Pendekatan Microsoft untuk AI yang Bertanggung Jawab](https://img.youtube.com/vi/dnC8-uUZXSc/0.jpg)](https://youtu.be/dnC8-uUZXSc "Pendekatan Microsoft untuk AI yang Bertanggung Jawab")
> 🎥 Klik gambar diatas untuk menonton video: Pendekatan Microsoft untuk AI yang Bertanggung Jawab
## Ketidakadilan dalam data dan algoritma
> "Jika Anda menyiksa data cukup lama, data itu akan mengakui apa pun " - Ronald Coase
Pernyataan ini terdengar ekstrem, tetapi memang benar bahwa data dapat dimanipulasi untuk mendukung kesimpulan apa pun. Manipulasi semacam itu terkadang bisa terjadi secara tidak sengaja. Sebagai manusia, kita semua memiliki bias, dan seringkali sulit untuk secara sadar mengetahui kapan kamu memperkenalkan bias dalam data.
Menjamin keadilan dalam AI dan machine learning tetap menjadi tantangan sosioteknik yang kompleks. Artinya, hal itu tidak bisa ditangani baik dari perspektif sosial atau teknis semata.
### Kerugian Terkait Keadilan
Apa yang dimaksud dengan ketidakadilan? "Ketidakadilan" mencakup dampak negatif atau "bahaya" bagi sekelompok orang, seperti yang didefinisikan dalam hal ras, jenis kelamin, usia, atau status disabilitas.
Kerugian utama yang terkait dengan keadilan dapat diklasifikasikan sebagai:
- **Alokasi**, jika suatu jenis kelamin atau etnisitas misalkan lebih disukai daripada yang lain.
- **Kualitas layanan**. Jika kamu melatih data untuk satu skenario tertentu tetapi kenyataannya jauh lebih kompleks, hasilnya adalah layanan yang berkinerja buruk.
- **Stereotip**. Mengaitkan grup tertentu dengan atribut yang ditentukan sebelumnya.
- **Fitnah**. Untuk mengkritik dan melabeli sesuatu atau seseorang secara tidak adil.
- **Representasi yang kurang atau berlebihan**. Idenya adalah bahwa kelompok tertentu tidak terlihat dalam profesi tertentu, dan layanan atau fungsi apa pun yang terus dipromosikan yang menambah kerugian.
Mari kita lihat contoh-contohnya.
### Alokasi
Bayangkan sebuah sistem untuk menyaring pengajuan pinjaman. Sistem cenderung memilih pria kulit putih sebagai kandidat yang lebih baik daripada kelompok lain. Akibatnya, pinjaman ditahan dari pemohon tertentu.
Contoh lain adalah alat perekrutan eksperimental yang dikembangkan oleh perusahaan besar untuk menyaring kandidat. Alat tersebut secara sistematis mendiskriminasi satu gender dengan menggunakan model yang dilatih untuk lebih memilih kata-kata yang terkait dengan gender lain. Hal ini mengakibatkan kandidat yang resumenya berisi kata-kata seperti "tim rugby wanita" tidak masuk kualifikasi.
✅ Lakukan sedikit riset untuk menemukan contoh dunia nyata dari sesuatu seperti ini
### Kualitas Layanan
Para peneliti menemukan bahwa beberapa pengklasifikasi gender komersial memiliki tingkat kesalahan yang lebih tinggi di sekitar gambar wanita dengan warna kulit lebih gelap dibandingkan dengan gambar pria dengan warna kulit lebih terang. [Referensi](https://www.media.mit.edu/publications/gender-shades-intersectional-accuracy-disparities-in-commercial-gender-classification/)
Contoh terkenal lainnya adalah dispenser sabun tangan yang sepertinya tidak bisa mendeteksi orang dengan kulit gelap. [Referensi](https://gizmodo.com/why-cant-this-soap-dispenser-identify-dark-skin-1797931773)
### Stereotip
Pandangan gender stereotip ditemukan dalam terjemahan mesin. Ketika menerjemahkan "dia (laki-laki) adalah seorang perawat dan dia (perempuan) adalah seorang dokter" ke dalam bahasa Turki, masalah muncul. Turki adalah bahasa tanpa gender yang memiliki satu kata ganti, "o" untuk menyampaikan orang ketiga tunggal, tetapi menerjemahkan kalimat kembali dari Turki ke Inggris menghasilkan stereotip dan salah sebagai "dia (perempuan) adalah seorang perawat dan dia (laki-laki) adalah seorang dokter".
![terjemahan ke bahasa Turki](../images/gender-bias-translate-en-tr.png)
![terjemahan kembali ke bahasa Inggris](../images/gender-bias-translate-tr-en.png)
### Fitnah
Sebuah teknologi pelabelan gambar yang terkenal salah memberi label gambar orang berkulit gelap sebagai gorila. Pelabelan yang salah berbahaya bukan hanya karena sistem membuat kesalahan karena secara khusus menerapkan label yang memiliki sejarah panjang yang sengaja digunakan untuk merendahkan orang kulit hitam.
[![AI: Bukankah Aku Seorang Wanita?](https://img.youtube.com/vi/QxuyfWoVV98/0.jpg)](https://www.youtube.com/watch?v=QxuyfWoVV98 "Bukankah Aku Seorang Wanita?")
> 🎥 Klik gambar diatas untuk sebuah video: AI, Bukankah Aku Seorang Wanita? - menunjukkan kerugian yang disebabkan oleh pencemaran nama baik yang menyinggung ras oleh AI
### Representasi yang kurang atau berlebihan
Hasil pencarian gambar yang condong ke hal tertentu (skewed) dapat menjadi contoh yang bagus dari bahaya ini. Saat menelusuri gambar profesi dengan persentase pria yang sama atau lebih tinggi daripada wanita, seperti teknik, atau CEO, perhatikan hasil yang lebih condong ke jenis kelamin tertentu.
![Pencarian CEO di Bing](../images/ceos.png)
> Pencarian di Bing untuk 'CEO' ini menghasilkan hasil yang cukup inklusif
Lima jenis bahaya utama ini tidak saling eksklusif, dan satu sistem dapat menunjukkan lebih dari satu jenis bahaya. Selain itu, setiap kasus bervariasi dalam tingkat keparahannya. Misalnya, memberi label yang tidak adil kepada seseorang sebagai penjahat adalah bahaya yang jauh lebih parah daripada memberi label yang salah pada gambar. Namun, penting untuk diingat bahwa bahkan kerugian yang relatif tidak parah dapat membuat orang merasa terasing atau diasingkan dan dampak kumulatifnya bisa sangat menekan.
✅ **Diskusi**: Tinjau kembali beberapa contoh dan lihat apakah mereka menunjukkan bahaya yang berbeda.
| | Alokasi | Kualitas Layanan | Stereotip | Fitnah | Representasi yang kurang atau berlebihan |
| -------------------------- | :-----: | :--------------: | :-------: | :----: | :--------------------------------------: |
| Sistem perekrutan otomatis | x | x | x | | x |
| Terjemahan mesin | | | | | |
| Melabeli foto | | | | | |
## Mendeteksi Ketidakadilan
Ada banyak alasan mengapa sistem tertentu berperilaku tidak adil. Bias sosial, misalnya, mungkin tercermin dalam kumpulan data yang digunakan untuk melatih. Misalnya, ketidakadilan perekrutan mungkin telah diperburuk oleh ketergantungan yang berlebihan pada data historis. Dengan menggunakan pola dalam resume yang dikirimkan ke perusahaan selama periode 10 tahun, model tersebut menentukan bahwa pria lebih berkualitas karena mayoritas resume berasal dari pria, yang mencerminkan dominasi pria di masa lalu di industri teknologi.
Data yang tidak memadai tentang sekelompok orang tertentu dapat menjadi alasan ketidakadilan. Misalnya, pengklasifikasi gambar memiliki tingkat kesalahan yang lebih tinggi untuk gambar orang berkulit gelap karena warna kulit yang lebih gelap kurang terwakili dalam data.
Asumsi yang salah yang dibuat selama pengembangan menyebabkan ketidakadilan juga. Misalnya, sistem analisis wajah yang dimaksudkan untuk memprediksi siapa yang akan melakukan kejahatan berdasarkan gambar wajah orang dapat menyebabkan asumsi yang merusak. Hal ini dapat menyebabkan kerugian besar bagi orang-orang yang salah diklasifikasikan.
## Pahami model kamu dan bangun dalam keadilan
Meskipun banyak aspek keadilan tidak tercakup dalam metrik keadilan kuantitatif, dan tidak mungkin menghilangkan bias sepenuhnya dari sistem untuk menjamin keadilan, Kamu tetap bertanggung jawab untuk mendeteksi dan mengurangi masalah keadilan sebanyak mungkin.
Saat Kamu bekerja dengan model pembelajaran mesin, penting untuk memahami model Kamu dengan cara memastikan interpretasinya dan dengan menilai serta mengurangi ketidakadilan.
Mari kita gunakan contoh pemilihan pinjaman untuk mengisolasi kasus untuk mengetahui tingkat dampak setiap faktor pada prediksi.
## Metode Penilaian
1. **Identifikasi bahaya (dan manfaat)**. Langkah pertama adalah mengidentifikasi bahaya dan manfaat. Pikirkan tentang bagaimana tindakan dan keputusan dapat memengaruhi calon pelanggan dan bisnis itu sendiri.
1. **Identifikasi kelompok yang terkena dampak**. Setelah Kamu memahami jenis kerugian atau manfaat apa yang dapat terjadi, identifikasi kelompok-kelompok yang mungkin terpengaruh. Apakah kelompok-kelompok ini ditentukan oleh jenis kelamin, etnis, atau kelompok sosial?
1. **Tentukan metrik keadilan**. Terakhir, tentukan metrik sehingga Kamu memiliki sesuatu untuk diukur dalam pekerjaan Kamu untuk memperbaiki situasi.
### Identifikasi bahaya (dan manfaat)
Apa bahaya dan manfaat yang terkait dengan pinjaman? Pikirkan tentang skenario negatif palsu dan positif palsu:
**False negatives** (ditolak, tapi Y=1) - dalam hal ini, pemohon yang akan mampu membayar kembali pinjaman ditolak. Ini adalah peristiwa yang merugikan karena sumber pinjaman ditahan dari pemohon yang memenuhi syarat.
**False positives** (diterima, tapi Y=0) - dalam hal ini, pemohon memang mendapatkan pinjaman tetapi akhirnya wanprestasi. Akibatnya, kasus pemohon akan dikirim ke agen penagihan utang yang dapat mempengaruhi permohonan pinjaman mereka di masa depan.
### Identifikasi kelompok yang terkena dampak
Langkah selanjutnya adalah menentukan kelompok mana yang kemungkinan akan terpengaruh. Misalnya, dalam kasus permohonan kartu kredit, sebuah model mungkin menentukan bahwa perempuan harus menerima batas kredit yang jauh lebih rendah dibandingkan dengan pasangan mereka yang berbagi aset rumah tangga. Dengan demikian, seluruh demografi yang ditentukan berdasarkan jenis kelamin menjadi terpengaruh.
### Tentukan metrik keadilan
Kamu telah mengidentifikasi bahaya dan kelompok yang terpengaruh, dalam hal ini digambarkan berdasarkan jenis kelamin. Sekarang, gunakan faktor terukur (*quantified factors*) untuk memisahkan metriknya. Misalnya, dengan menggunakan data di bawah ini, Kamu dapat melihat bahwa wanita memiliki tingkat *false positive* terbesar dan pria memiliki yang terkecil, dan kebalikannya berlaku untuk *false negative*.
✅ Dalam pelajaran selanjutnya tentang *Clustering*, Kamu akan melihat bagaimana membangun 'confusion matrix' ini dalam kode
| | False positive rate | False negative rate | count |
| ---------- | ------------------- | ------------------- | ----- |
| Women | 0.37 | 0.27 | 54032 |
| Men | 0.31 | 0.35 | 28620 |
| Non-binary | 0.33 | 0.31 | 1266 |
Tabel ini memberitahu kita beberapa hal. Pertama, kami mencatat bahwa ada sedikit orang non-biner dalam data. Datanya condong (*skewed*), jadi Kamu harus berhati-hati dalam menafsirkan angka-angka ini.
Dalam hal ini, kita memiliki 3 grup dan 2 metrik. Ketika kita memikirkan tentang bagaimana sistem kita memengaruhi kelompok pelanggan dengan permohonan pinjaman mereka, ini mungkin cukup, tetapi ketika Kamu ingin menentukan jumlah grup yang lebih besar, Kamu mungkin ingin menyaringnya menjadi kumpulan ringkasan yang lebih kecil. Untuk melakukannya, Kamu dapat menambahkan lebih banyak metrik, seperti perbedaan terbesar atau rasio terkecil dari setiap *false negative* dan *false positive*.
✅ Berhenti dan Pikirkan: Kelompok lain yang apa lagi yang mungkin terpengaruh untuk pengajuan pinjaman?
## Mengurangi ketidakadilan
Untuk mengurangi ketidakadilan, jelajahi model untuk menghasilkan berbagai model yang dimitigasi dan bandingkan pengorbanan yang dibuat antara akurasi dan keadilan untuk memilih model yang paling adil.
Pelajaran pengantar ini tidak membahas secara mendalam mengenai detail mitigasi ketidakadilan algoritmik, seperti pendekatan pasca-pemrosesan dan pengurangan (*post-processing and reductions approach*), tetapi berikut adalah *tool* yang mungkin ingin Kamu coba.
### Fairlearn
[Fairlearn](https://fairlearn.github.io/) adalah sebuah *package* Python open-source yang memungkinkan Kamu untuk menilai keadilan sistem Kamu dan mengurangi ketidakadilan.
*Tool* ini membantu Kamu menilai bagaimana prediksi model memengaruhi kelompok yang berbeda, memungkinkan Kamu untuk membandingkan beberapa model dengan menggunakan metrik keadilan dan kinerja, dan menyediakan serangkaian algoritma untuk mengurangi ketidakadilan dalam klasifikasi dan regresi biner.
- Pelajari bagaimana cara menggunakan komponen-komponen yang berbeda dengan mengunjungi [GitHub](https://github.com/fairlearn/fairlearn/) Fairlearn
- Jelajahi [panduan pengguna](https://fairlearn.github.io/main/user_guide/index.html), [contoh-contoh](https://fairlearn.github.io/main/auto_examples/index.html)
- Coba beberapa [sampel notebook](https://github.com/fairlearn/fairlearn/tree/master/notebooks).
- Pelajari [bagaimana cara mengaktifkan penilaian keadilan](https://docs.microsoft.com/azure/machine-learning/how-to-machine-learning-fairness-aml?WT.mc_id=academic-15963-cxa) dari model machine learning di Azure Machine Learning.
- Lihat [sampel notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/contrib/fairness) ini untuk skenario penilaian keadilan yang lebih banyak di Azure Machine Learning.
---
## 🚀 Tantangan
Untuk mencegah kemunculan bias pada awalnya, kita harus:
- memiliki keragaman latar belakang dan perspektif di antara orang-orang yang bekerja pada sistem
- berinvestasi dalam dataset yang mencerminkan keragaman masyarakat kita
- mengembangkan metode yang lebih baik untuk mendeteksi dan mengoreksi bias ketika itu terjadi
Pikirkan tentang skenario kehidupan nyata di mana ketidakadilan terbukti dalam pembuatan dan penggunaan model. Apa lagi yang harus kita pertimbangkan?
## [Quiz Pasca-Pelajaran](https://white-water-09ec41f0f.azurestaticapps.net/quiz/6/)
## Ulasan & Belajar Mandiri
Dalam pelajaran ini, Kamu telah mempelajari beberapa dasar konsep keadilan dan ketidakadilan dalam pembelajaran mesin.
Tonton workshop ini untuk menyelami lebih dalam kedalam topik:
- YouTube: Kerugian terkait keadilan dalam sistem AI: Contoh, penilaian, dan mitigasi oleh Hanna Wallach dan Miro Dudik [Kerugian terkait keadilan dalam sistem AI: Contoh, penilaian, dan mitigasi - YouTube](https://www.youtube.com/watch?v=1RptHwfkx_k)
Kamu juga dapat membaca:
- Pusat sumber daya RAI Microsoft: [Responsible AI Resources – Microsoft AI](https://www.microsoft.com/ai/responsible-ai-resources?activetab=pivot1%3aprimaryr4)
- Grup riset FATE Microsoft: [FATE: Fairness, Accountability, Transparency, and Ethics in AI - Microsoft Research](https://www.microsoft.com/research/theme/fate/)
Jelajahi *toolkit* Fairlearn
[Fairlearn](https://fairlearn.org/)
Baca mengenai *tools* Azure Machine Learning untuk memastikan keadilan
- [Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/concept-fairness-ml?WT.mc_id=academic-15963-cxa)
## Tugas
[Jelajahi Fairlearn](assignment.id.md)

@ -1,212 +1,212 @@
# Equità e machine learning
![Riepilogo dell'equità in machine learning in uno sketchnote](../../../sketchnotes/ml-fairness.png)
> Sketchnote di [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/5/)
## Introduzione
In questo programma di studi, si inizierà a scoprire come machine learning può e sta influenzando la vita quotidiana. Anche ora, sistemi e modelli sono coinvolti nelle attività decisionali quotidiane, come le diagnosi sanitarie o l'individuazione di frodi. Quindi è importante che questi modelli funzionino bene per fornire risultati equi per tutti.
Si immagini cosa può accadere quando i dati che si stanno utilizzando per costruire questi modelli mancano di determinati dati demografici, come razza, genere, visione politica, religione, o rappresentano tali dati demografici in modo sproporzionato. E quando il risultato del modello viene interpretato per favorire alcuni gruppi demografici? Qual è la conseguenza per l'applicazione?
In questa lezione, si dovrà:
- Aumentare la propria consapevolezza sull'importanza dell'equità nel machine learning.
- Informarsi sui danni legati all'equità.
- Apprendere ulteriori informazioni sulla valutazione e la mitigazione dell'ingiustizia.
## Prerequisito
Come prerequisito, si segua il percorso di apprendimento "Principi di AI Responsabile" e si guardi il video qui sotto sull'argomento:
Si scopra di più sull'AI Responsabile seguendo questo [percorso di apprendimento](https://docs.microsoft.com/learn/modules/responsible-ai-principles/?WT.mc_id=academic-15963-cxa)
[![L'approccio di Microsoft all'AI responsabileL'](https://img.youtube.com/vi/dnC8-uUZXSc/0.jpg)](https://youtu.be/dnC8-uUZXSc "approccio di Microsoft all'AI Responsabile")
> 🎥 Fare clic sull'immagine sopra per un video: L'approccio di Microsoft all'AI Responsabile
## Iniquità nei dati e negli algoritmi
> "Se si torturano i dati abbastanza a lungo, essi confesseranno qualsiasi cosa" - Ronald Coase
Questa affermazione suona estrema, ma è vero che i dati possono essere manipolati per supportare qualsiasi conclusione. Tale manipolazione a volte può avvenire involontariamente. Come esseri umani, abbiamo tutti dei pregiudizi, ed è spesso difficile sapere consapevolmente quando si introduce un pregiudizio nei dati.
Garantire l'equità nell'intelligenza artificiale e machine learning rimane una sfida socio-tecnica complessa. Ciò significa che non può essere affrontata da prospettive puramente sociali o tecniche.
### Danni legati all'equità
Cosa si intende per ingiustizia? L'"ingiustizia" comprende gli impatti negativi, o "danni", per un gruppo di persone, come quelli definiti in termini di razza, genere, età o stato di disabilità.
I principali danni legati all'equità possono essere classificati come:
- **Allocazione**, se un genere o un'etnia, ad esempio, sono preferiti a un altro.
- **Qualità di servizio** Se si addestrano i dati per uno scenario specifico, ma la realtà è molto più complessa, si ottiene un servizio scadente.
- **Stereotipi**. Associazione di un dato gruppo con attributi preassegnati.
- **Denigrazione**. Criticare ed etichettare ingiustamente qualcosa o qualcuno.
- **Sovra o sotto rappresentazione**. L'idea è che un certo gruppo non è visto in una certa professione, e qualsiasi servizio o funzione che continua a promuovere ciò, contribuisce al danno.
Si dia un'occhiata agli esempi.
### Allocazione
Si consideri un ipotetico sistema per la scrematura delle domande di prestito. Il sistema tende a scegliere gli uomini bianchi come candidati migliori rispetto ad altri gruppi. Di conseguenza, i prestiti vengono negati ad alcuni richiedenti.
Un altro esempio potrebbe essere uno strumento sperimentale di assunzione sviluppato da una grande azienda per selezionare i candidati. Lo strumento discrimina sistematicamente un genere utilizzando i modelli che sono stati addestrati a preferire parole associate con altro. Ha portato a penalizzare i candidati i cui curricula contengono parole come "squadra di rugby femminile".
✅ Si compia una piccola ricerca per trovare un esempio reale di qualcosa del genere
### Qualità di Servizio
I ricercatori hanno scoperto che diversi classificatori di genere commerciali avevano tassi di errore più elevati intorno alle immagini di donne con tonalità della pelle più scura rispetto alle immagini di uomini con tonalità della pelle più chiare. [Riferimento](https://www.media.mit.edu/publications/gender-shades-intersectional-accuracy-disparities-in-commercial-gender-classification/)
Un altro esempio infamante è un distributore di sapone per le mani che sembrava non essere in grado di percepire le persone con la pelle scura. [Riferimento](https://gizmodo.com/why-cant-this-soap-dispenser-identify-dark-skin-1797931773)
### Stereotipi
La visione di genere stereotipata è stata trovata nella traduzione automatica. Durante la traduzione in turco "he is a nurse and she is a doctor" (lui è un'infermiere e lei un medico), sono stati riscontrati problemi. Il turco è una lingua senza genere che ha un pronome, "o" per trasmettere una terza persona singolare, ma tradurre la frase dal turco all'inglese produce lo stereotipo e scorretto come "she is a nurse and he is a doctor" (lei è un'infermiera e lui è un medico).
![traduzione in turco](../images/gender-bias-translate-en-tr.png)
![Traduzione in inglese](../images/gender-bias-translate-tr-en.png)
### Denigrazione
Una tecnologia di etichettatura delle immagini ha contrassegnato in modo infamante le immagini di persone dalla pelle scura come gorilla. L'etichettatura errata è dannosa non solo perché il sistema ha commesso un errore, ma anche perché ha applicato specificamente un'etichetta che ha una lunga storia di essere intenzionalmente utilizzata per denigrare i neri.
[![AI: Non sono una donna?](https://img.youtube.com/vi/QxuyfWoVV98/0.jpg)](https://www.youtube.com/watch?v=QxuyfWoVV98 "AI, non sono una donna?")
> 🎥 Cliccare sull'immagine sopra per un video: AI, Ain't I a Woman - una performance che mostra il danno causato dalla denigrazione razzista da parte dell'AI
### Sovra o sotto rappresentazione
I risultati di ricerca di immagini distorti possono essere un buon esempio di questo danno. Quando si cercano immagini di professioni con una percentuale uguale o superiore di uomini rispetto alle donne, come l'ingegneria o CEO, si osserva che i risultati sono più fortemente distorti verso un determinato genere.
![Ricerca CEO di Bing](../images/ceos.png)
> Questa ricerca su Bing per "CEO" produce risultati piuttosto inclusivi
Questi cinque principali tipi di danno non si escludono a vicenda e un singolo sistema può presentare più di un tipo di danno. Inoltre, ogni caso varia nella sua gravità. Ad esempio, etichettare ingiustamente qualcuno come criminale è un danno molto più grave che etichettare erroneamente un'immagine. È importante, tuttavia, ricordare che anche danni relativamente non gravi possono far sentire le persone alienate o emarginate e l'impatto cumulativo può essere estremamente opprimente.
✅ **Discussione**: rivisitare alcuni degli esempi e vedere se mostrano danni diversi.
| | Allocatione | Qualita di servizio | Stereotipo | Denigrazione | Sovra o sotto rappresentazione |
| ----------------------- | :--------: | :----------------: | :----------: | :---------: | :----------------------------: |
| Sistema di assunzione automatizzato | x | x | x | | x |
| Traduzione automatica | | | | | |
| Eitchettatura foto | | | | | |
## Rilevare l'ingiustizia
Ci sono molte ragioni per cui un dato sistema si comporta in modo scorretto. I pregiudizi sociali, ad esempio, potrebbero riflettersi nell'insieme di dati utilizzati per addestrarli. Ad esempio, l'ingiustizia delle assunzioni potrebbe essere stata esacerbata dall'eccessivo affidamento sui dati storici. Utilizzando i modelli nei curricula inviati all'azienda per un periodo di 10 anni, il modello ha determinato che gli uomini erano più qualificati perché la maggior parte dei curricula proveniva da uomini, un riflesso del passato dominio maschile nell'industria tecnologica.
Dati inadeguati su un determinato gruppo di persone possono essere motivo di ingiustizia. Ad esempio, i classificatori di immagini hanno un tasso di errore più elevato per le immagini di persone dalla pelle scura perché le tonalità della pelle più scure sono sottorappresentate nei dati.
Anche le ipotesi errate fatte durante lo sviluppo causano iniquità. Ad esempio, un sistema di analisi facciale destinato a prevedere chi commetterà un crimine basato sulle immagini dei volti delle persone può portare a ipotesi dannose. Ciò potrebbe portare a danni sostanziali per le persone classificate erroneamente.
## Si comprendano i propri modelli e si costruiscano in modo onesto
Sebbene molti aspetti dell'equità non vengano catturati nelle metriche di equità quantitativa e non sia possibile rimuovere completamente i pregiudizi da un sistema per garantire l'equità, si è comunque responsabili di rilevare e mitigare il più possibile i problemi di equità.
Quando si lavora con modelli di machine learning, è importante comprendere i propri modelli assicurandone l'interpretabilità e valutando e mitigando l'ingiustizia.
Si utilizza l'esempio di selezione del prestito per isolare il caso e determinare il livello di impatto di ciascun fattore sulla previsione.
## Metodi di valutazione
1. **Identificare i danni (e benefici)**. Il primo passo è identificare danni e benefici. Si pensi a come azioni e decisioni possono influenzare sia i potenziali clienti che un'azienda stessa.
1. **Identificare i gruppi interessati**. Una volta compreso il tipo di danni o benefici che possono verificarsi, identificare i gruppi che potrebbero essere interessati. Questi gruppi sono definiti per genere, etnia o gruppo sociale?
1. **Definire le metriche di equità**. Infine, si definisca una metrica in modo da avere qualcosa su cui misurare il proprio lavoro per migliorare la situazione.
### **Identificare danni (e benefici)**
Quali sono i danni e i benefici associati al prestito? Si pensi agli scenari di falsi negativi e falsi positivi:
**Falsi negativi** (rifiutato, ma Y=1) - in questo caso viene rifiutato un richiedente che sarà in grado di rimborsare un prestito. Questo è un evento avverso perché le risorse dei prestiti non sono erogate a richiedenti qualificati.
**Falsi positivi** (accettato, ma Y=0) - in questo caso, il richiedente ottiene un prestito ma alla fine fallisce. Di conseguenza, il caso del richiedente verrà inviato a un'agenzia di recupero crediti che può influire sulle sue future richieste di prestito.
### **Identificare i gruppi interessati**
Il passo successivo è determinare quali gruppi potrebbero essere interessati. Ad esempio, nel caso di una richiesta di carta di credito, un modello potrebbe stabilire che le donne dovrebbero ricevere limiti di credito molto più bassi rispetto ai loro coniugi che condividono i beni familiari. Un intero gruppo demografico, definito in base al genere, è così interessato.
### **Definire le metriche di equità**
Si sono identificati i danni e un gruppo interessato, in questo caso, delineato per genere. Ora, si usino i fattori quantificati per disaggregare le loro metriche. Ad esempio, utilizzando i dati di seguito, si può vedere che le donne hanno il più alto tasso di falsi positivi e gli uomini il più piccolo, e che è vero il contrario per i falsi negativi.
✅ In una futura lezione sul Clustering, si vedrà come costruire questa 'matrice di confusione' nel codice
| | percentuale di falsi positivi | Percentuale di falsi negativi |conteggio |
| ---------- | ------------------- | ------------------- | ----- |
| Donna | 0,37 | 0,27 | 54032 |
| Uomo | 0,31 | 0.35 | 28620 |
| Non binario | 0,33 | 0,31 | 1266 |
Questa tabella ci dice diverse cose. Innanzitutto, si nota che ci sono relativamente poche persone non binarie nei dati. I dati sono distorti, quindi si deve fare attenzione a come si interpretano questi numeri.
In questo caso, ci sono 3 gruppi e 2 metriche. Quando si pensa a come il nostro sistema influisce sul gruppo di clienti con i loro richiedenti di prestito, questo può essere sufficiente, ma quando si desidera definire un numero maggiore di gruppi, è possibile distillare questo in insiemi più piccoli di riepiloghi. Per fare ciò, si possono aggiungere più metriche, come la differenza più grande o il rapporto più piccolo di ogni falso negativo e falso positivo.
✅ Ci si fermi a pensare: quali altri gruppi potrebbero essere interessati dalla richiesta di prestito?
## Mitigare l'ingiustizia
Per mitigare l'ingiustizia, si esplori il modello per generare vari modelli mitigati e si confrontino i compromessi tra accuratezza ed equità per selezionare il modello più equo.
Questa lezione introduttiva non approfondisce i dettagli dell'algoritmo della mitigazione dell'ingiustizia, come l'approccio di post-elaborazione e riduzione, ma ecco uno strumento che si potrebbe voler provare.
### Fairlearn
[Fairlearn](https://fairlearn.github.io/) è un pacchetto Python open source che consente di valutare l'equità dei propri sistemi e mitigare l'ingiustizia.
Lo strumento consente di valutare in che modo le previsioni di un modello influiscono su diversi gruppi, consentendo di confrontare più modelli utilizzando metriche di equità e prestazioni e fornendo una serie di algoritmi per mitigare l'ingiustizia nella classificazione binaria e nella regressione.
- Si scopra come utilizzare i diversi componenti controllando il GitHub di [Fairlearn](https://github.com/fairlearn/fairlearn/)
- Si esplori la [guida per l'utente](https://fairlearn.github.io/main/user_guide/index.html), e gli [esempi](https://fairlearn.github.io/main/auto_examples/index.html)
- Si provino alcuni [notebook di esempio](https://github.com/fairlearn/fairlearn/tree/master/notebooks).
- Si scopra [come abilitare le valutazioni dell'equità](https://docs.microsoft.com/azure/machine-learning/how-to-machine-learning-fairness-aml?WT.mc_id=academic-15963-cxa) dei modelli di Machine Learning in Azure Machine Learning.
- Si dia un'occhiata a questi [notebook di esempio](https://github.com/Azure/MachineLearningNotebooks/tree/master/contrib/fairness) per ulteriori scenari di valutazione dell'equità in Azure Machine Learning.
---
## 🚀 Sfida
Per evitare che vengano introdotti pregiudizi, in primo luogo, si dovrebbe:
- avere una diversità di background e prospettive tra le persone che lavorano sui sistemi
- investire in insiemi di dati che riflettano le diversità della società
- sviluppare metodi migliori per rilevare e correggere i pregiudizi quando si verificano
Si pensi a scenari di vita reale in cui l'ingiustizia è evidente nella creazione e nell'utilizzo del modello. Cos'altro si dovrebbe considerare?
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/6/)
## Revisione e Auto Apprendimento
In questa lezione si sono apprese alcune nozioni di base sui concetti di equità e ingiustizia in machine learning.
Si guardi questo workshop per approfondire gli argomenti:
- YouTube: Danni correlati all'equità nei sistemi di IA: esempi, valutazione e mitigazione di Hanna Wallach e Miro Dudik [Danni correlati all'equità nei sistemi di IA: esempi, valutazione e mitigazione - YouTube](https://www.youtube.com/watch?v=1RptHwfkx_k)
Si legga anche:
- Centro risorse RAI di Microsoft: [risorse AI responsabili – Microsoft AI](https://www.microsoft.com/ai/responsible-ai-resources?activetab=pivot1%3aprimaryr4)
- Gruppo di ricerca FATE di Microsoft[: FATE: equità, responsabilità, trasparenza ed etica nell'intelligenza artificiale - Microsoft Research](https://www.microsoft.com/research/theme/fate/)
Si esplori il toolkit Fairlearn
[Fairlearn](https://fairlearn.org/)
Si scoprano gli strumenti di Azure Machine Learning per garantire l'equità
- [Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/concept-fairness-ml?WT.mc_id=academic-15963-cxa)
## Compito
[Esplorare Fairlearn](assignment.it.md)
# Equità e machine learning
![Riepilogo dell'equità in machine learning in uno sketchnote](../../../sketchnotes/ml-fairness.png)
> Sketchnote di [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Quiz pre-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/5/?loc=it)
## Introduzione
In questo programma di studi, si inizierà a scoprire come machine learning può e sta influenzando la vita quotidiana. Anche ora, sistemi e modelli sono coinvolti nelle attività decisionali quotidiane, come le diagnosi sanitarie o l'individuazione di frodi. Quindi è importante che questi modelli funzionino bene per fornire risultati equi per tutti.
Si immagini cosa può accadere quando i dati che si stanno utilizzando per costruire questi modelli mancano di determinati dati demografici, come razza, genere, visione politica, religione, o rappresentano tali dati demografici in modo sproporzionato. E quando il risultato del modello viene interpretato per favorire alcuni gruppi demografici? Qual è la conseguenza per l'applicazione?
In questa lezione, si dovrà:
- Aumentare la propria consapevolezza sull'importanza dell'equità nel machine learning.
- Informarsi sui danni legati all'equità.
- Apprendere ulteriori informazioni sulla valutazione e la mitigazione dell'ingiustizia.
## Prerequisito
Come prerequisito, si segua il percorso di apprendimento "Principi di AI Responsabile" e si guardi il video qui sotto sull'argomento:
Si scopra di più sull'AI Responsabile seguendo questo [percorso di apprendimento](https://docs.microsoft.com/learn/modules/responsible-ai-principles/?WT.mc_id=academic-15963-cxa)
[![L'approccio di Microsoft all'AI responsabileL'](https://img.youtube.com/vi/dnC8-uUZXSc/0.jpg)](https://youtu.be/dnC8-uUZXSc "approccio di Microsoft all'AI Responsabile")
> 🎥 Fare clic sull'immagine sopra per un video: L'approccio di Microsoft all'AI Responsabile
## Iniquità nei dati e negli algoritmi
> "Se si torturano i dati abbastanza a lungo, essi confesseranno qualsiasi cosa" - Ronald Coase
Questa affermazione suona estrema, ma è vero che i dati possono essere manipolati per supportare qualsiasi conclusione. Tale manipolazione a volte può avvenire involontariamente. Come esseri umani, abbiamo tutti dei pregiudizi, ed è spesso difficile sapere consapevolmente quando si introduce un pregiudizio nei dati.
Garantire l'equità nell'intelligenza artificiale e machine learning rimane una sfida socio-tecnica complessa. Ciò significa che non può essere affrontata da prospettive puramente sociali o tecniche.
### Danni legati all'equità
Cosa si intende per ingiustizia? L'"ingiustizia" comprende gli impatti negativi, o "danni", per un gruppo di persone, come quelli definiti in termini di razza, genere, età o stato di disabilità.
I principali danni legati all'equità possono essere classificati come:
- **Allocazione**, se un genere o un'etnia, ad esempio, sono preferiti a un altro.
- **Qualità di servizio** Se si addestrano i dati per uno scenario specifico, ma la realtà è molto più complessa, si ottiene un servizio scadente.
- **Stereotipi**. Associazione di un dato gruppo con attributi preassegnati.
- **Denigrazione**. Criticare ed etichettare ingiustamente qualcosa o qualcuno.
- **Sovra o sotto rappresentazione**. L'idea è che un certo gruppo non è visto in una certa professione, e qualsiasi servizio o funzione che continua a promuovere ciò, contribuisce al danno.
Si dia un'occhiata agli esempi.
### Allocazione
Si consideri un ipotetico sistema per la scrematura delle domande di prestito. Il sistema tende a scegliere gli uomini bianchi come candidati migliori rispetto ad altri gruppi. Di conseguenza, i prestiti vengono negati ad alcuni richiedenti.
Un altro esempio potrebbe essere uno strumento sperimentale di assunzione sviluppato da una grande azienda per selezionare i candidati. Lo strumento discrimina sistematicamente un genere utilizzando i modelli che sono stati addestrati a preferire parole associate con altro. Ha portato a penalizzare i candidati i cui curricula contengono parole come "squadra di rugby femminile".
✅ Si compia una piccola ricerca per trovare un esempio reale di qualcosa del genere
### Qualità di Servizio
I ricercatori hanno scoperto che diversi classificatori di genere commerciali avevano tassi di errore più elevati intorno alle immagini di donne con tonalità della pelle più scura rispetto alle immagini di uomini con tonalità della pelle più chiare. [Riferimento](https://www.media.mit.edu/publications/gender-shades-intersectional-accuracy-disparities-in-commercial-gender-classification/)
Un altro esempio infamante è un distributore di sapone per le mani che sembrava non essere in grado di percepire le persone con la pelle scura. [Riferimento](https://gizmodo.com/why-cant-this-soap-dispenser-identify-dark-skin-1797931773)
### Stereotipi
La visione di genere stereotipata è stata trovata nella traduzione automatica. Durante la traduzione in turco "he is a nurse and she is a doctor" (lui è un'infermiere e lei un medico), sono stati riscontrati problemi. Il turco è una lingua senza genere che ha un pronome, "o" per trasmettere una terza persona singolare, ma tradurre la frase dal turco all'inglese produce lo stereotipo e scorretto come "she is a nurse and he is a doctor" (lei è un'infermiera e lui è un medico).
![traduzione in turco](../images/gender-bias-translate-en-tr.png)
![Traduzione in inglese](../images/gender-bias-translate-tr-en.png)
### Denigrazione
Una tecnologia di etichettatura delle immagini ha contrassegnato in modo infamante le immagini di persone dalla pelle scura come gorilla. L'etichettatura errata è dannosa non solo perché il sistema ha commesso un errore, ma anche perché ha applicato specificamente un'etichetta che ha una lunga storia di essere intenzionalmente utilizzata per denigrare i neri.
[![AI: Non sono una donna?](https://img.youtube.com/vi/QxuyfWoVV98/0.jpg)](https://www.youtube.com/watch?v=QxuyfWoVV98 "AI, non sono una donna?")
> 🎥 Cliccare sull'immagine sopra per un video: AI, Ain't I a Woman - una performance che mostra il danno causato dalla denigrazione razzista da parte dell'AI
### Sovra o sotto rappresentazione
I risultati di ricerca di immagini distorti possono essere un buon esempio di questo danno. Quando si cercano immagini di professioni con una percentuale uguale o superiore di uomini rispetto alle donne, come l'ingegneria o CEO, si osserva che i risultati sono più fortemente distorti verso un determinato genere.
![Ricerca CEO di Bing](../images/ceos.png)
> Questa ricerca su Bing per "CEO" produce risultati piuttosto inclusivi
Questi cinque principali tipi di danno non si escludono a vicenda e un singolo sistema può presentare più di un tipo di danno. Inoltre, ogni caso varia nella sua gravità. Ad esempio, etichettare ingiustamente qualcuno come criminale è un danno molto più grave che etichettare erroneamente un'immagine. È importante, tuttavia, ricordare che anche danni relativamente non gravi possono far sentire le persone alienate o emarginate e l'impatto cumulativo può essere estremamente opprimente.
✅ **Discussione**: rivisitare alcuni degli esempi e vedere se mostrano danni diversi.
| | Allocatione | Qualita di servizio | Stereotipo | Denigrazione | Sovra o sotto rappresentazione |
| ----------------------------------- | :---------: | :-----------------: | :--------: | :----------: | :----------------------------: |
| Sistema di assunzione automatizzato | x | x | x | | x |
| Traduzione automatica | | | | | |
| Eitchettatura foto | | | | | |
## Rilevare l'ingiustizia
Ci sono molte ragioni per cui un dato sistema si comporta in modo scorretto. I pregiudizi sociali, ad esempio, potrebbero riflettersi nell'insieme di dati utilizzati per addestrarli. Ad esempio, l'ingiustizia delle assunzioni potrebbe essere stata esacerbata dall'eccessivo affidamento sui dati storici. Utilizzando i modelli nei curricula inviati all'azienda per un periodo di 10 anni, il modello ha determinato che gli uomini erano più qualificati perché la maggior parte dei curricula proveniva da uomini, un riflesso del passato dominio maschile nell'industria tecnologica.
Dati inadeguati su un determinato gruppo di persone possono essere motivo di ingiustizia. Ad esempio, i classificatori di immagini hanno un tasso di errore più elevato per le immagini di persone dalla pelle scura perché le tonalità della pelle più scure sono sottorappresentate nei dati.
Anche le ipotesi errate fatte durante lo sviluppo causano iniquità. Ad esempio, un sistema di analisi facciale destinato a prevedere chi commetterà un crimine basato sulle immagini dei volti delle persone può portare a ipotesi dannose. Ciò potrebbe portare a danni sostanziali per le persone classificate erroneamente.
## Si comprendano i propri modelli e si costruiscano in modo onesto
Sebbene molti aspetti dell'equità non vengano catturati nelle metriche di equità quantitativa e non sia possibile rimuovere completamente i pregiudizi da un sistema per garantire l'equità, si è comunque responsabili di rilevare e mitigare il più possibile i problemi di equità.
Quando si lavora con modelli di machine learning, è importante comprendere i propri modelli assicurandone l'interpretabilità e valutando e mitigando l'ingiustizia.
Si utilizza l'esempio di selezione del prestito per isolare il caso e determinare il livello di impatto di ciascun fattore sulla previsione.
## Metodi di valutazione
1. **Identificare i danni (e benefici)**. Il primo passo è identificare danni e benefici. Si pensi a come azioni e decisioni possono influenzare sia i potenziali clienti che un'azienda stessa.
1. **Identificare i gruppi interessati**. Una volta compreso il tipo di danni o benefici che possono verificarsi, identificare i gruppi che potrebbero essere interessati. Questi gruppi sono definiti per genere, etnia o gruppo sociale?
1. **Definire le metriche di equità**. Infine, si definisca una metrica in modo da avere qualcosa su cui misurare il proprio lavoro per migliorare la situazione.
### **Identificare danni (e benefici)**
Quali sono i danni e i benefici associati al prestito? Si pensi agli scenari di falsi negativi e falsi positivi:
**Falsi negativi** (rifiutato, ma Y=1) - in questo caso viene rifiutato un richiedente che sarà in grado di rimborsare un prestito. Questo è un evento avverso perché le risorse dei prestiti non sono erogate a richiedenti qualificati.
**Falsi positivi** (accettato, ma Y=0) - in questo caso, il richiedente ottiene un prestito ma alla fine fallisce. Di conseguenza, il caso del richiedente verrà inviato a un'agenzia di recupero crediti che può influire sulle sue future richieste di prestito.
### **Identificare i gruppi interessati**
Il passo successivo è determinare quali gruppi potrebbero essere interessati. Ad esempio, nel caso di una richiesta di carta di credito, un modello potrebbe stabilire che le donne dovrebbero ricevere limiti di credito molto più bassi rispetto ai loro coniugi che condividono i beni familiari. Un intero gruppo demografico, definito in base al genere, è così interessato.
### **Definire le metriche di equità**
Si sono identificati i danni e un gruppo interessato, in questo caso, delineato per genere. Ora, si usino i fattori quantificati per disaggregare le loro metriche. Ad esempio, utilizzando i dati di seguito, si può vedere che le donne hanno il più alto tasso di falsi positivi e gli uomini il più piccolo, e che è vero il contrario per i falsi negativi.
✅ In una futura lezione sul Clustering, si vedrà come costruire questa 'matrice di confusione' nel codice
| | percentuale di falsi positivi | Percentuale di falsi negativi | conteggio |
| ----------- | ----------------------------- | ----------------------------- | --------- |
| Donna | 0,37 | 0,27 | 54032 |
| Uomo | 0,31 | 0.35 | 28620 |
| Non binario | 0,33 | 0,31 | 1266 |
Questa tabella ci dice diverse cose. Innanzitutto, si nota che ci sono relativamente poche persone non binarie nei dati. I dati sono distorti, quindi si deve fare attenzione a come si interpretano questi numeri.
In questo caso, ci sono 3 gruppi e 2 metriche. Quando si pensa a come il nostro sistema influisce sul gruppo di clienti con i loro richiedenti di prestito, questo può essere sufficiente, ma quando si desidera definire un numero maggiore di gruppi, è possibile distillare questo in insiemi più piccoli di riepiloghi. Per fare ciò, si possono aggiungere più metriche, come la differenza più grande o il rapporto più piccolo di ogni falso negativo e falso positivo.
✅ Ci si fermi a pensare: quali altri gruppi potrebbero essere interessati dalla richiesta di prestito?
## Mitigare l'ingiustizia
Per mitigare l'ingiustizia, si esplori il modello per generare vari modelli mitigati e si confrontino i compromessi tra accuratezza ed equità per selezionare il modello più equo.
Questa lezione introduttiva non approfondisce i dettagli dell'algoritmo della mitigazione dell'ingiustizia, come l'approccio di post-elaborazione e riduzione, ma ecco uno strumento che si potrebbe voler provare.
### Fairlearn
[Fairlearn](https://fairlearn.github.io/) è un pacchetto Python open source che consente di valutare l'equità dei propri sistemi e mitigare l'ingiustizia.
Lo strumento consente di valutare in che modo le previsioni di un modello influiscono su diversi gruppi, consentendo di confrontare più modelli utilizzando metriche di equità e prestazioni e fornendo una serie di algoritmi per mitigare l'ingiustizia nella classificazione binaria e nella regressione.
- Si scopra come utilizzare i diversi componenti controllando il GitHub di [Fairlearn](https://github.com/fairlearn/fairlearn/)
- Si esplori la [guida per l'utente](https://fairlearn.github.io/main/user_guide/index.html), e gli [esempi](https://fairlearn.github.io/main/auto_examples/index.html)
- Si provino alcuni [notebook di esempio](https://github.com/fairlearn/fairlearn/tree/master/notebooks).
- Si scopra [come abilitare le valutazioni dell'equità](https://docs.microsoft.com/azure/machine-learning/how-to-machine-learning-fairness-aml?WT.mc_id=academic-15963-cxa) dei modelli di Machine Learning in Azure Machine Learning.
- Si dia un'occhiata a questi [notebook di esempio](https://github.com/Azure/MachineLearningNotebooks/tree/master/contrib/fairness) per ulteriori scenari di valutazione dell'equità in Azure Machine Learning.
---
## 🚀 Sfida
Per evitare che vengano introdotti pregiudizi, in primo luogo, si dovrebbe:
- avere una diversità di background e prospettive tra le persone che lavorano sui sistemi
- investire in insiemi di dati che riflettano le diversità della società
- sviluppare metodi migliori per rilevare e correggere i pregiudizi quando si verificano
Si pensi a scenari di vita reale in cui l'ingiustizia è evidente nella creazione e nell'utilizzo del modello. Cos'altro si dovrebbe considerare?
## [Quiz post-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/6/?loc=it)
## Revisione e Auto Apprendimento
In questa lezione si sono apprese alcune nozioni di base sui concetti di equità e ingiustizia in machine learning.
Si guardi questo workshop per approfondire gli argomenti:
- YouTube: Danni correlati all'equità nei sistemi di IA: esempi, valutazione e mitigazione di Hanna Wallach e Miro Dudik [Danni correlati all'equità nei sistemi di IA: esempi, valutazione e mitigazione - YouTube](https://www.youtube.com/watch?v=1RptHwfkx_k)
Si legga anche:
- Centro risorse RAI di Microsoft: [risorse AI responsabili – Microsoft AI](https://www.microsoft.com/ai/responsible-ai-resources?activetab=pivot1%3aprimaryr4)
- Gruppo di ricerca FATE di Microsoft[: FATE: equità, responsabilità, trasparenza ed etica nell'intelligenza artificiale - Microsoft Research](https://www.microsoft.com/research/theme/fate/)
Si esplori il toolkit Fairlearn
[Fairlearn](https://fairlearn.org/)
Si scoprano gli strumenti di Azure Machine Learning per garantire l'equità
- [Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/concept-fairness-ml?WT.mc_id=academic-15963-cxa)
## Compito
[Esplorare Fairlearn](assignment.it.md)

@ -3,7 +3,7 @@
![機械学習における公平性をまとめたスケッチ](../../../sketchnotes/ml-fairness.png)
> [Tomomi Imura](https://www.twitter.com/girlie_mac)によるスケッチ
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/5/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/5?loc=ja)
## イントロダクション
@ -88,11 +88,11 @@ AIや機械学習における公平性の保証は、依然として複雑な社
✅ **ディスカッション**: いくつかの例を再検討し、異なる害を示しているかどうかを確認してください。
| | アロケーション | サービスの質 | 固定観念 | 誹謗中傷 | 過剰表現/過小表現 |
| ----------------------- | :--------: | :----------------: | :----------: | :---------: | :----------------------------: |
| 採用システムの自動化 | x | x | x | | x |
| 機械翻訳 | | | | | |
| 写真のラベリング | | | | | |
| | アロケーション | サービスの質 | 固定観念 | 誹謗中傷 | 過剰表現/過小表現 |
| -------------------- | :------------: | :----------: | :------: | :------: | :---------------: |
| 採用システムの自動化 | x | x | x | | x |
| 機械翻訳 | | | | | |
| 写真のラベリング | | | | | |
## 不公平の検出
@ -134,11 +134,11 @@ AIや機械学習における公平性の保証は、依然として複雑な社
✅ 今後の"クラスタリング"のレッスンでは、この"混同行列"をコードで構築する方法をご紹介します。
| | 偽陽性率 | 偽陰性率 | サンプル数 |
| ---------- | ------------------- | ------------------- | ----- |
| 女性 | 0.37 | 0.27 | 54032 |
| 男性 | 0.31 | 0.35 | 28620 |
| どちらにも属さない | 0.33 | 0.31 | 1266 |
| | 偽陽性率 | 偽陰性率 | サンプル数 |
| ------------------ | -------- | -------- | ---------- |
| 女性 | 0.37 | 0.27 | 54032 |
| 男性 | 0.31 | 0.35 | 28620 |
| どちらにも属さない | 0.33 | 0.31 | 1266 |
この表から、いくつかのことがわかります。まず、データに含まれる男性と女性どちらでもない人が比較的少ないことがわかります。従ってこのデータは歪んでおり、この数字をどう解釈するかに注意が必要です。
@ -178,7 +178,7 @@ AIや機械学習における公平性の保証は、依然として複雑な社
モデルの構築や使用において、不公平が明らかになるような現実のシナリオを考えてみてください。他にどのようなことを考えるべきでしょうか?
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/6/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/6?loc=ja)
## Review & Self Study
このレッスンでは、機械学習における公平、不公平の概念の基礎を学びました。
@ -201,4 +201,4 @@ Azure Machine Learningによる、公平性を確保するためのツールに
## 課題
[Fairlearnを調査する](../assignment.md)
[Fairlearnを調査する](./assignment.ja.md)

@ -0,0 +1,214 @@
# 머신러닝의 공정성
![Summary of Fairness in Machine Learning in a sketchnote](../../../sketchnotes/ml-fairness.png)
> Sketchnote by [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [강의 전 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/5/)
## 소개
이 커리큘럼에서, 머신러닝이 우리의 생활에 어떻게 영향을 미칠 수 있는 지 알아보겠습니다. 지금도, 시스템과 모델은 건강 관리 진단 또는 사기 탐지와 같이 일상의 의사-결정 작업에 관여하고 있습니다. 따라서 모두에게 공정한 결과를 주기 위해서는 모델이 잘 작동하는게 중요합니다.
모델을 구축할 때 사용하는 데이터에 인종, 성별, 정치적 관점, 종교와 같이 특정 인구 통계가 부족하거나 불균형하게 나타내는 경우, 어떤 일이 발생할 지 상상해봅시다. 모델의 결과가 일부 인구 통계에 유리하도록 해석하는 경우는 어떨까요? 애플리케이션의 결과는 어떨까요?
이 강의에서, 아래 내용을 합니다:
- 머신러닝에서 공정성의 중요도에 대한 인식을 높입니다.
- 공정성-관련 피해에 대하여 알아봅니다.
- 불공정성 평가와 완화에 대하여 알아봅니다.
## 전제 조건
전제 조건으로, "Responsible AI Principles" 학습 과정을 수강하고 주제에 대한 영상을 시청합니다:
[Learning Path](https://docs.microsoft.com/learn/modules/responsible-ai-principles/?WT.mc_id=academic-15963-cxa)를 따라서 Responsible AI에 대하여 더 자세히 알아보세요
[![Microsoft's Approach to Responsible AI](https://img.youtube.com/vi/dnC8-uUZXSc/0.jpg)](https://youtu.be/dnC8-uUZXSc "Microsoft's Approach to Responsible AI")
> 🎥 영상을 보려면 이미지 클릭: Microsoft's Approach to Responsible AI
## 데이터와 알고리즘의 불공정성
> "If you torture the data long enough, it will confess to anything" - Ronald Coase
이 소리는 극단적이지만, 결론을 돕기 위하여 데이터를 조작할 수 있다는 건 사실입니다. 의도치않게 발생할 수 있습니다. 사람으로서, 모두 편견을 가지고 있고, 데이터에 편향적일 때 의식하는 것은 어렵습니다.
AI와 머신러닝의 공정성을 보장하는 건 계속 복잡한 사회기술적 도전 과제로 남고 있습니다. 순수하게 사화나 기술 관점에서 다룰 수 없다고 의미합니다.
### 공정성-관련 피해
불공정이란 무엇일까요? "Unfairness"은 인종, 성별, 나이, 또는 장애 등급으로 정의된 인구 그룹에 대한 부정적인 영향 혹은 "harms"를 포함합니다.
공정성-관련된 주요 피해는 다음처럼 분류할 수 있습니다:
- **할당**, 예를 들자면 성별이나 인종이 다른 사람들보다 선호되는 경우
- **서비스 품질**. 복잡할 때 한 특정 시나리오에 맞춰 데이터를 훈련하면, 서비스 성능이 낮아집니다.
- **고정관념**. 지정된 그룹을 사전에 할당한 속성에 넘깁니다.
- **명예훼손**. 무언가 누군가 부당한 비판하고 라벨링합니다.
- **과도- 또는 과소- 평가**. 아이디어는 특정 공언에서 그룹을 볼 수 없으며, 같이 피해를 입히는 서비스 혹은 기능을 꾸준히 홍보합니다.
이 예시를 보겠습니다.
### 할당
대출 심사하는 가상의 시스템을 생각해보세요. 이 시스템은 백인 남성을 다른 그룹보다 더 선택하는 경향이 있습니다. 결과적으로, 특정 지원자는 대출이 미뤄집니다.
또 다른 예시로는 후보를 뽑기 위해 대기업에서 개발한 실험적 채용 도구입니다. 모델을 사용하여 다른 단어를 선호하도록 훈련하며 하나의 성별을 특정할 수 있는 도구입니다. 이력서에 "women’s rugby team" 같은 단어가 포함되면 패널티가 주어졌습니다.
✅ 이런 실제 사례를 찾기 위하여 약간 조사해보세요
### 서비스 품질
연구원들은 여러가지 상용 성별 분류기에서 피부가 하얀 남성 이미지와 다르게 피부가 어두운 여성 이미지에서 오류 비율이 더 높다는 것을 발견했습니다. [Reference](https://www.media.mit.edu/publications/gender-shades-intersectional-accuracy-disparities-in-commercial-gender-classification/)
또 다른 이면에는 피부가 어두운 사람을 잘 인식하지 못하는 비누 디스펜서도 있습니다. [Reference](https://gizmodo.com/why-cant-this-soap-dispenser-identify-dark-skin-1797931773)
### 고정관념
기계 번역에서 성별에 대한 고정관념이 발견되었습니다. “he is a nurse and she is a doctor”라고 터키어로 번역할 때, 문제가 발생했습니다. 터키어는 3인칭을 전달하면서 "o"가 하나인 성별을 가지리지 않지만, 터키어에서 영어로 다시 문장을 번역해보면 “she is a nurse and he is a doctor”라는 고정관념과 부정확하게 반환됩니다.
![translation to Turkish](../images/gender-bias-translate-en-tr.png)
![translation back to English](../images/gender-bias-translate-tr-en.png)
### 명예훼손
이미지 라벨링 기술은 어두운-피부 사람의 이미지를 고릴라로 잘 못 분류했습니다. 잘 못 라벨링된 현상은 denigrate Black people된 오랜 역사를 라벨링하며 적용했으며 시스템이 실수했을 때 해롭습니다.
[![AI: Ain't I a Woman?](https://img.youtube.com/vi/QxuyfWoVV98/0.jpg)](https://www.youtube.com/watch?v=QxuyfWoVV98 "AI, Ain't I a Woman?")
> 🎥 영상을 보려면 이미지 클릭: AI, Ain't I a Woman - a performance showing the harm caused by racist denigration by AI
### 과도- 또는 과소- 평가
왜곡된 이미지 검색 결과가 이러한 피해의 올바른 예시가 됩니다. 공학, 또는 CEO와 같이, 여자보다 남자가 높거나 비슷한 비율의 직업 이미지를 검색할 때 특정 성별에 대하여 더 치우친 결과를 보여 줍니다.
![Bing CEO search](../images/ceos.png)
> This search on Bing for 'CEO' produces pretty inclusive results
5가지의 주요 피해 타입은 mutually exclusive적이지 않으며, 하나의 시스템이 여러 타입의 피해를 나타낼 수 있습니다. 또한, 각 사례들은 심각성이 다릅니다. 예를 들자면, 누군가 범죄자로 부적절하게 노출하는 것은 이미지를 잘못 보여주는 것보다 더 심한 피해입니다. 그러나, 중요한 점은, 상대적으로 심하지 않은 피해도 사람들이 소외감을 느끼거나 피하게 만들 수 있고 쌓인 영향은 꽤 부담이 될 수 있다는 점입니다.
✅ **토론**: 몇 가지 예시를 다시 보고 다른 피해가 발생했는지 확인해봅시다.
| | Allocation | Quality of service | Stereotyping | Denigration | Over- or under- representation |
| ----------------------- | :--------: | :----------------: | :----------: | :---------: | :----------------------------: |
| Automated hiring system | x | x | x | | x |
| Machine translation | | | | | |
| Photo labeling | | | | | |
## 불공정성 감지
주어진 시스템이 부당하게 동작하는 것은 여러 이유가 존재합니다. 사회 편견을, 예시로 들자면, 훈련에 사용한 데이터셋에 영향을 줄 수 있습니다. 예를 들자면, 채용 불공정성은 이전 데이터에 과하게 의존하여 더욱 악화되었을 가능성이 있습니다. 10년 넘게 회사에 제출된 이력서에서 패턴을 사용했으므로, 이 모델은 대부분의 이력서가 기술업의 과거 지배력을 반영했던 남자가 냈기 때문에 남자가 자격이 있다고 판단했습니다.
특정 그룹의 사람에 대한 적절하지 못한 데이터가 불공정의 이유가 될 수 있습니다. 예를 들자면, 이미지 분류기는 데이터에서 더 어두운 피부 톤를 underrepresented 했으므로 어두운-피부 사람 이미지에 대해 오류 비율이 더 높습니다.
개발하면서 잘 못된 가정을 하면 불공정성을 발생합니다. 예를 들자면, 사람들의 얼굴 이미지를 기반으로 범죄를 저지를 것 같은 사람을 예측하기 위한 얼굴 분석 시스템은 올바르지 못한 가정으로 이어질 수 있습니다. 이는 잘 못 분류된 사람들에게 큰 피해를 줄 수 있습니다.
## 모델 이해하고 공정성 구축하기
공정성의 많은 측면은 정량 공정성 지표에 보이지 않고, 공정성을 보장하기 위하여 시스템에서 편향성을 완전히 제거할 수 없지만, 여전히 공정성 문제를 최대한 파악하고 완화할 책임은 있습니다.
머신러닝 모델을 작업할 때, interpretability를 보장하고 불공정성을 평가하며 완화하여 모델을 이해하는 것이 중요합니다.
대출 선택 예시로 케이스를 분리하고 예측에 대한 각 영향 수준을 파악해보겠습니다.
## 평가 방식
1. **피해 (와 이익) 식별하기**. 첫 단계는 피해와 이익을 식별하는 것입니다. 행동과 결정이 잠재적 고객과 비지니스에 어떻게 영향을 미칠 지 생각해봅니다.
1. **영향받는 그룹 식별하기**. 어떤 종류의 피해나 이익을 발생할 수 있는지 파악했다면, 영향을 받을 수 있는 그룹을 식별합니다. 그룹은 성별, 인종, 또는 사회 집단으로 정의되나요?
1. **공정성 지표 정의하기**. 마지막으로, 지표를 정의하여 상황을 개선할 작업에서 특정할 무언가를 가집니다.
### 피해 (와 이익) 식별하기
대출과 관련한 피해와 이익은 어떤 것일까요? false negatives와 false positive 시나리오로 생각해보세요:
**False negatives** (거절, but Y=1) - 이 케이스와 같은 경우, 대출금을 상환할 수 있는 신청자가 거절됩니다. 자격있는 신청자에게 대출이 보류되기 때문에 불리한 이벤트입니다.
**False positives** (승인, but Y=0) - 이 케이스와 같은 경우, 신청자는 대출을 받지만 상환하지 못합니다. 결론적으로, 신청자의 케이스는 향후 대출에 영향을 미칠 수 있는 채권 추심으로 넘어갑니다.
### 영향 받는 그룹 식별
다음 단계는 영향을 받을 것 같은 그룹을 정의하는 것입니다. 예를 들자면, 신용카드를 신청하는 케이스인 경우, 모델은 여자가 가계 재산을 공유하는 배우자에 비해서 매우 낮은 신용도를 받아야 한다고 결정할 수 있습니다. 성별에 의해서, 정의된 전체 인구 통계가 영향 받습니다.
### 공정성 지표 정의
피해와 영향받는 그룹을 식별했습니다, 이 케이스와 같은 경우에는, 성별로 표기됩니다. 이제, 정량화된 원인으로 지표를 세분화합니다. 예시로, 아래 데이터를 사용하면, false positive 비율은 여자의 비율이 가장 크고 남자의 비율이 가장 낮으며, false negatives에서는 반대됩니다.
✅ Clustering에 대한 향후 강의에서는, 이 'confusion matrix'을 코드로 어떻게 작성하는 지 봅시다
| | False positive rate | False negative rate | count |
| ---------- | ------------------- | ------------------- | ----- |
| Women | 0.37 | 0.27 | 54032 |
| Men | 0.31 | 0.35 | 28620 |
| Non-binary | 0.33 | 0.31 | 1266 |
이 테이블은 몇 가지를 알려줍니다. 먼저, 데이터에 non-binary people이 비교적 적다는 것을 알 수 있습니다. 이 데이터는 왜곡되었으므로, 이런 숫자를 해석하는 것은 조심해야 합니다.
이러한 케이스는, 3개의 그룹과 2개의 지표가 존재합니다. 시스템이 대출 신청자와 함께 소비자 그룹에 어떤 영향을 미치는지 알아볼 때는, 충분할 수 있지만, 더 많은 수의 그룹을 정의하려는 경우, 더 작은 요약 셋으로 추출할 수 있습니다. 이를 위해서, 각 false negative와 false positive의 가장 큰 차이 또는 최소 비율과 같은, 지표를 더 추가할 수 있습니다.
✅ Stop and Think: 대출 신청에 영향을 받을 수 있는 다른 그룹이 있을까요?
## 불공정성 완화
불공정성 완화하려면, 모델을 탐색해서 다양하게 완화된 모델을 만들고 가장 공정한 모델을 선택하기 위하여 정확성과 공정성 사이 트레이드오프해서 비교합니다.
입문 강의에서는 post-processing 및 reductions approach과 같은 알고리즘 불공정성 완화에 대한, 세부적인 사항에 대해 깊게 설명하지 않지만, 여기에서 시도할 수 있는 도구가 있습니다.
### Fairlearn
[Fairlearn](https://fairlearn.github.io/)은 시스템의 공정성을 평가하고 불공정성을 완화할 수있는 오픈소스 Python 패키지입니다.
이 도구는 모델의 예측이 다른 그룹에 미치는 영향을 평가하며 돕고, 공정성과 성능 지표를 사용하여 여러 모델을 비교할 수 있으며, binary classification과 regression의 불공정성을 완화하는 알고리즘 셋을 제공할 수 있습니다.
- Fairlearn's [GitHub](https://github.com/fairlearn/fairlearn/)를 확인하고 다양한 컴포넌트를 어떻게 쓰는 지 알아보기.
- [user guide](https://fairlearn.github.io/main/user_guide/index.html), [examples](https://fairlearn.github.io/main/auto_examples/index.html) 탐색해보기.
- [sample notebooks](https://github.com/fairlearn/fairlearn/tree/master/notebooks) 시도해보기.
- Azure Machine Learning에서 머신러닝 모델의 [how to enable fairness assessments](https://docs.microsoft.com/azure/machine-learning/how-to-machine-learning-fairness-aml?WT.mc_id=academic-15963-cxa) 알아보기.
- Azure Machine Learning에서 더 공정한 평가 시나리오에 대하여 [sample notebooks](https://github.com/Azure/MachineLearningNotebooks/tree/master/contrib/fairness) 확인해보기.
---
## 🚀 도전
편견이 처음부터 들어오는 것을 막으려면, 이렇게 해야 합니다:
- 시스템을 작동하는 사람들 사이 다양한 배경과 관점을 가집니다
- 사회의 다양성을 반영하는 데이터 셋에 투자합니다
- 편향적일 때에 더 좋은 방법을 개발합니다
모델을 구축하고 사용하면서 불공정한 실-생활 시나리오를 생각해보세요. 어떻게 고려해야 하나요?
## [강의 후 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/6/)
## 검토 & 자기주도 학습
이 강의에서, 머신러닝의 공정성과 불공정성 개념에 대한 몇 가지 기본사항을 배웠습니다.
워크숍을 보고 토픽에 대하여 깊게 알아봅니다:
- YouTube: Fairness-related harms in AI systems: Examples, assessment, and mitigation by Hanna Wallach and Miro Dudik [Fairness-related harms in AI systems: Examples, assessment, and mitigation - YouTube](https://www.youtube.com/watch?v=1RptHwfkx_k)
또한, 읽어봅시다:
- Microsoft의 RAI 리소스 센터: [Responsible AI Resources – Microsoft AI](https://www.microsoft.com/ai/responsible-ai-resources?activetab=pivot1%3aprimaryr4)
- Microsoft의 FATE research 그룹: [FATE: Fairness, Accountability, Transparency, and Ethics in AI - Microsoft Research](https://www.microsoft.com/research/theme/fate/)
Fairlearn toolkit 탐색합니다
[Fairlearn](https://fairlearn.org/)
공정성을 보장하기 위한 Azure Machine Learning 도구에 대해 읽어봅시다
- [Azure Machine Learning](https://docs.microsoft.com/azure/machine-learning/concept-fairness-ml?WT.mc_id=academic-15963-cxa)
## 과제
[Explore Fairlearn](../assignment.md)

@ -1,9 +1,9 @@
# 机器学习中的公平性
![机器学习中的公平性概述](../../../sketchnotes/ml-fairness.png)
> 作者[Tomomi Imura](https://www.twitter.com/girlie_mac)
> 作者 [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [课前测验](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/5/)
## [课前测验](https://white-water-09ec41f0f.azurestaticapps.net/quiz/5/)
## 介绍
@ -76,29 +76,29 @@
一种图像标记技术,臭名昭著地将深色皮肤的人的图像错误地标记为大猩猩。错误的标签是有害的,不仅仅是因为这个系统犯了一个错误,而且它还特别使用了一个长期以来被故意用来诋毁黑人的标签。
[![AI: 我不是女人吗?](https://img.youtube.com/vi/QxuyfWoVV98/0.jpg)](https://www.youtube.com/watch?v=QxuyfWoVV98 "AI, 我不是女人吗?")
> 🎥 点击上图观看视频:AI,我不是女人吗 - 一场展示AI种族主义诋毁造成的伤害的表演
> 🎥 点击上图观看视频:AI,我不是女人吗 - 一场展示 AI 种族主义诋毁造成的伤害的表演
### 代表性过高或过低
有倾向性的图像搜索结果就是一个很好的例子。在搜索男性比例等于或高于女性的职业的图片时,比如工程或首席执行官,要注意那些更倾向于特定性别的结果。
![必应CEO搜索](../images/ceos.png)
> 在Bing上搜索“CEO”会得到非常全面的结果
> 在 Bing 上搜索“CEO”会得到非常全面的结果
这五种主要类型的危害不是相互排斥的,一个单一的系统可以表现出一种以上的危害。此外,每个案例的严重程度各不相同。例如,不公平地给某人贴上罪犯的标签比给形象贴上错误的标签要严重得多。然而,重要的是要记住,即使是相对不严重的伤害也会让人感到疏远或被孤立,累积的影响可能会非常压抑。
✅ **讨论**:重温一些例子,看看它们是否显示出不同的危害。
| | 分配 | 服务质量 | 刻板印象 | 诋毁 | 代表性过高或过低 |
| ----------------------- | :--------: | :----------------: | :----------: | :---------: | :----------------------------: |
| 自动招聘系统 | x | x | x | | x |
| 机器翻译 | | | | | |
| 照片加标签 | | | | | |
| | 分配 | 服务质量 | 刻板印象 | 诋毁 | 代表性过高或过低 |
| ------------ | :---: | :------: | :------: | :---: | :--------------: |
| 自动招聘系统 | x | x | x | | x |
| 机器翻译 | | | | | |
| 照片加标签 | | | | | |
## 检测不公平
给定系统行为不公平的原因有很多。例如,社会偏见可能会反映在用于训练它们的数据集中。例如,过度依赖历史数据可能会加剧招聘不公平。通过使用过去10年提交给公司的简历中的模式,该模型确定男性更合格,因为大多数简历来自男性,这反映了过去男性在整个科技行业的主导地位。
给定系统行为不公平的原因有很多。例如,社会偏见可能会反映在用于训练它们的数据集中。例如,过度依赖历史数据可能会加剧招聘不公平。通过使用过去 10 年提交给公司的简历中的模式,该模型确定男性更合格,因为大多数简历来自男性,这反映了过去男性在整个科技行业的主导地位。
关于特定人群的数据不足可能是不公平的原因。例如,图像分类器对于深肤色人的图像具有较高的错误率,因为数据中没有充分代表较深的肤色。
@ -124,9 +124,9 @@
与贷款相关的危害和好处是什么?想想假阴性和假阳性的情况:
**假阴性**(拒绝,但Y=1)-在这种情况下,将拒绝有能力偿还贷款的申请人。这是一个不利的事件,因为贷款的资源是从合格的申请人扣留。
**假阴性**(拒绝,但 Y=1)-在这种情况下,将拒绝有能力偿还贷款的申请人。这是一个不利的事件,因为贷款的资源是从合格的申请人扣留。
**假阳性**(接受,但Y=0)-在这种情况下,申请人确实获得了贷款,但最终违约。因此,申请人的案件将被送往一个债务催收机构,这可能会影响他们未来的贷款申请。
**假阳性**(接受,但 Y=0)-在这种情况下,申请人确实获得了贷款,但最终违约。因此,申请人的案件将被送往一个债务催收机构,这可能会影响他们未来的贷款申请。
### 确定受影响的群体
@ -138,16 +138,16 @@
✅ 在以后关于聚类的课程中,你将看到如何在代码中构建这个“混淆矩阵”
| | 假阳性率 | 假阴性率 | 数量 |
| ---------- | ------------------- | ------------------- | ----- |
| 女性 | 0.37 | 0.27 | 54032 |
| 男性 | 0.31 | 0.35 | 28620 |
| 未列出性别 | 0.33 | 0.31 | 1266 |
| | 假阳性率 | 假阴性率 | 数量 |
| ---------- | -------- | -------- | ----- |
| 女性 | 0.37 | 0.27 | 54032 |
| 男性 | 0.31 | 0.35 | 28620 |
| 未列出性别 | 0.33 | 0.31 | 1266 |
这个表格告诉我们几件事。首先,我们注意到数据中的未列出性别的人相对较少。数据是有偏差的,所以你需要小心解释这些数字。
在本例中,我们有3个组和2个度量。当我们考虑我们的系统如何影响贷款申请人的客户群时,这可能就足够了,但是当你想要定义更多的组时,你可能需要将其提取到更小的摘要集。为此,你可以添加更多的度量,例如每个假阴性和假阳性的最大差异或最小比率。
在本例中,我们有 3 个组和 2 个度量。当我们考虑我们的系统如何影响贷款申请人的客户群时,这可能就足够了,但是当你想要定义更多的组时,你可能需要将其提取到更小的摘要集。为此,你可以添加更多的度量,例如每个假阴性和假阳性的最大差异或最小比率。
✅ 停下来想一想:还有哪些群体可能会受到贷款申请的影响?
@ -159,19 +159,19 @@
### Fairlearn
[Fairlearn](https://fairlearn.github.io/) 是一个开源Python包,可让你评估系统的公平性并减轻不公平性。
[Fairlearn](https://fairlearn.github.io/) 是一个开源 Python 包,可让你评估系统的公平性并减轻不公平性。
该工具可帮助你评估模型的预测如何影响不同的组,使你能够通过使用公平性和性能指标来比较多个模型,并提供一组算法来减轻二元分类和回归中的不公平性。
- 通过查看Fairlearn的[GitHub](https://github.com/fairlearn/fairlearn/)了解如何使用不同的组件
- 通过查看 Fairlearn 的 [GitHub](https://github.com/fairlearn/fairlearn/) 了解如何使用不同的组件
- 浏览[用户指南](https://fairlearn.github.io/main/user_guide/index.html), [示例](https://fairlearn.github.io/main/auto_examples/index.html)
- 尝试一些 [示例Notebook](https://github.com/fairlearn/fairlearn/tree/master/notebooks).
- 尝试一些 [示例 Notebook](https://github.com/fairlearn/fairlearn/tree/master/notebooks).
- 了解Azure机器学习中机器学习模型[如何启用公平性评估](https://docs.microsoft.com/azure/machine-learning/how-to-machine-learning-fairness-aml?WT.mc_id=academic-15963-cxa)。
- 看看这些[示例Notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/contrib/fairness)了解Azure机器学习中的更多公平性评估场景。
- 看看这些[示例 Notebook](https://github.com/Azure/MachineLearningNotebooks/tree/master/contrib/fairness)了解 Azure 机器学习中的更多公平性评估场景。
---
## 🚀 挑战
@ -186,29 +186,29 @@
想想现实生活中的场景,在模型构建和使用中明显存在不公平。我们还应该考虑什么?
## [课后测验](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/6/)
## [课后测验](https://white-water-09ec41f0f.azurestaticapps.net/quiz/6/)
## 复习与自学
在本课中,你学习了机器学习中公平和不公平概念的一些基础知识。
观看本次研讨会,深入探讨以下主题:
- YouTube:人工智能系统中与公平相关的危害:示例、评估和缓解Hanna Wallach和Miro Dudik[人工智能系统中与公平相关的危害:示例、评估和缓解-YouTube](https://www.youtube.com/watch?v=1RptHwfkx_k)
- YouTube:人工智能系统中与公平相关的危害:示例、评估和缓解 Hanna Wallach 和 Miro Dudik[人工智能系统中与公平相关的危害:示例、评估和缓解-YouTube](https://www.youtube.com/watch?v=1RptHwfkx_k)
另外,请阅读:
- 微软RAI资源中心:[负责人工智能资源-微软人工智能](https://www.microsoft.com/ai/responsible-ai-resources?activetab=pivot1%3aprimaryr4)
- 微软FATE研究小组:[FATE:AI 中的公平、问责、透明和道德-微软研究院](https://www.microsoft.com/research/theme/fate/)
- 微软 FATE 研究小组:[FATE:AI 中的公平、问责、透明和道德-微软研究院](https://www.microsoft.com/research/theme/fate/)
探索Fairlearn工具箱
探索 Fairlearn 工具箱
[Fairlearn](https://fairlearn.org/)
了解Azure机器学习的工具以确保公平性
了解 Azure 机器学习的工具以确保公平性
- [Azure机器学习](https://docs.microsoft.com/azure/machine-learning/concept-fairness-ml?WT.mc_id=academic-15963-cxa)
- [Azure 机器学习](https://docs.microsoft.com/azure/machine-learning/concept-fairness-ml?WT.mc_id=academic-15963-cxa)
## 任务
[探索Fairlearn](../assignment.md)
[探索 Fairlearn](assignment.zh-cn.md)

@ -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,11 @@
# Fairlearnを調査する
## 指示
このレッスンでは、「データサイエンティストがAIシステムの公平性を向上させるための、オープンソースでコミュニティ主導のプロジェクト」であるFairlearnについて学習しました。この課題では、Fairlearnの [ノートブック](https://fairlearn.org/v0.6.2/auto_examples/index.html) のうちのひとつを調査し、わかったことをレポートやプレゼンテーションの形で報告してください。
## 評価基準
| 基準 | 模範的 | 十分 | 要改善 |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | -------------------------- |
| | Fairlearnのシステム・実行したノートブック・実行によって得られた結果が、レポートやパワーポイントのプレゼンテーションとして提示されている | 結論のないレポートが提示されている | レポートが提示されていない |

@ -0,0 +1,11 @@
# 探索 Fairlearn
## 说明
在这节课中,你了解了 Fairlearn,一个“开源的,社区驱动的项目,旨在帮助数据科学家们提高人工智能系统的公平性”。在这项作业中,探索 Fairlearn [笔记本](https://fairlearn.org/v0.6.2/auto_examples/index.html)中的一个例子,之后你可以用论文或者 ppt 的形式叙述你学习后的发现。
## 评判标准
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
| -------- | --------- | -------- | ----------------- |
| | 提交了一篇论文或者ppt 关于讨论 Fairlearn 系统、挑选运行的例子、和运行这个例子后所得出来的心得结论 | 提交了一篇没有结论的论文 | 没有提交论文 |

@ -4,8 +4,9 @@ The process of building, using, and maintaining machine learning models and the
- Understand the processes underpinning machine learning at a high level.
- Explore base concepts such as 'models', 'predictions', and 'training data'.
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/7/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/7/)
## Introduction
On a high level, the craft of creating machine learning (ML) processes is comprised of a number of steps:
@ -39,14 +40,20 @@ To be able to answer your question with any kind of certainty, you need a good a
✅ After collecting and processing your data, take a moment to see if its shape will allow you to address your intended question. It may be that the data will not perform well in your given task, as we discover in our [Clustering](../../5-Clustering/1-Visualize/README.md) lessons!
### Selecting your feature variable
### Features and Target
A [feature](https://www.datasciencecentral.com/profiles/blogs/an-introduction-to-variable-and-feature-selection) is a measurable property of your data. In many datasets it is expressed as a column heading like 'date' 'size' or 'color'. Your feature variable, usually represented as `X` in code, represent the input variable which will be used to train model.
A target is a thing you are trying to predict. Target usually represented as `y` in code, represents the answer to the question you are trying to ask of your data: in December, what **color** pumpkins will be cheapest? in San Francisco, what neighborhoods will have the best real estate **price**? Sometimes target is also referred as label attribute.
A [feature](https://www.datasciencecentral.com/profiles/blogs/an-introduction-to-variable-and-feature-selection) is a measurable property of your data. In many datasets it is expressed as a column heading like 'date' 'size' or 'color'. Your feature variable, usually represented as `y` in code, represents the answer to the question you are trying to ask of your data: in December, what **color** pumpkins will be cheapest? in San Francisco, what neighborhoods will have the best real estate **price**?
### Selecting your feature variable
🎓 **Feature Selection and Feature Extraction** How do you know which variable to choose when building a model? You'll probably go through a process of feature selection or feature extraction to choose the right variables for the most performant model. They're not the same thing, however: "Feature extraction creates new features from functions of the original features, whereas feature selection returns a subset of the features." ([source](https://wikipedia.org/wiki/Feature_selection))
### Visualize your data
An important aspect of the data scientist's toolkit is the power to visualize data using several excellent libraries such as Seaborn or MatPlotLib. Representing your data visually might allow you to uncover hidden correlations that you can leverage. Your visualizations might also help you to uncover bias or unbalanced data (as we discover in [Classification](../../4-Classification/2-Classifiers-1/README.md)).
An important aspect of the data scientist's toolkit is the power to visualize data using several excellent libraries such as Seaborn or MatPlotLib. Representing your data visually might allow you to uncover hidden correlations that you can leverage. Your visualizations might also help you to uncover bias or unbalanced data (as we discover in [Classification](../../4-Classification/2-Classifiers-1/README.md)).
### Split your dataset
Prior to training, you need to split your dataset into two or more parts of unequal size that still represent the data well.
@ -61,10 +68,12 @@ Using your training data, your goal is to build a model, or a statistical repres
### Decide on a training method
Depending on your question and the nature of your data, your will choose a method to train it. Stepping through [Scikit-learn's documentation](https://scikit-learn.org/stable/user_guide.html) - which we use in this course - you can explore many ways to train a model. Depending on your experience, you might have to try several different methods to build the best model. You are likely to go through a process whereby data scientists evaluate the performance of a model by feeding it unseen data, checking for accuracy, bias, and other quality-degrading issues, and selecting the most appropriate training method for the task at hand.
Depending on your question and the nature of your data, you will choose a method to train it. Stepping through [Scikit-learn's documentation](https://scikit-learn.org/stable/user_guide.html) - which we use in this course - you can explore many ways to train a model. Depending on your experience, you might have to try several different methods to build the best model. You are likely to go through a process whereby data scientists evaluate the performance of a model by feeding it unseen data, checking for accuracy, bias, and other quality-degrading issues, and selecting the most appropriate training method for the task at hand.
### Train a model
Armed with your training data, you are ready to 'fit' it to create a model. You will notice that in many ML libraries you will find the code 'model.fit' - it is at this time that you send in your data as an array of values (usually 'X') and a feature variable (usually 'y').
Armed with your training data, you are ready to 'fit' it to create a model. You will notice that in many ML libraries you will find the code 'model.fit' - it is at this time that you send in your feature variable as an array of values (usually 'X') and a target variable (usually 'y').
### Evaluate the model
Once the training process is complete (it can take many iterations, or 'epochs', to train a large model), you will be able to evaluate the model's quality by using test data to gauge its performance. This data is a subset of the original data that the model has not previously analyzed. You can print out a table of metrics about your model's quality.
@ -94,7 +103,7 @@ In these lessons, you will discover how to use these steps to prepare, build, te
Draw a flow chart reflecting the steps of a ML practitioner. Where do you see yourself right now in the process? Where do you predict you will find difficulty? What seems easy to you?
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/8/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/8/)
## Review & Self Study

@ -0,0 +1,112 @@
# 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://white-water-09ec41f0f.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)!
### Características y destino
Una característica es una propiedad medible de los datos.En muchos conjuntos de datos se expresa como un encabezado de columna como 'date' 'size' o 'color'. La variable de entidad, normalmente representada como `X` en el código, representa la variable de entrada que se utilizará para entrenar el modelo.
Un objetivo es una cosa que está tratando de predecir. Target generalmente representado como `y` en el código, representa la respuesta a la pregunta que está tratando de hacer de sus datos: en diciembre, ¿qué color de calabazas serán más baratas? en San Francisco, ¿qué barrios tendrán el mejor precio de bienes raíces? A veces, target también se conoce como atributo label.
### Seleccionando su variable característica
🎓 **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 "ajustarlo" para crear un modelo. Notará que en muchas bibliotecas de ML encontrará el código 'model.fit' - es en este momento que envía su variable de característica como una matriz de valores (generalmente `X`) y una variable de destino (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'.
![overfitting model](images/overfitting.png)
> 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 posterior a la conferencia](https://white-water-09ec41f0f.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,111 @@
# 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://white-water-09ec41f0f.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).
### Fitur dan Target
Fitur adalah properti terukur dari data Anda. Dalam banyak set data, data tersebut dinyatakan sebagai judul kolom seperti 'date' 'size' atau 'color'. Variabel fitur Anda, biasanya direpresentasikan sebagai `X` dalam kode, mewakili variabel input yang akan digunakan untuk melatih model.
A target is a thing you are trying to predict. Target usually represented as `y` in code, represents the answer to the question you are trying to ask of your data: in December, what color pumpkins will be cheapest? in San Francisco, what neighborhoods will have the best real estate price? Sometimes target is also referred as label attribute.
### Memilih variabel fiturmu
🎓 **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
Berbekan dengan data pelatihan Anda, Anda siap untuk 'menyesuaikan' untuk membuat model. Anda akan melihat bahwa di banyak perpustakaan ML Anda akan menemukan kode 'model.fit' - saat inilah Anda mengirim variabel fitur Anda sebagai array nilai (biasanya `X`) dan variabel target (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.
![overfitting model](../images/overfitting.png)
> 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://white-water-09ec41f0f.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)

@ -1,110 +1,114 @@
# Tecniche di Machine Learning
Il processo di creazione, utilizzo e mantenimento dei modelli di machine learning e dei dati che utilizzano è un processo molto diverso da molti altri flussi di lavoro di sviluppo. In questa lezione si demistifica il processo, e si delineano le principali tecniche che occorre conoscere. Si dovrà:
- Comprendere i processi ad alto livello alla base di machine learning.
- Esplorare concetti di base come "modelli", "previsioni" e "dati di addestramento".
## [Quiz Pre-Lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/7/)
## Introduzione
Ad alto livello, il mestiere di creare processi di apprendimento automatico (ML) comprende una serie di passaggi:
1. **Decidere circa la domanda**. La maggior parte dei processi ML inizia ponendo una domanda alla quale non è possibile ottenere risposta da un semplice programma condizionale o da un motore basato su regole. Queste domande spesso ruotano attorno a previsioni basate su una raccolta di dati.
2. **Raccogliere e preparare i dati**. Per poter rispondere alla domanda, servono dati. La qualità e, a volte, la quantità dei dati determineranno quanto bene sarà possibile rispondere alla domanda iniziale. La visualizzazione dei dati è un aspetto importante di questa fase. Questa fase include anche la suddivisione dei dati in un gruppo di addestramento (training) e test per costruire un modello.
3. **Scegliere un metodo di addestramento**. A seconda della domanda e della natura dei dati, è necessario scegliere come si desidera addestrare un modello per riflettere al meglio i dati e fare previsioni accurate su di essi. Questa è la parte del processo di ML che richiede competenze specifiche e, spesso, una notevole quantità di sperimentazione.
4. **Addestrare il modello**. Usando i dati di addestramento, si utilizzeranno vari algoritmi per addestrare un modello a riconoscere modelli nei dati. Il modello potrebbe sfruttare pesi interni che possono essere regolati per privilegiare alcune parti dei dati rispetto ad altre per costruire un modello migliore.
5. **Valutare il modello**. Si utilizzano dati mai visti prima (i dati di test) da quelli raccolti per osservare le prestazioni del modello.
6. **Regolazione dei parametri**. In base alle prestazioni del modello, si può ripetere il processo utilizzando parametri differenti, o variabili, che controllano il comportamento degli algoritmi utilizzati per addestrare il modello.
7. **Prevedere**. Usare nuovi input per testare la precisione del modello.
## Che domanda fare
I computer sono particolarmente abili nello scoprire modelli nascosti nei dati. Questa caratteristica è molto utile per i ricercatori che hanno domande su un determinato campo a cui non è possibile rispondere facilmente creando un motore di regole basato su condizioni. Dato un compito attuariale, ad esempio, un data scientist potrebbe essere in grado di costruire manualmente regole sulla mortalità dei fumatori rispetto ai non fumatori.
Quando molte altre variabili vengono introdotte nell'equazione, tuttavia, un modello ML potrebbe rivelarsi più efficiente per prevedere i tassi di mortalità futuri in base alla storia sanitaria passata. Un esempio più allegro potrebbe essere fare previsioni meteorologiche per il mese di aprile in una determinata località sulla base di dati che includono latitudine, longitudine, cambiamento climatico, vicinanza all'oceano, modelli della corrente a getto e altro ancora.
✅ Questa [presentazione](https://www2.cisl.ucar.edu/sites/default/files/0900%20June%2024%20Haupt_0.pdf) sui modelli meteorologici offre una prospettiva storica per l'utilizzo di ML nell'analisi meteorologica.
## Attività di pre-costruzione
Prima di iniziare a costruire il proprio modello, ci sono diverse attività da completare. Per testare la domanda e formare un'ipotesi basata sulle previsioni di un modello, occorre identificare e configurare diversi elementi.
### Dati
Per poter rispondere con sicurezza alla domanda, serve una buona quantità di dati del tipo giusto. Ci sono due cose da fare a questo punto:
- **Raccogliere dati**. Tenendo presente la lezione precedente sull'equità nell'analisi dei dati, si raccolgano i dati con cura. Ci sia consapevolezza delle fonti di questi dati, di eventuali pregiudizi intrinseci che potrebbero avere e si documenti la loro origine.
- **Preparare i dati**. Ci sono diversi passaggi nel processo di preparazione dei dati. Potrebbe essere necessario raccogliere i dati e normalizzarli se provengono da fonti diverse. Si può migliorare la qualità e la quantità dei dati attraverso vari metodi come la conversione di stringhe in numeri (come si fa in [Clustering](../../../5-Clustering/1-Visualize/transaltions/README.it.md)). Si potrebbero anche generare nuovi dati, basati sull'originale (come si fa in [Classificazione](../../../4-Classification/1-Introduction/translations/README.it.md)). Si possono pulire e modificare i dati (come verrà fatto prima della lezione sull'[app Web](../../../3-Web-App/translations/README.it.md) ). Infine, si potrebbe anche aver bisogno di renderli casuali e mescolarli, a seconda delle proprie tecniche di addestramento.
✅ Dopo aver raccolto ed elaborato i propri dati, si prenda un momento per vedere se la loro forma consentirà di rispondere alla domanda prevista. Potrebbe essere che i dati non funzionino bene nello svolgere il compito assegnato, come si scopre nelle lezioni di [Clustering](../../../5-Clustering/1-Visualize/translations/README.it.md)!
### Selezione della variabile caratteristica
Una [caratteristica](https://www.datasciencecentral.com/profiles/blogs/an-introduction-to-variable-and-feature-selection) è una proprietà misurabile dei propri dati. In molti insiemi di dati è espressa come un'intestazione di colonna come "data", "dimensione" o "colore". La propria variabile caratteristica, solitamente rappresentata come `y` nel codice, rappresenta la risposta alla domanda che si sta cercando di porre ai propri dati: a dicembre, di che **colore** saranno le zucche più economiche? A San Francisco, quali quartieri avranno il miglior **prezzo** immobiliare?
🎓 **Selezione ed estrazione della caratteristica** Come si fa a sapere quale variabile scegliere quando si costruisce un modello? Probabilmente si dovrà passare attraverso un processo di selezione o estrazione delle caratteristiche per scegliere le variabili giuste per il modello più efficace. Tuttavia, non è la stessa cosa: "L'estrazione delle caratteristiche crea nuove caratteristiche dalle funzioni delle caratteristiche originali, mentre la selezione delle caratteristiche restituisce un sottoinsieme delle caratteristiche". ([fonte](https://it.wikipedia.org/wiki/Selezione_delle_caratteristiche))
### Visualizzare i dati
Un aspetto importante del bagaglio del data scientist è la capacità di visualizzare i dati utilizzando diverse eccellenti librerie come Seaborn o MatPlotLib. Rappresentare visivamente i propri dati potrebbe consentire di scoprire correlazioni nascoste che si possono sfruttare. Le visualizzazioni potrebbero anche aiutare a scoprire pregiudizi o dati sbilanciati (come si scopre in [Classificazione](../../../4-Classification/2-Classifiers-1/translations/README.it.md)).
### Dividere l'insieme di dati
Prima dell'addestramento, è necessario dividere l'insieme di dati in due o più parti di dimensioni diverse che rappresentano comunque bene i dati.
- **Addestramento**. Questa parte dell'insieme di dati è adatta al proprio modello per addestrarlo. Questo insieme costituisce la maggior parte dell'insieme di dati originale.
- **Test**. Un insieme di dati di test è un gruppo indipendente di dati, spesso raccolti dai dati originali, che si utilizzano per confermare le prestazioni del modello creato.
- **Convalida**. Un insieme di convalida è un gruppo indipendente più piccolo di esempi da usare per ottimizzare gli iperparametri, o architettura, del modello per migliorarlo. A seconda delle dimensioni dei propri dati e della domanda che si sta ponendo, si potrebbe non aver bisogno di creare questo terzo insieme (come si nota in [Previsione delle Serie Temporali](../../../7-TimeSeries/1-Introduction/translations/README.it.md)).
## Costruire un modello
Utilizzando i dati di addestramento, l'obiettivo è costruire un modello o una rappresentazione statistica dei propri dati, utilizzando vari algoritmi per **addestrarlo** . L'addestramento di un modello lo espone ai dati e consente di formulare ipotesi sui modelli percepiti che scopre, convalida e accetta o rifiuta.
### Decidere un metodo di addestramento
A seconda della domanda e della natura dei dati, si sceglierà un metodo per addestrarlo. Passando attraverso [la documentazione di Scikit-learn](https://scikit-learn.org/stable/user_guide.html), che si usa in questo corso, si possono esplorare molti modi per addestrare un modello. A seconda della propria esperienza, si potrebbe dover provare diversi metodi per creare il modello migliore. È probabile che si attraversi un processo in cui i data scientist valutano le prestazioni di un modello fornendogli dati non visti, verificandone l'accuratezza, i pregiudizi e altri problemi che degradano la qualità e selezionando il metodo di addestramento più appropriato per l'attività da svolgere.
### Allenare un modello
Occorre armarsi dei propri dati di allenamento, per essere pronti per "adattarli" per creare un modello. Si noterà che in molte librerie ML si trova il codice "model.fit" - è in questo momento che si inviano i propri dati come un vettore di valori (di solito "X") e una variabile di caratteristica (di solito "y" ).
### Valutare il modello
Una volta completato il processo di addestramento (potrebbero essere necessarie molte iterazioni, o "epoche", per addestrare un modello di grandi dimensioni), si sarà in grado di valutare la qualità del modello utilizzando i dati di test per valutarne le prestazioni. Questi dati sono un sottoinsieme dei dati originali che il modello non ha analizzato in precedenza. Si può stampare una tabella di metriche sulla qualità del proprio modello.
🎓 **Adattamento del modello**
Nel contesto di machine learning, l'adattamento del modello si riferisce all'accuratezza della funzione sottostante del modello mentre tenta di analizzare dati con cui non ha familiarità.
🎓 **Inadeguatezza** o **sovraadattamento** sono problemi comuni che degradano la qualità del modello, poiché il modello non si adatta abbastanza bene o troppo bene. Ciò fa sì che il modello esegua previsioni troppo allineate o troppo poco allineate con i suoi dati di addestramento. Un modello overfit (sovraaddestrato) prevede troppo bene i dati di addestramento perché ha appreso troppo bene i dettagli e il rumore dei dati. Un modello underfit (inadeguato) non è accurato in quanto non può né analizzare accuratamente i suoi dati di allenamento né i dati che non ha ancora "visto".
![modello sovraaddestrato](../images/overfitting.png)
> Infografica di [Jen Looper](https://twitter.com/jenlooper)
## Sintonia dei parametri
Una volta completato l'addestramento iniziale, si osservi la qualità del modello e si valuti di migliorarlo modificando i suoi "iperparametri". Maggiori informazioni sul processo [nella documentazione](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters?WT.mc_id=academic-15963-cxa).
## Previsione
Questo è il momento in cui si possono utilizzare dati completamente nuovi per testare l'accuratezza del proprio modello. In un'impostazione ML "applicata", in cui si creano risorse Web per utilizzare il modello in produzione, questo processo potrebbe comportare la raccolta dell'input dell'utente (ad esempio, la pressione di un pulsante) per impostare una variabile e inviarla al modello per l'inferenza, oppure valutazione.
In queste lezioni si scoprirà come utilizzare questi passaggi per preparare, costruire, testare, valutare e prevedere - tutti gesti di un data scientist e altro ancora, mentre si avanza nel proprio viaggio per diventare un ingegnere ML "full stack".
---
## 🚀 Sfida
Disegnare un diagramma di flusso che rifletta i passaggi di un professionista di ML. Dove ci si vede in questo momento nel processo? Dove si prevede che sorgeranno difficoltà? Cosa sembra facile?
## [Quiz post-lezione](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/8/)
## Revisione e Auto Apprendimento
Cercare online le interviste con i data scientist che discutono del loro lavoro quotidiano. Eccone [una](https://www.youtube.com/watch?v=Z3IjgbbCEfs).
## Compito
[Intervista a un data scientist](assignment.it.md)
# Tecniche di Machine Learning
Il processo di creazione, utilizzo e mantenimento dei modelli di machine learning e dei dati che utilizzano è un processo molto diverso da molti altri flussi di lavoro di sviluppo. In questa lezione si demistifica il processo, e si delineano le principali tecniche che occorre conoscere. Si dovrà:
- Comprendere i processi ad alto livello alla base di machine learning.
- Esplorare concetti di base come "modelli", "previsioni" e "dati di addestramento".
## [Quiz pre-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/7/?loc=it)
## Introduzione
Ad alto livello, il mestiere di creare processi di apprendimento automatico (ML) comprende una serie di passaggi:
1. **Decidere circa la domanda**. La maggior parte dei processi ML inizia ponendo una domanda alla quale non è possibile ottenere risposta da un semplice programma condizionale o da un motore basato su regole. Queste domande spesso ruotano attorno a previsioni basate su una raccolta di dati.
2. **Raccogliere e preparare i dati**. Per poter rispondere alla domanda, servono dati. La qualità e, a volte, la quantità dei dati determineranno quanto bene sarà possibile rispondere alla domanda iniziale. La visualizzazione dei dati è un aspetto importante di questa fase. Questa fase include anche la suddivisione dei dati in un gruppo di addestramento (training) e test per costruire un modello.
3. **Scegliere un metodo di addestramento**. A seconda della domanda e della natura dei dati, è necessario scegliere come si desidera addestrare un modello per riflettere al meglio i dati e fare previsioni accurate su di essi. Questa è la parte del processo di ML che richiede competenze specifiche e, spesso, una notevole quantità di sperimentazione.
4. **Addestrare il modello**. Usando i dati di addestramento, si utilizzeranno vari algoritmi per addestrare un modello a riconoscere modelli nei dati. Il modello potrebbe sfruttare pesi interni che possono essere regolati per privilegiare alcune parti dei dati rispetto ad altre per costruire un modello migliore.
5. **Valutare il modello**. Si utilizzano dati mai visti prima (i dati di test) da quelli raccolti per osservare le prestazioni del modello.
6. **Regolazione dei parametri**. In base alle prestazioni del modello, si può ripetere il processo utilizzando parametri differenti, o variabili, che controllano il comportamento degli algoritmi utilizzati per addestrare il modello.
7. **Prevedere**. Usare nuovi input per testare la precisione del modello.
## Che domanda fare
I computer sono particolarmente abili nello scoprire modelli nascosti nei dati. Questa caratteristica è molto utile per i ricercatori che hanno domande su un determinato campo a cui non è possibile rispondere facilmente creando un motore di regole basato su condizioni. Dato un compito attuariale, ad esempio, un data scientist potrebbe essere in grado di costruire manualmente regole sulla mortalità dei fumatori rispetto ai non fumatori.
Quando molte altre variabili vengono introdotte nell'equazione, tuttavia, un modello ML potrebbe rivelarsi più efficiente per prevedere i tassi di mortalità futuri in base alla storia sanitaria passata. Un esempio più allegro potrebbe essere fare previsioni meteorologiche per il mese di aprile in una determinata località sulla base di dati che includono latitudine, longitudine, cambiamento climatico, vicinanza all'oceano, modelli della corrente a getto e altro ancora.
✅ Questa [presentazione](https://www2.cisl.ucar.edu/sites/default/files/0900%20June%2024%20Haupt_0.pdf) sui modelli meteorologici offre una prospettiva storica per l'utilizzo di ML nell'analisi meteorologica.
## Attività di pre-costruzione
Prima di iniziare a costruire il proprio modello, ci sono diverse attività da completare. Per testare la domanda e formare un'ipotesi basata sulle previsioni di un modello, occorre identificare e configurare diversi elementi.
### Dati
Per poter rispondere con sicurezza alla domanda, serve una buona quantità di dati del tipo giusto. Ci sono due cose da fare a questo punto:
- **Raccogliere dati**. Tenendo presente la lezione precedente sull'equità nell'analisi dei dati, si raccolgano i dati con cura. Ci sia consapevolezza delle fonti di questi dati, di eventuali pregiudizi intrinseci che potrebbero avere e si documenti la loro origine.
- **Preparare i dati**. Ci sono diversi passaggi nel processo di preparazione dei dati. Potrebbe essere necessario raccogliere i dati e normalizzarli se provengono da fonti diverse. Si può migliorare la qualità e la quantità dei dati attraverso vari metodi come la conversione di stringhe in numeri (come si fa in [Clustering](../../../5-Clustering/1-Visualize/transaltions/README.it.md)). Si potrebbero anche generare nuovi dati, basati sull'originale (come si fa in [Classificazione](../../../4-Classification/1-Introduction/translations/README.it.md)). Si possono pulire e modificare i dati (come verrà fatto prima della lezione sull'[app Web](../../../3-Web-App/translations/README.it.md) ). Infine, si potrebbe anche aver bisogno di renderli casuali e mescolarli, a seconda delle proprie tecniche di addestramento.
✅ Dopo aver raccolto ed elaborato i propri dati, si prenda un momento per vedere se la loro forma consentirà di rispondere alla domanda prevista. Potrebbe essere che i dati non funzionino bene nello svolgere il compito assegnato, come si scopre nelle lezioni di [Clustering](../../../5-Clustering/1-Visualize/translations/README.it.md)!
### Caratteristiche e destinazione
Una caratteristica è una proprietà misurabile dei dati. In molti set di dati è espresso come intestazione di colonna come 'date' 'size' o 'color'. La variabile di caratteristica, solitamente rappresentata come `X` nel codice, rappresenta la variabile di input che verrà utilizzata per il training del modello.
Un obiettivo è una cosa che stai cercando di prevedere. Target solitamente rappresentato come `y` nel codice, rappresenta la risposta alla domanda che stai cercando di porre dei tuoi dati: a dicembre, di che colore saranno le zucche più economiche? a San Francisco, quali quartieri avranno il miglior prezzo immobiliare? A volte la destinazione viene anche definita attributo label.
### Selezione della variabile caratteristica
🎓 **Selezione ed estrazione della caratteristica** Come si fa a sapere quale variabile scegliere quando si costruisce un modello? Probabilmente si dovrà passare attraverso un processo di selezione o estrazione delle caratteristiche per scegliere le variabili giuste per il modello più efficace. Tuttavia, non è la stessa cosa: "L'estrazione delle caratteristiche crea nuove caratteristiche dalle funzioni delle caratteristiche originali, mentre la selezione delle caratteristiche restituisce un sottoinsieme delle caratteristiche". ([fonte](https://it.wikipedia.org/wiki/Selezione_delle_caratteristiche))
### Visualizzare i dati
Un aspetto importante del bagaglio del data scientist è la capacità di visualizzare i dati utilizzando diverse eccellenti librerie come Seaborn o MatPlotLib. Rappresentare visivamente i propri dati potrebbe consentire di scoprire correlazioni nascoste che si possono sfruttare. Le visualizzazioni potrebbero anche aiutare a scoprire pregiudizi o dati sbilanciati (come si scopre in [Classificazione](../../../4-Classification/2-Classifiers-1/translations/README.it.md)).
### Dividere l'insieme di dati
Prima dell'addestramento, è necessario dividere l'insieme di dati in due o più parti di dimensioni diverse che rappresentano comunque bene i dati.
- **Addestramento**. Questa parte dell'insieme di dati è adatta al proprio modello per addestrarlo. Questo insieme costituisce la maggior parte dell'insieme di dati originale.
- **Test**. Un insieme di dati di test è un gruppo indipendente di dati, spesso raccolti dai dati originali, che si utilizzano per confermare le prestazioni del modello creato.
- **Convalida**. Un insieme di convalida è un gruppo indipendente più piccolo di esempi da usare per ottimizzare gli iperparametri, o architettura, del modello per migliorarlo. A seconda delle dimensioni dei propri dati e della domanda che si sta ponendo, si potrebbe non aver bisogno di creare questo terzo insieme (come si nota in [Previsione delle Serie Temporali](../../../7-TimeSeries/1-Introduction/translations/README.it.md)).
## Costruire un modello
Utilizzando i dati di addestramento, l'obiettivo è costruire un modello o una rappresentazione statistica dei propri dati, utilizzando vari algoritmi per **addestrarlo** . L'addestramento di un modello lo espone ai dati e consente di formulare ipotesi sui modelli percepiti che scopre, convalida e accetta o rifiuta.
### Decidere un metodo di addestramento
A seconda della domanda e della natura dei dati, si sceglierà un metodo per addestrarlo. Passando attraverso [la documentazione di Scikit-learn](https://scikit-learn.org/stable/user_guide.html), che si usa in questo corso, si possono esplorare molti modi per addestrare un modello. A seconda della propria esperienza, si potrebbe dover provare diversi metodi per creare il modello migliore. È probabile che si attraversi un processo in cui i data scientist valutano le prestazioni di un modello fornendogli dati non visti, verificandone l'accuratezza, i pregiudizi e altri problemi che degradano la qualità e selezionando il metodo di addestramento più appropriato per l'attività da svolgere.
### Allenare un modello
Armati dei tuoi dati di allenamento, sei pronto a "adattarlo" per creare un modello. Noterai che in molte librerie ML troverai il codice "model.fit" - è in questo momento che invii la tua variabile di funzionalità come matrice di valori (in genere `X`) e una variabile di destinazione (di solito `y`).
### Valutare il modello
Una volta completato il processo di addestramento (potrebbero essere necessarie molte iterazioni, o "epoche", per addestrare un modello di grandi dimensioni), si sarà in grado di valutare la qualità del modello utilizzando i dati di test per valutarne le prestazioni. Questi dati sono un sottoinsieme dei dati originali che il modello non ha analizzato in precedenza. Si può stampare una tabella di metriche sulla qualità del proprio modello.
🎓 **Adattamento del modello**
Nel contesto di machine learning, l'adattamento del modello si riferisce all'accuratezza della funzione sottostante del modello mentre tenta di analizzare dati con cui non ha familiarità.
🎓 **Inadeguatezza** o **sovraadattamento** sono problemi comuni che degradano la qualità del modello, poiché il modello non si adatta abbastanza bene o troppo bene. Ciò fa sì che il modello esegua previsioni troppo allineate o troppo poco allineate con i suoi dati di addestramento. Un modello overfit (sovraaddestrato) prevede troppo bene i dati di addestramento perché ha appreso troppo bene i dettagli e il rumore dei dati. Un modello underfit (inadeguato) non è accurato in quanto non può né analizzare accuratamente i suoi dati di allenamento né i dati che non ha ancora "visto".
![modello sovraaddestrato](../images/overfitting.png)
> Infografica di [Jen Looper](https://twitter.com/jenlooper)
## Sintonia dei parametri
Una volta completato l'addestramento iniziale, si osservi la qualità del modello e si valuti di migliorarlo modificando i suoi "iperparametri". Maggiori informazioni sul processo [nella documentazione](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters?WT.mc_id=academic-15963-cxa).
## Previsione
Questo è il momento in cui si possono utilizzare dati completamente nuovi per testare l'accuratezza del proprio modello. In un'impostazione ML "applicata", in cui si creano risorse Web per utilizzare il modello in produzione, questo processo potrebbe comportare la raccolta dell'input dell'utente (ad esempio, la pressione di un pulsante) per impostare una variabile e inviarla al modello per l'inferenza, oppure valutazione.
In queste lezioni si scoprirà come utilizzare questi passaggi per preparare, costruire, testare, valutare e prevedere - tutti gesti di un data scientist e altro ancora, mentre si avanza nel proprio viaggio per diventare un ingegnere ML "full stack".
---
## 🚀 Sfida
Disegnare un diagramma di flusso che rifletta i passaggi di un professionista di ML. Dove ci si vede in questo momento nel processo? Dove si prevede che sorgeranno difficoltà? Cosa sembra facile?
## [Quiz post-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/8/?loc=it)
## Revisione e Auto Apprendimento
Cercare online le interviste con i data scientist che discutono del loro lavoro quotidiano. Eccone [una](https://www.youtube.com/watch?v=Z3IjgbbCEfs).
## Compito
[Intervista a un data scientist](assignment.it.md)

@ -0,0 +1,114 @@
# 機械学習の手法
機械学習モデルやそのモデルが使用するデータを構築・使用・管理するプロセスは、他の多くの開発ワークフローとは全く異なるものです。このレッスンでは、このプロセスを明快にして、知っておくべき主な手法の概要をまとめます。あなたは、
- 機械学習を支えるプロセスを高い水準で理解します。
- 「モデル」「予測」「訓練データ」などの基本的な概念を調べます。
## [講義前の小テスト](https://white-water-09ec41f0f.azurestaticapps.net/quiz/7?loc=ja)
## 導入
大まかに言うと、機械学習 (Machine Learning: ML) プロセスを作成する技術はいくつかのステップで構成されています。
1. **質問を決める**。ほとんどの機械学習プロセスは、単純な条件のプログラムやルールベースのエンジンでは答えられないような質問をすることから始まります。このような質問は、データの集合を使った予測を中心にされることが多いです。
2. **データを集めて準備する**。質問に答えるためにはデータが必要です。データの質と、ときには量が、最初の質問にどれだけうまく答えられるかを決めます。データの可視化がこのフェーズの重要な側面です。モデルを構築するためにデータを訓練グループとテストグループに分けることもこのフェーズに含みます。
3. **学習方法を選ぶ**。質問の内容やデータの性質に応じて、データを最も良く反映して正確に予測できるモデルを、どのように学習するかを選ぶ必要があります。これは機械学習プロセスの中でも、特定の専門知識と、多くの場合はかなりの試行回数が必要になる部分です。
4. **モデルを学習する**。データのパターンを認識するモデルを学習するために、訓練データと様々なアルゴリズムを使います。モデルはより良いモデルを構築するために、データの特定の部分を優先するように調整できる内部の重みを活用するかもしれません。
5. **モデルを評価する**。モデルがどのように動作しているかを確認するために、集めたデータの中からまだ見たことのないもの(テストデータ)を使います。
6. **パラメータチューニング**。モデルの性能によっては、モデルを学習するために使われる、各アルゴリズムの挙動を制御するパラメータや変数を変更してプロセスをやり直すこともできます。
7. **予測する**。モデルの精度をテストするために新しい入力を使います。
## どのような質問をすれば良いか
コンピュータはデータの中に隠れているパターンを見つけることがとても得意です。この有用性は、条件ベースのルールエンジンを作っても簡単には答えられないような、特定の領域に関する質問を持っている研究者にとって非常に役立ちます。たとえば、ある保険数理の問題があったとして、データサイエンティストは喫煙者と非喫煙者の死亡率に関する法則を自分の手だけでも作れるかもしれません。
しかし、他にも多くの変数が方程式に含まれる場合、過去の健康状態から将来の死亡率を予測する機械学習モデルの方が効率的かもしれません。もっと明るいテーマの例としては、緯度、経度、気候変動、海への近さ、ジェット気流のパターンなどのデータに基づいて、特定の場所における4月の天気を予測することができます。
✅ 気象モデルに関するこの [スライド](https://www2.cisl.ucar.edu/sites/default/files/0900%20June%2024%20Haupt_0.pdf) は、気象解析に機械学習を使う際の歴史的な考え方を示しています。
## 構築前のタスク
モデルの構築を始める前に、いくつかのタスクを完了させる必要があります。質問をテストしたりモデルの予測に基づいた仮説を立てたりするためには、いくつかの要素を特定して設定する必要があります。
### データ
質問に確実に答えるためには、適切な種類のデータが大量に必要になります。ここではやるべきことが2つあります。
- **データを集める**。データ解析における公平性に関する前回の講義を思い出しながら、慎重にデータを集めてください。特定のバイアスを持っているかもしれないデータのソースに注意し、それを記録しておいてください。
- **データを準備する**。データを準備するプロセスにはいくつかのステップがあります。異なるソースからデータを集めた場合、照合と正規化が必要になるかもしれません。([クラスタリング](../../../5-Clustering/1-Visualize/README.md) で行っているように、)文字列を数値に変換するなどの様々な方法でデータの質と量を向上させることができます。([分類](../../../4-Classification/1-Introduction/README.md) で行っているように、)元のデータから新しいデータを生成することもできます。([Webアプリ](../../../3-Web-App/README.md) の講義の前に行うように、)データをクリーニングしたり編集したりすることができます。最後に、学習の手法によっては、ランダムにしたりシャッフルしたりする必要もあるかもしれません。
✅ データを集めて処理した後は、その形で意図した質問に対応できるかどうかを確認してみましょう。[クラスタリング](../../../5-Clustering/1-Visualize/README.md) の講義でわかるように、データは与えられたタスクに対して上手く機能しないかもしれません!
### 機能とターゲット
フィーチャは、データの測定可能なプロパティです。多くのデータセットでは、'日付' 'サイズ' や '色' のような列見出しとして表現されます。通常、コードでは `X` として表されるフィーチャ変数は、モデルのトレーニングに使用される入力変数を表します
ターゲットは、予測しようとしているものです。ターゲットは通常、コードで`y`として表され、あなたのデータを尋ねようとしている質問に対する答えを表します:12月に、どの色のカボチャが最も安くなりますか?サンフランシスコでは、どの地域が最高の不動産価格を持つでしょうか?ターゲットはラベル属性とも呼ばれることもあります。
### 特徴量の選択
🎓 **特徴選択と特徴抽出** モデルを構築する際にどの変数を選ぶべきかは、どうすればわかるでしょうか?最も性能の高いモデルのためには、適した変数を選択する特徴選択や特徴抽出のプロセスをたどることになるでしょう。しかし、これらは同じものではありません。「特徴抽出は元の特徴の機能から新しい特徴を作成するのに対し、特徴選択は特徴の一部を返すものです。」 ([出典](https://wikipedia.org/wiki/Feature_selection))
### データを可視化する
データサイエンティストの道具に関する重要な側面は、Seaborn や MatPlotLib などの優れたライブラリを使ってデータを可視化する力です。データを視覚的に表現することで、隠れた相関関係を見つけて活用できるかもしれません。また、([分類](../../../4-Classification/2-Classifiers-1/README.md) でわかるように、)視覚化することで、バイアスやバランシングされていないデータを見つけられるかもしれません。
### データセットを分割する
学習の前にデータセットを2つ以上に分割して、それぞれがデータを表すのに十分かつ不均等な大きさにする必要があります。
- **学習**。データセットのこの部分は、モデルを学習するために適合させます。これは元のデータセットの大部分を占めます。
- **テスト**。テストデータセットとは、構築したモデルの性能を確認するために使用する独立したデータグループのことで、多くの場合は元のデータから集められます。
- **検証**。検証セットとは、さらに小さくて独立したサンプルの集合のことで、モデルを改善するためにハイパーパラメータや構造を調整する際に使用されます。([時系列予測](../../../7-TimeSeries/1-Introduction/README.md) に記載しているように、)データの大きさや質問の内容によっては、この3つ目のセットを作る必要はありません。
## モデルの構築
訓練データと様々なアルゴリズムを使った **学習** によって、モデルもしくはデータの統計的な表現を構築することが目標です。モデルを学習することで、データを扱えるようになったり、発見、検証、肯定または否定したパターンに関する仮説を立てることができたりします。
### 学習方法を決める
質問の内容やデータの性質に応じて、モデルを学習する方法を選択します。このコースで使用する [Scikit-learn のドキュメント](https://scikit-learn.org/stable/user_guide.html) を見ると、モデルを学習する様々な方法を調べられます。経験次第では、最適なモデルを構築するためにいくつかの異なる方法を試す必要があるかもしれません。また、モデルが見たことのないデータを与えたり、質を下げている問題、精度、バイアスについて調べたり、タスクに対して最適な学習方法を選んだりすることで、データサイエンティストが行っている、モデルの性能を評価するプロセスを踏むことになるでしょう。
### モデルを学習する
トレーニングデータを使用して、モデルを作成するために「フィット」する準備が整いました。多くの ML ライブラリでは、コード 'model.fit' が見つかります - この時点で、値の配列 (通常は `X`) とターゲット変数 (通常は `y`) として機能変数を送信します。
### モデルを評価する
(大きなモデルを学習するには多くの反復(エポック)が必要になりますが、)学習プロセスが完了したら、テストデータを使ってモデルの質を評価することができます。このデータは元のデータのうち、モデルがそれまでに分析していないものです。モデルの質を表す指標の表を出力することができます。
🎓 **モデルフィッティング**
機械学習におけるモデルフィッティングは、モデルがまだ知らないデータを分析する際の根本的な機能の精度を参照します。
🎓 **未学習** と **過学習** はモデルの質を下げる一般的な問題で、モデルが十分に適合していないか、または適合しすぎています。これによってモデルは訓練データに近すぎたり遠すぎたりする予測を行います。過学習モデルは、データの詳細やノイズもよく学習しているため、訓練データを上手く予測しすぎてしまいます。未学習モデルは、訓練データやまだ「見たことのない」データを正確に分析することができないため、精度が高くないです。
![過学習モデル](../images/overfitting.png)
> [Jen Looper](https://twitter.com/jenlooper) さんによる解説画像
## パラメータチューニング
最初のトレーニングが完了したら、モデルの質を観察して、「ハイパーパラメータ」の調整によるモデルの改善を検討しましょう。このプロセスについては [ドキュメント](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters?WT.mc_id=academic-15963-cxa) を読んでください。
## 予測
全く新しいデータを使ってモデルの精度をテストする瞬間です。本番環境でモデルを使用するためにWebアセットを構築するよう「適用された」機械学習の設定においては、推論や評価のためにモデルに渡したり、変数を設定したりするためにユーザの入力(ボタンの押下など)を収集することがこのプロセスに含まれるかもしれません。
この講義では、「フルスタック」の機械学習エンジニアになるための旅をしながら、準備・構築・テスト・評価・予測などのデータサイエンティストが行うすべてのステップの使い方を学びます。
---
## 🚀チャレンジ
機械学習の学習者のステップを反映したフローチャートを描いてください。今の自分はこのプロセスのどこにいると思いますか?どこに困難があると予想しますか?あなたにとって簡単そうなことは何ですか?
## [講義後の小テスト](https://white-water-09ec41f0f.azurestaticapps.net/quiz/8?loc=ja)
## 振り返りと自主学習
データサイエンティストが日々の仕事について話しているインタビューをネットで検索してみましょう。ひとつは [これ](https://www.youtube.com/watch?v=Z3IjgbbCEfs) です。
## 課題
[データサイエンティストにインタビューする](assignment.ja.md)

@ -0,0 +1,114 @@
# 머신러닝의 기술
머신러닝 모델과 이를 사용하는 데이터를 구축, 사용, 그리고 관리하는 프로세스는 많은 타 개발 워크플로우와 매우 다른 프로세스입니다. 이 강의에서, 프로세스를 이해하고, 알아야 할 주요 기술을 간단히 설명합니다:
- 머신러닝을 받쳐주는 프로세스를 고수준에서 이해합니다.
- 'models', 'predictions', 그리고 'training data'와 같은 기초 개념을 탐색합니다.
## [강의 전 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/7/)
## 소개
고수준에서, 머신러닝 (ML) 프로세스를 만드는 기술은 여러 단계로 구성됩니다:
1. **질문 결정하기**. 대부분 ML 프로세스는 간단 조건 프로그램 또는 룰-베이스 엔진으로 대답할 수 없는 질문을 하는 것으로 시작합니다. 이 질문은 가끔 데이터 셋을 기반으로 한 예측을 중심으로 진행됩니다.
2. **데이터 수집 및 준비하기**. 질문에 대답하려면, 데이터가 필요합니다. 데이터의 품질과, 때때로, 양에 따라 초기 질문에 잘 대답할 수 있는 지 결정됩니다. 데이터 시각화는 이 측면에서 중요합니다. 이 단계에서 데이터를 훈련과 테스트 그룹으로 분할하여 모델을 구축하는 게 포함됩니다.
3. **학습 방식 선택하기**. 질문과 데이터의 특성에 따라, 데이터를 가장 잘 반영하고 정확한 예측을 할 수 있게 훈련하는 방법을 선택해야 합니다. 특정 전문 지식과, 지속적으로, 많은 실험이 필요한 ML 프로세스의 일부분입니다.
4. **모델 학습하기**. 학습 데이터로, 다양한 알고리즘을 사용하여 데이터의 패턴을 인식하게 모델을 학습시킵니다. 모델을 더 좋게 만들기 위하여 데이터의 특정 부분을 타 부분보다 먼저 하도록 조정할 수 있도록 내부 가중치를 활용할 수 있습니다.
5. **모델 평가하기**. 수집한 셋에서 이전에 본 적 없는 데이터 (테스트 데이터)로 모델의 성능을 확인합니다.
6. **파라미터 튜닝하기**. 모델의 성능을 기반해서, 모델 학습으로 알고리즘의 동작을 컨트롤하는 다른 파라미터, 또는 변수를, 사용해서 프로세스를 다시 실행할 수 있습니다.
7. **예측하기**. 모델의 정확성을 새로운 입력으로 테스트합니다.
## 물어볼 질문하기
컴퓨터는 데이터에서 숨겨진 패턴 찾는 것을 잘합니다. 유틸리티는 조건-기반 룰 엔진을 만들어서 쉽게 답할 수 없는 도메인에 대해 질문하는 연구원에게 매우 도움이 됩니다. 예를 들어서, actuarial 작업이 주어지면, 데이터 사이언티스트는 흡연자와 비흡연자의 사망률에 대하여 수작업 룰을 작성할 수 있습니다.
많은 다른 변수가 방정식에 포함되면, ML 모델이 과거 건강기록을 기반으로 미래 사망률을 예측하는 데에 효율적이라고 검증할 수 있습니다. 유쾌한 예시로 위도, 경도, 기후 변화, proximity to the ocean, 제트 기류의 패턴을 포함한 데이터 기반으로 주어진 위치에서 4월의 날씨를 예측하는 것입니다.
✅ 날씨 모델에 대한 [slide deck](https://www2.cisl.ucar.edu/sites/default/files/0900%20June%2024%20Haupt_0.pdf)은 날씨 분석에서 ML을 사용한 역사적 관점을 제공합니다.
## 작업 사전-구축하기
모델을 만들기 전에, 완료해야 할 몇가지 작업이 더 있습니다. 질문을 테스트하고 모델 예측을 기반으로 가설 구성하려면, 여러 요소를 식별하고 구성해야 합니다.
### 데이터
어떠한 종류의 질문을 대답하려면, 올바른 타입의 데이터가 필요합니다. 이 포인트에서 필요한 두 가지가 있습니다:
- **데이터 수집**. 데이터 분석의 공정도를 설명한 이전 강의를 기억하고, 데이터를 조심히 수집합니다. 데이터의 출처와, 내재적 편견을 알고, 출처를 문서화합니다.
- **데이터 준비**. 데이터 준비 프로세스는 여러 단계가 있습니다. 데이터가 다양한 소스에서 제공되는 경우에는 정렬하고 노멀라이즈해야 할 수 있습니다. ([Clustering](../../../5-Clustering/1-Visualize/README.md)과 같이) 문자열을 숫자로 바꾸는 방식처럼 다양한 방식을 통하여 데이터의 품질과 양을 향상시킬 수 있습니다. ([Classification](../../../4-Classification/1-Introduction/README.md)과 같이) 원본 기반으로, 새로운 데이터를 생성할 수 있습니다. ([Web App](../../../3-Web-App/README.md) 강의 이전처럼) 데이터를 정리하고 변경할 수 있습니다. 마지막으로, 훈련하는 기술에 따라서, 무작위로 섞어야 할 수 있습니다.
✅ 데이터를 수집하고 처리하면, 그 모양이 의도한 질문을 해결할 수 있는 지 잠시 봅니다. [Clustering](../../5-Clustering/1-Visualize/README.md) 강의에서 본 것처럼, 데이터가 주어진 작업에서 잘 수행하지 못할 수 있습니다!
### Features와 타겟
feature는 데이터의 측정할 수 있는 속성입니다. 많은 데이터셋에서 'date' 'size' 또는 'color'처럼 열 제목으로 표현합니다. 일반적으로 코드에서 X로 보여지는 feature 변수는, 모델을 훈련할 때 사용되는 입력 변수로 나타냅니다.
타겟은 예측하려고 시도한 것입니다. 코드에서 X로 표시하는 보통 타겟은, 데이터에 물어보려는 질문의 대답을 나타냅니다: 12월에, 어떤 색의 호박이 가장 쌀까요? San Francisco 근처의 좋은 토지 실제 거래가는 어디인가요? 가끔은 타겟을 라벨 속성이라고 부르기도 합니다.
### feature 변수 선택하기
🎓 **Feature Selection과 Feature Extraction** 모델을 만들 때 선택할 변수를 어떻게 알 수 있을까요? 가장 성능이 좋은 모델에 올바른 변수를 선택하기 위하여 Feature Selection 또는 Feature Extraction 프로세스를 거치게 됩니다. 그러나, 같은 내용이 아닙니다: "Feature extraction creates new features from functions of the original features, whereas feature selection returns a subset of the features." ([source](https://wikipedia.org/wiki/Feature_selection))
### 데이터 시각화하기
데이터 사이언티스트의 툴킷에서 중요한 측면은 Seaborn 또는 MatPlotLib과 같이 여러가지 뛰어난 라이브러리로 데이터 시각화하는 파워입니다. 데이터를 시각화로 보여주면 숨겨진 correlations를 찾아서 활용할 수 있습니다. ([Classification](../../../4-Classification/2-Classifiers-1/README.md)에서 발견한대로) 시각화는 편향적이거나 균형적이지 않은 데이터를 찾는 데 도움이 될 수 있습니다.
### 데이터셋 나누기
훈련하기 전, 데이터를 잘 나타낼 크기로 2개 이상의 데이터 셋을 나눌 필요가 있습니다.
- **학습**. 데이터셋의 파트는 모델을 학습할 때 적당합니다. 이 셋은 본 데이터셋의 대부분을 차지합니다.
- **테스트**. 테스트 데이터셋은 독립적인 데이터의 그룹이지만, 미리 만들어진 모델의 성능을 확인할 때에, 가끔 본 데이터에서도 수집됩니다.
- **검증**. 검증 셋은 모델을 개선하며 모델의 hyperparameters, 또는 architecture를 튜닝할 때, 사용하는 작은 독립된 예시 그룹입니다. ([Time Series Forecasting](../../../7-TimeSeries/1-Introduction/README.md)에서 언급하듯) 데이터의 크기와 질문에 따라서 세번째 셋을 만들 이유가 없습니다.
## 모델 구축하기
훈련하고 있는 데이터를 사용하여, **학습**할 다양한 알고리즘으로, 모델 또는, 데이터의 통계적 표현을 만드는 게 목표입니다. 모델을 학습하면서 데이터에 노출되면 발견, 검증, 그리고 승인하거나 거부되는 perceived patterns에 대하여 가설을 세울 수 있습니다.
### 학습 방식 결정하기
질문과 데이터의 특성에 따라서, 어떻게 학습할 지 선택합니다. [Scikit-learn's documentation](https://scikit-learn.org/stable/user_guide.html)을 - 이 코스에서 - 단계별로 보면 모델이 학습하는 많은 방식을 찾을 수 있습니다. 숙련도에 따라서, 최고의 모델을 만들기 위하여 다른 방식을 해볼 수 있습니다. 데이터 사이언티스트가 볼 수 없는 데이터를 주고 정확도, 편향적, 품질-저하 이슈를 점검해서, 현재 작업에 가장 적당한 학습 방식을 선택하여 모델의 성능을 평가하는 프로세스를 거치게 될 예정입니다.
### 모델 학습하기
훈련 데이터로 감싸면, 모델을 만들 'fit'이 준비 되었습니다. 많은 ML 라이브러리에서 'model.fit' 코드를 찾을 수 있습니다. - 이 순간에 값의 배열 (보통 'X')과 feature 변수 (보통 'y')로 데이터를 보내게 됩니다.
### 모델 평가하기
훈련 프로세스가 완료되면 (큰 모델을 훈련하기 위해서 많이 반복하거나 'epochs'가 요구), 테스트 데이터로 모델의 성능을 측정해서 품질을 평가할 수 있습니다. 데이터는 모델이 이전에 분석하지 않았던 본 데이터의 서브셋입니다. 모델의 품질에 대한 지표 테이블을 출력할 수 있습니다.
🎓 **모델 피팅**
머신러닝의 컨텍스트에서, 모델 피팅은 친근하지 않은 데이터를 분석하려고 시도하는 순간에 모델 기본 기능의 정확도를 보입니다.
🎓 **Underfitting** 과 **overfitting**은 모델 핏이 충분하지 않거나 너무 많을 때, 모델의 품질이 낮아지는 일반적인 이슈입니다. 이러한 이유는 모델이 훈련 데이터와 너무 근접하게 얼라인되거나 너무 느슨하게 얼라인된 예측을 합니다. overfit 모델은 데이터의 디테일과 노이즈를 너무 잘 배웠기에 훈련 데이터로 너무나 잘 예측합니다. underfit 모델은 훈련 데이터 또는 아직 볼 수 없던 데이터를 잘 분석할 수 없으므로 정확하지 않습니다.
![overfitting model](../images/overfitting.png)
> Infographic by [Jen Looper](https://twitter.com/jenlooper)
## 파라미터 튜닝
초반 훈련이 마무리 될 때, 모델의 품질을 살펴보고 'hyperparameters'를 트윅해서 개선하는 것을 고려합니다. [in the documentation](https://docs.microsoft.com/en-us/azure/machine-learning/how-to-tune-hyperparameters?WT.mc_id=academic-15963-cxa) 프로세스에 대하여 알아봅니다.
## 예측
완전히 새 데이터로 모델의 정확도를 테스트할 수 있는 순간입니다. 프로덕션에서 모델을 쓰기 위해서 웹 어셋을 만들며, '적용한' ML 세팅에, 프로세스는 변수를 설정하고 추론하거나, 평가하고자 사용자 입력(예를 들면, 버튼 입력)을 수집해 모델로 보낼 수 있습니다.
이 강의에서는, 'full stack' ML 엔지니어가 되기 위하여 여행을 떠나는 과정이며, 이 단계에 - 데이터 사이언티스트의 모든 제스쳐가 있으며 준비, 빌드, 테스트, 평가와 예측 방식을 보게 됩니다.
---
## 🚀 도전
ML 실무자의 단계를 반영한 플로우를 그려보세요. 프로세스에서 지금 어디에 있는 지 보이나요? 어려운 내용을 예상할 수 있나요? 어떤게 쉬울까요?
## [강의 후 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/8/)
## 검토 & 자기주도 학습
일상 업무를 이야기하는 데이터 사이언티스트 인터뷰를 온라인으로 검색합니다. 여기 [one](https://www.youtube.com/watch?v=Z3IjgbbCEfs) 있습니다.
## 과제
[Interview a data scientist](../assignment.md)

@ -6,7 +6,7 @@
- 在高层次上理解支持机器学习的过程。
- 探索基本概念,例如“模型”、“预测”和“训练数据”。
## [课前测验](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/7/)
## [课前测验](https://white-water-09ec41f0f.azurestaticapps.net/quiz/7/)
## 介绍
在较高的层次上,创建机器学习(ML)过程的工艺包括许多步骤:
@ -40,9 +40,13 @@
✅ 在收集和处理你的数据后,花点时间看看它的形状是否能让你解决你的预期问题。正如我们在[聚类](../../../5-Clustering/1-Visualize/README.md)课程中发现的那样,数据可能在你的给定任务中表现不佳!
### 选择特征变量
### 功能和目标
功能是数据的可测量属性。在许多数据集中,它表示为标题为"日期""大小"或"颜色"的列。您的功能变量(通常在代码中表示为 `X`)表示用于训练模型的输入变量。
[特征](https://www.datasciencecentral.com/profiles/blogs/an-introduction-to-variable-and-feature-selection)是数据的可衡量属性。在许多数据集中,它表示为列标题,如“日期”、“大小”或“颜色”。你的特征变量(通常在代码中表示为`y`)代表你试图对数据提出的问题的答案:在12月,哪种**颜色**的南瓜最便宜?在旧金山,哪些街区的房地产**价格**最好?
目标就是你试图预测的事情。目标通常表示为代码中的 `y`,代表您试图询问数据的问题的答案:在 12 月,什么颜色的南瓜最便宜?在旧金山,哪些街区的房地产价格最好?有时目标也称为标签属性。
### 选择特征变量
🎓 **特征选择和特征提取** 构建模型时如何知道选择哪个变量?你可能会经历一个特征选择或特征提取的过程,以便为性能最好的模型选择正确的变量。然而,它们不是一回事:“特征提取是从基于原始特征的函数中创建新特征,而特征选择返回特征的一个子集。”([来源](https://wikipedia.org/wiki/Feature_selection))
### 可视化数据
@ -54,7 +58,7 @@
- **训练**。这部分数据集适合你的模型进行训练。这个集合构成了原始数据集的大部分。
- **测试**。测试数据集是一组独立的数据,通常从原始数据中收集,用于确认构建模型的性能。
- **验证**。验证集是一个较小的独立示例组,用于调整模型的超参数或架构,以改进模型。根据你的数据大小和你提出的问题,你可能不需要构建第三组(正如我们在[时间序列预测](../../7-TimeSeries/1-Introduction/README.md)中所述)。
- **验证**。验证集是一个较小的独立示例组,用于调整模型的超参数或架构,以改进模型。根据你的数据大小和你提出的问题,你可能不需要构建第三组(正如我们在[时间序列预测](../../../7-TimeSeries/1-Introduction/README.md)中所述)。
## 建立模型
@ -66,20 +70,20 @@
### 训练模型
有了你的训练数据,你就可以“拟合”它以创建模型。你会注意到,在许多ML库中,你会找到代码'model.fit'——此时你将数据作为值数组(通常为'X')和特征变量(通常为'y')发送)。
有了您的培训数据,您就可以"适应"它来创建模型。您会注意到,在许多 ML 库中,您会发现代码"model.fit"-此时,您将功能变量作为一系列值(通常是`X`)和目标变量(通常是`y`)发送。
### 评估模型
训练过程完成后(训练大型模型可能需要多次迭代或“时期”),你将能够通过使用测试数据来衡量模型的性能来评估模型的质量。此数据是模型先前未分析的原始数据的子集。 你可以打印出有关模型质量的指标表。
🎓 **模型拟合 **
🎓 **模型拟合**
在机器学习的背景下,模型拟合是指模型在尝试分析不熟悉的数据时其底层功能的准确性。
🎓 **欠拟合**和**过拟合**是降低模型质量的常见问题,因为模型拟合得不够好或太好。这会导致模型做出与其训练数据过于紧密对齐或过于松散对齐的预测。 过拟合模型对训练数据的预测太好,因为它已经很好地了解了数据的细节和噪声。欠拟合模型并不准确,因为它既不能准确分析其训练数据,也不能准确分析尚未“看到”的数据。
![过拟合模型 ](../images/overfitting.png)
> 作者[Jen Looper](https://twitter.com/jenlooper)
> 作者 [Jen Looper](https://twitter.com/jenlooper)
## 参数调优
@ -97,7 +101,7 @@
画一个流程图,反映ML的步骤。在这个过程中,你认为自己现在在哪里?你预测你在哪里会遇到困难?什么对你来说很容易?
## [阅读后测验](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/8/)
## [阅读后测验](https://white-water-09ec41f0f.azurestaticapps.net/quiz/8/)
## 复习与自学
@ -105,4 +109,4 @@
## 任务
[采访一名数据科学家](../assignment.md)
[采访一名数据科学家](assignment.zh-cn.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,11 @@
# データサイエンティストにインタビューする
## 指示
会社・ユーザグループ・友人・学生仲間の中で、データサイエンティストとして専門的に働いている人に話を聞いてみましょう。その人の日々の仕事について短いレポート(500語)を書いてください。その人は専門家でしょうか?それとも「フルスタック」として働いているでしょうか?
## 評価基準
| 基準 | 模範的 | 十分 | 要改善 |
| ---- | ---------------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------- |
| | 出典が明記された適切な長さのレポートが.docファイルとして提示されている | レポートに出典が明記されていない、もしくは必要な長さよりも短い | レポートが提示されていない |

@ -0,0 +1,11 @@
# 采访一位数据科学家
## 说明
在你的公司、你所在的社群、或者在你的朋友和同学中,找到一位从事数据科学专业工作的人,与他或她交流一下。写一篇关于他们工作日常的小短文(500字左右)。他们是专家,还是说他们是“全栈”开发者?
## 评判标准
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
| -------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------ | --------------------- |
| | 提交一篇清晰描述了职业属性且字数符合规范的word文档 | 提交的文档职业属性描述得不清晰或者字数不合规范 | 啥都没有交 |

@ -7,10 +7,10 @@ Dans cette section du programme, vous découvrirez les concepts de base sous-jac
### Leçons
1. [Introduction au machine learning](1-intro-to-ML/README.md)
1. [L’histoire du machine learning et de l’IA](2-history-of-ML/README.md)
1. [Équité et machine learning](3-équité/README.md)
1. [Techniques de machine learning](4-techniques-of-ML/README.md)
1. [Introduction au machine learning](../1-intro-to-ML/translations/README.fr.md)
1. [L’histoire du machine learning et de l’IA](../2-history-of-ML/translations/README.fr.md)
1. [Équité et machine learning](../3-fairness/translations/README.fr.md)
1. [Techniques de machine learning](../4-techniques-of-ML/translations/README.fr.md)
### Crédits
"Introduction au machine learning" a été écrit avec ♥️ par une équipe de personnes comprenant [Muhammad Sakib Khan Inan](https://twitter.com/Sakibinan), [Ornella Altunyan](https://twitter.com/ornelladotcom) et [Jen Looper](https://twitter.com/jenlooper)

@ -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!
![bola dunia](../images/globe.jpg)
> 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,23 @@
# 머신러닝 소개하기
커리큘럼의 이 섹션에서, 머신러닝 필드의 기초가 될 기본 개념, 의미, 역사와 연구자가 이용하는 기술을 배울 예정입니다. 새로운 ML의 세계로 같이 모험을 떠납시다!
![globe](../images/globe.jpg)
> Photo by <a href="https://unsplash.com/@bill_oxford?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Bill Oxford</a> on <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.ko.md)
1. [머신러닝과 AI의 역사](../2-history-of-ML/translations/README.ko.md)
1. [공정성과 머신러닝](../3-fairness/translations/README.ko.md)
1. [머신러닝의 기술](../4-techniques-of-ML/translations/README.ko.md)
### 크레딧
"Introduction to Machine Learning" was written with ♥️ by a team of folks including [Muhammad Sakib Khan Inan](https://twitter.com/Sakibinan), [Ornella Altunyan](https://twitter.com/ornelladotcom) and [Jen Looper](https://twitter.com/jenlooper)
"The History of Machine Learning" was written with ♥️ by [Jen Looper](https://twitter.com/jenlooper) and [Amy Boyd](https://twitter.com/AmyKateNicho)
"Fairness and Machine Learning" was written with ♥️ by [Tomomi Imura](https://twitter.com/girliemac)
"Techniques of Machine Learning" was written with ♥️ by [Jen Looper](https://twitter.com/jenlooper) and [Chris Noring](https://twitter.com/softchris)

@ -1,6 +1,6 @@
# 机器学习入门
课程的本章节将为您介绍机器学习领域背后的基本概念、什么是机器学习,并学习它的历史以及曾为此做出贡献的技术研究者门。让我们一起开始探索机器学习的全新世界吧!
课程的本章节将为您介绍机器学习领域背后的基本概念、什么是机器学习,并学习它的历史以及曾为此做出贡献的技术研究者们。让我们一起开始探索机器学习的全新世界吧!
![globe](../images/globe.jpg)
> 图片由 <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>

@ -4,7 +4,10 @@
> Sketchnote by [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/9/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/9/)
> ### [This lesson is available in R!](./solution/R/lesson_1-R.ipynb)
## Introduction
In these four lessons, you will discover how to build regression models. We will discuss what these are for shortly. But before you do anything, make sure you have the right tools in place to start the process!
@ -18,7 +21,7 @@ In this lesson, you will learn how to:
## Installations and configurations
[![Using Python with Visual Studio Code](https://img.youtube.com/vi/7EXd4_ttIuw/0.jpg)](https://youtu.be/7EXd4_ttIuw "Using Python with Visual Studio Code")
[![Setup Python with Visual Studio Code](https://img.youtube.com/vi/yyQM70vi7V8/0.jpg)](https://youtu.be/yyQM70vi7V8 "Setup Python with Visual Studio Code")
> 🎥 Click the image above for a video: using Python within VS Code.
@ -32,7 +35,7 @@ In this lesson, you will learn how to:
3. **Install Scikit-learn**, by following [these instructions](https://scikit-learn.org/stable/install.html). Since you need to ensure that you use Python 3, it's recommended that you use a virtual environment. Note, if you are installing this library on a M1 Mac, there are special instructions on the page linked above.
1. **Install Jupyter Notebook**. You will need to [install the Jupyter package](https://pypi.org/project/jupyter/).
1. **Install Jupyter Notebook**. You will need to [install the Jupyter package](https://pypi.org/project/jupyter/).
## Your ML authoring environment
@ -42,7 +45,7 @@ Notebooks are an interactive environment that allow the developer to both code a
### Exercise - work with a notebook
In this folder, you will find the file _notebook.ipynb_.
In this folder, you will find the file _notebook.ipynb_.
1. Open _notebook.ipynb_ in Visual Studio Code.
@ -50,7 +53,7 @@ In this folder, you will find the file _notebook.ipynb_.
1. Select the `md` icon and add a bit of markdown, and the following text **# Welcome to your notebook**.
Next, add some Python code.
Next, add some Python code.
1. Type **print('hello notebook')** in the code block.
1. Select the arrow to run the code.
@ -73,7 +76,7 @@ Now that Python is set up in your local environment, and you are comfortable wit
According to their [website](https://scikit-learn.org/stable/getting_started.html), "Scikit-learn is an open source machine learning library that supports supervised and unsupervised learning. It also provides various tools for model fitting, data preprocessing, model selection and evaluation, and many other utilities."
In this course, you will use Scikit-learn and other tools to build machine learning models to perform what we call 'traditional machine learning' tasks. We have deliberately avoided neural networks and deep learning, as they are better covered in our forthcoming 'AI for Beginners' curriculum.
In this course, you will use Scikit-learn and other tools to build machine learning models to perform what we call 'traditional machine learning' tasks. We have deliberately avoided neural networks and deep learning, as they are better covered in our forthcoming 'AI for Beginners' curriculum.
Scikit-learn makes it straightforward to build models and evaluate them for use. It is primarily focused on using numeric data and contains several ready-made datasets for use as learning tools. It also includes pre-built models for students to try. Let's explore the process of loading prepackaged data and using a built in estimator first ML model with Scikit-learn with some basic data.
@ -95,7 +98,7 @@ For this task we will import some libraries:
- **matplotlib**. It's a useful [graphing tool](https://matplotlib.org/) and we will use it to create a line plot.
- **numpy**. [numpy](https://numpy.org/doc/stable/user/whatisnumpy.html) is a useful library for handling numeric data in Python.
- **sklearn**. This is the Scikit-learn library.
- **sklearn**. This is the [Scikit-learn](https://scikit-learn.org/stable/user_guide.html) library.
Import some libraries to help with your tasks.
@ -113,10 +116,10 @@ Import some libraries to help with your tasks.
The built-in [diabetes dataset](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset) includes 442 samples of data around diabetes, with 10 feature variables, some of which include:
age: age in years
bmi: body mass index
bp: average blood pressure
s1 tc: T-Cells (a type of white blood cells)
- age: age in years
- bmi: body mass index
- bp: average blood pressure
- s1 tc: T-Cells (a type of white blood cells)
✅ This dataset includes the concept of 'sex' as a feature variable important to research around diabetes. Many medical datasets include this type of binary classification. Think a bit about how categorizations such as this might exclude certain parts of a population from treatments.
@ -124,7 +127,7 @@ Now, load up the X and y data.
> 🎓 Remember, this is supervised learning, and we need a named 'y' target.
In a new code cell, load the diabetes dataset by calling `load_diabetes()`. The input `return_X_y=True` signals that `X` will be a data matrix, and `y` will be the regression target.
In a new code cell, load the diabetes dataset by calling `load_diabetes()`. The input `return_X_y=True` signals that `X` will be a data matrix, and `y` will be the regression target.
1. Add some print commands to show the shape of the data matrix and its first element:
@ -180,6 +183,9 @@ In a new code cell, load the diabetes dataset by calling `load_diabetes()`. The
```python
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.xlabel('Scaled BMIs')
plt.ylabel('Disease Progression')
plt.title('A Graph Plot Showing Diabetes Progression Against BMI')
plt.show()
```
@ -193,7 +199,7 @@ Congratulations, you built your first linear regression model, created a predict
## 🚀Challenge
Plot a different variable from this dataset. Hint: edit this line: `X = X[:, np.newaxis, 2]`. Given this dataset's target, what are you able to discover about the progression of diabetes as a disease?
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/10/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/10/)
## Review & Self Study
@ -201,6 +207,6 @@ In this tutorial, you worked with simple linear regression, rather than univaria
Read more about the concept of regression and think about what kinds of questions can be answered by this technique. Take this [tutorial](https://docs.microsoft.com/learn/modules/train-evaluate-regression-models?WT.mc_id=academic-15963-cxa) to deepen your understanding.
## Assignment
## Assignment
[A different dataset](assignment.md)

Binary file not shown.

After

Width:  |  Height:  |  Size: 558 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

After

Width:  |  Height:  |  Size: 16 KiB

@ -0,0 +1 @@
This is a temporary placeholder

@ -0,0 +1,441 @@
{
"nbformat": 4,
"nbformat_minor": 2,
"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",
"source": [
"# Build a regression model: Get started with R and Tidymodels for regression models"
],
"metadata": {
"id": "YJUHCXqK57yz"
}
},
{
"cell_type": "markdown",
"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",
"<p >\n",
" <img src=\"../../images/encouRage.jpg\"\n",
" width=\"630\"/>\n",
" <figcaption>Artwork by @allison_horst</figcaption>\n",
"\n",
"<!--![Artwork by \\@allison_horst](../../images/encouRage.jpg)<br>Artwork by @allison_horst-->"
],
"metadata": {
"id": "LWNNzfqd6feZ"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "FIo2YhO26wI9"
}
},
{
"cell_type": "code",
"execution_count": 2,
"source": [
"suppressWarnings(if(!require(\"pacman\")) install.packages(\"pacman\"))\n",
"pacman::p_load(tidyverse, tidymodels)"
],
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"Loading required package: pacman\n",
"\n"
]
}
],
"metadata": {
"id": "cIA9fz9v7Dss",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "2df7073b-86b2-4b32-cb86-0da605a0dc11"
}
},
{
"cell_type": "markdown",
"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)"
],
"metadata": {
"id": "gpO_P_6f9WUG"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# load the core Tidyverse packages\r\n",
"library(tidyverse)\r\n",
"\r\n",
"# load the core Tidymodels packages\r\n",
"library(tidymodels)\r\n"
],
"outputs": [],
"metadata": {
"id": "NLMycgG-9ezO"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "KM6iXLH996Cl"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Import the data set\r\n",
"diabetes <- read_table2(file = \"https://www4.stat.ncsu.edu/~boos/var.select/diabetes.rwrite1.txt\")\r\n",
"\r\n",
"\r\n",
"# Get a glimpse and dimensions of the data\r\n",
"glimpse(diabetes)\r\n",
"\r\n",
"\r\n",
"# Select the first 5 rows of the data\r\n",
"diabetes %>% \r\n",
" slice(1:5)"
],
"outputs": [],
"metadata": {
"id": "Z1geAMhM-bSP"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "UwjVT1Hz-c3Z"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Select predictor feature `bmi` and outcome `y`\r\n",
"diabetes_select <- diabetes %>% \r\n",
" select(c(bmi, y))\r\n",
"\r\n",
"# Print the first 5 rows\r\n",
"diabetes_select %>% \r\n",
" slice(1:10)"
],
"outputs": [],
"metadata": {
"id": "RDY1oAKI-m80"
}
},
{
"cell_type": "markdown",
"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"
],
"metadata": {
"id": "SDk668xK-tc3"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"set.seed(2056)\r\n",
"# Split 67% of the data for training and the rest for tesing\r\n",
"diabetes_split <- diabetes_select %>% \r\n",
" initial_split(prop = 0.67)\r\n",
"\r\n",
"# Extract the resulting train and test sets\r\n",
"diabetes_train <- training(diabetes_split)\r\n",
"diabetes_test <- testing(diabetes_split)\r\n",
"\r\n",
"# Print the first 3 rows of the training set\r\n",
"diabetes_train %>% \r\n",
" slice(1:10)"
],
"outputs": [],
"metadata": {
"id": "EqtHx129-1h-"
}
},
{
"cell_type": "markdown",
"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!"
],
"metadata": {
"id": "sBOS-XhB-6v7"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Build a linear model specification\r\n",
"lm_spec <- \r\n",
" # Type\r\n",
" linear_reg() %>% \r\n",
" # Engine\r\n",
" set_engine(\"lm\") %>% \r\n",
" # Mode\r\n",
" set_mode(\"regression\")\r\n",
"\r\n",
"\r\n",
"# Print the model specification\r\n",
"lm_spec"
],
"outputs": [],
"metadata": {
"id": "20OwEw20--t3"
}
},
{
"cell_type": "markdown",
"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` )"
],
"metadata": {
"id": "_oDHs89k_CJj"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Build a linear model specification\r\n",
"lm_spec <- linear_reg() %>% \r\n",
" set_engine(\"lm\") %>%\r\n",
" set_mode(\"regression\")\r\n",
"\r\n",
"\r\n",
"# Train a linear regression model\r\n",
"lm_mod <- lm_spec %>% \r\n",
" fit(y ~ ., data = diabetes_train)\r\n",
"\r\n",
"# Print the model\r\n",
"lm_mod"
],
"outputs": [],
"metadata": {
"id": "YlsHqd-q_GJQ"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "kGZ22RQj_Olu"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Make predictions for the test set\r\n",
"predictions <- lm_mod %>% \r\n",
" predict(new_data = diabetes_test)\r\n",
"\r\n",
"# Print out some of the predictions\r\n",
"predictions %>% \r\n",
" slice(1:5)"
],
"outputs": [],
"metadata": {
"id": "nXHbY7M2_aao"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "R_JstwUY_bIs"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Combine the predictions and the original test set\r\n",
"results <- diabetes_test %>% \r\n",
" bind_cols(predictions)\r\n",
"\r\n",
"\r\n",
"results %>% \r\n",
" slice(1:5)"
],
"outputs": [],
"metadata": {
"id": "RybsMJR7_iI8"
}
},
{
"cell_type": "markdown",
"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**."
],
"metadata": {
"id": "XJbYbMZW_n_s"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Set a theme for the plot\r\n",
"theme_set(theme_light())\r\n",
"# Create a scatter plot\r\n",
"results %>% \r\n",
" ggplot(aes(x = bmi)) +\r\n",
" # Add a scatter plot\r\n",
" geom_point(aes(y = y), size = 1.6) +\r\n",
" # Add a line plot\r\n",
" geom_line(aes(y = .pred), color = \"blue\", size = 1.5)"
],
"outputs": [],
"metadata": {
"id": "R9tYp3VW_sTn"
}
},
{
"cell_type": "markdown",
"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"
],
"metadata": {
"id": "zrPtHIxx_tNI"
}
}
]
}

@ -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!
![Artwork by \@allison_horst](../../images/encouRage.jpg){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!

@ -28,7 +28,7 @@
"cells": [
{
"source": [
"## Linear Regression for North American Pumpkins - Lesson 1"
"## Linear Regression for Diabetes dataset - Lesson 1"
],
"cell_type": "markdown",
"metadata": {}
@ -182,13 +182,6 @@
"plt.plot(X_test, y_pred, color='blue', linewidth=3)\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
]
}
}

@ -0,0 +1,206 @@
# Comience con Python y Scikit-learn para modelos de regresión
![Resumen de regresiones en un boceto](../../sketchnotes/ml-regression.png)
> Boceto de [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Cuestionario previo](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/9/)
## Introducción
En estas cuatro lecciones, descubrirá como crear modelos de regresión. Discutiremos para que sirven estos en breve. Pero antes de hacer cualquier coasa, asegúrese de tener las herramientas adecuadas para comenzar el proceso!
En esta lección, aprenderá a:
- Configurar su computadora para tares locales de machine learning.
- Trabajar con cuadernos Jupyter.
- Usar Scikit-learn, incluida la instalación.
- Explorar la regressión lineal con un ejercicio práctico.
## Instalaciones y configuraciones.
[![Uso de Python con Visual Studio Code](https://img.youtube.com/vi/yyQM70vi7V8/0.jpg)](https://youtu.be/yyQM70vi7V8 "Uso de Python con Visual Studio Code")
> 🎥 Haga click en la imagen de arriba para ver un video: usando Python dentro de VS Code.
1. **Instale Python**. Asegúrese de que [Python](https://www.python.org/downloads/) esté instalado en su computadora. Utilizará Python para muchas tareas de ciencia de datos y machine learning. La mayoría de los sistemas informáticos ya incluyen una instalación de Python. También hay disponibles [paquetes de código de Python](https://code.visualstudio.com/learn/educators/installers?WT.mc_id=academic-15963-cxa) útiles para facilitar la configuración a algunos usuarios.
Sin embargo algunos usos de Python requieren una versión del software, mientras otros requieren una versión diferente. Por esta razón, es útil trabajar dentro de un [entorno virtual](https://docs.python.org/3/library/venv.html).
2. **Instale Visual Studio Code**. Asegúrese de tener Visual Studio Code instalado en su computadora. Siga estas instrucciones para [instalar Visual Studio Code](https://code.visualstudio.com/) para la instalación básica. Va a utilizar Python en Visual Studio Code en este curso, por lo que es posible que desee repasar cómo [configurar Visual Studio Code](https://docs.microsoft.com/learn/modules/python-install-vscode?WT.mc_id=academic-15963-cxa) para el desarrollo en Python.
> Siéntase cómodo con Python trabajando con esta colección de [módulos de aprendizaje](https://docs.microsoft.com/users/jenlooper-2911/collections/mp1pagggd5qrq7?WT.mc_id=academic-15963-cxa)
3. **Instale Scikit-learn**, siguiendo [estas instrucciones](https://scikit-learn.org/stable/install.html). Dado que debe asegurarse de usar Python3, se recomienda que use un entorno virtual. Tenga en cuenta que si está instalando esta biblioteca en una Mac M1, hay instrucciones especiales en la página vinculada arriba.
1. **Instale Jupyter Notebook**. Deberá [instalar el paquete de Jupyter](https://pypi.org/project/jupyter/).
## El entorno de creación de ML
Utilizará **cuadernos** para desarrollar su código en Python y crear modelos de machine learning. Este tipo de archivos es una herramienta común para científicos de datos, y se pueden identificar por su sufijo o extensión `.ipynb`.
Los cuadernos son un entorno interactivo que permiten al desarrollador codificar y agregar notas y escribir documentación sobre el código lo cual es bastante útil para proyectos experimentales u orientados a la investigación.
### Ejercicio - trabajar con un cuaderno
En esta carpeta, encontrará el archivo _notebook.ipynb_.
1. Abra _notebook.ipynb_ en Visual Studio Code.
Un servidor de Jupyter comenzará con Python 3+ iniciado. Encontrará áreas del cuaderno que se pueden ejecutar, fragmentos de código. Puede ejecutar un bloque de código seleccionando el icono que parece un botón de reproducción.
1. Seleccione el icono `md` y agrege un poco de _markdown_, y el siguiente texto **# Welcome to your notebook**.
A continuación, agrege algo de código Python.
1. Escriba **print('hello notebook')** en el bloque de código.
1. Seleccione la flecha para ejecutar el código.
Debería ver impresa la declaración:
```output
hello notebook
```
![VS Code con un cuaderno abierto](images/notebook.png)
Puede intercalar su código con comentarios para autodocumentar el cuaderno.
✅ Piense por un minuto en cuán diferente es el entorno de trabajo de un desarrollador web en comparación con el de un científico de datos.
## En funcionamiento con Scikit-learn
Ahora que Python está configurado en un entorno local, y se siente cómo con los cuadernos de Jupyter, vamos a sentirnos igualmente cómodos con Scikit-learn (pronuncie `sci` como en `science`). Scikit-learn proporciona una [API extensa](https://scikit-learn.org/stable/modules/classes.html#api-ref) para ayudarlo a realizar tares de ML.
Según su [sitio web](https://scikit-learn.org/stable/getting_started.html), "Scikit-learn es una biblioteca de machine learning de código abierto que admite el aprendizaje supervisado y no supervisado. También proporciona varias herramientas para el ajuste de modelos, preprocesamiento de datos, selección y evaluación de modelos, y muchas otras utilidades."
En este curso, utilizará Scikit-learn y otras herramientas para crear modelos de machine learning para realizar lo que llamamos tareas de 'machine leraning tradicional'. Hemos evitado deliberadamente las redes neuronales y el _deep learning_, ya que se tratartán mejor en nuestro próximo plan de estudios 'IA para principiantes'.
Scikit-learn hace que sea sencillo construir modelos y evaluarlos para su uso. Se centra principalmente en el uso de datos numéricos y contiene varios conjuntos de datos listos para usar como herramientas de aprendizaje. También incluye modelos prediseñados para que los estudiantes lo prueben. Exploremos el proceso de cargar datos preempaquetados y el uso de un primer modelo de estimador integrado con Scikit-learn con algunos datos básicos.
## Ejercicio - su primer cuaderno de Scikit-learn
> Este tutorial se insipiró en el [ejemplo de regresión lineal](https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py) en el sitio web de Scikit-learn's.
En el archivo _notebook.ipynb_ asociado a esta lección, borre todas las celdas presionando el icono 'papelera'.
En esta sección, trabajará con un pequeño conjunto de datos sobre la diabetes que está integrado con Scikit-learn con fines de aprendizaje. Imagínese que quisiera probar un tratamiento para pacientes diabéticos. Los modelos de Machine Learning, pueden ayudarlo a determinar que pacientes responderían mejor al tratamiento, en función de combinanciones de varibales. Incluso un modelo de regresión muy básico, cuando se visualiza, puede mostrar información sobre variables que le ayudarían en sus ensayos clínicos teóricos.
✅ Hay muchos tipos de métodos de regresión y el que elija dependerá de las respuestas que esté buscando. Si desea predecir la altura probable de una persona de una edad determinada, utlizaría la regresión lineal, ya que busca un **valor numérico**. Si está interesado en descubrir si un tipo de cocina puede considerarse vegano o no, está buscando una **asignación de categoría**, por lo que utlilizaría la regresión logística. Más adelante aprenderá más sobre la regresión logística. Piense un poco en algunas preguntas que puede puede hacer a los datos y cuáles de estos métodos sería más apropiado.
Comencemos con esta tarea.
### Importar bibliotecas
Para esta tarea importaremos algunas librerías:
- **matplotlib**. Es una [herramienta gráfica](https://matplotlib.org/) útil y la usaremos para crear un diagrama de líneas.
- **numpy**. [numpy](https://numpy.org/doc/stable/user/whatisnumpy.html) es una librería útil para manejar datos numéricos en Python.
- **sklearn**. Esta es la librería Scikit-learn.
Importar algunas librerías para ayudarte con tus tareas.
1. Agrege importaciones escribiendo el siguiente código:
```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model, model_selection
```
Arriba estás importando `matplottlib`, `numpy` y estás importando `datasets`, `linear_model` y `model_selection` de `sklearn`. `model_selection` se usa para dividir datos en conjuntos de entrenamiento y de prueba.
### El conjunto de datos de diabetes
El [conjunto de datos de diabetes](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset) incluye 442 muestras de datos sobre la diabetes, con 10 variables de características, algunas de las cuales incluyen:
edad: edad en años.
bmi: índice de masa corporal.
bp: presión arterial promedio.
s1 tc: Células-T (un tipo de glóbulos blancos).
✅ Este conjunto de datos incluye el concepto de sexo como una variable característica importante para la investigación sobre la diabetes. Piense un poco en cómo categorizaciones como esta podrían excluir a ciertas partes de una población de los tratamientos.
Ahora cargue los datos X e y.
> 🎓 Recuerde, esto es aprendizeje supervisado, y necesitamos un objetivo llamado 'y'.
En una nueva celda de código, cargue el conjunto de datos de diabetes llamando `load_diabetes()`. La entrada `return_X_y=True` indica que `X` será una matriz de datos, y `y` será el objetivo de regresión.
1. Agregue algunos comandos de impresión para mostrar la forma de la matriz de datos y su primer elemento:
```python
X, y = datasets.load_diabetes(return_X_y=True)
print(X.shape)
print(X[0])
```
Lo que recibe como respuesta es una tupla. Lo que está haciendo es asignar los dos primeros valores de la tupla a `X` y `y` respectivamente. Más información [sobre tuplas](https://wikipedia.org/wiki/Tuple).
Puede ver que estos datos tienen 442 elementos en forma de matrices de 10 elementos:
```text
(442, 10)
[ 0.03807591 0.05068012 0.06169621 0.02187235 -0.0442235 -0.03482076
-0.04340085 -0.00259226 0.01990842 -0.01764613]
```
✅ Piense un poco en la relación entre los datos y el objetivo de la regresión. La regersión lineal predice relaciones entre la característica X y la variable objetivo y. ¿Puede encontrar el [objetivo](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset) para el cojunto de datos de diabetes en la documentación? ¿Qué está demostrando este conjunto de datos dado ese objetivo?
2. A continuación, seleccione una parte de este conjunto de datos para graficarlos colocándolos en una nueva matriz utilizando la función `newaxis` de _numpy_. Vamos utilizar una regresión lineal para generar una línea entre los valores de estos datos, según un patrón que determine.
```python
X = X[:, np.newaxis, 2]
```
✅ En cualquier momento, imprima los datos para comprobar su forma.
3. Ahora que tiene los datos listos para graficarlos, puede ver si una máquina puede ayudar a determinar una división lógica entre los númnero en este conjunto de datos. Para hacer esto, necesita dividir los datos (X) y el objetivo (y) en conjunto de datos de prueba y entrenamiento. Scikit-learn tiene una forma sencilla de hacer esto; puede dividir sus datos de prueba en un punto determinado.
```python
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33)
```
4. Ahora está listo para entrenar su modelo! Cargue el modelo de regresión lineal y entrénelo con sus datos de entrenamiento X e y usando `model.fit()`:
```python
model = linear_model.LinearRegression()
model.fit(X_train, y_train)
```
✅ `model.fit()` es una función que verá en muchas bibliotecas de ML como TensorFlow
5. Luego, cree una predicción usando datos de prueba, usando la función `predict()`. Esto se utilizará para trazar la línea entre los grupos de datos.
```python
y_pred = model.predict(X_test)
```
6. Ahora es el momento de mostrar los datos en una gráfica. Matplotlib es una herramienta muy útil para esta tarea. Cree una gráfica de dispersión de todos los datos de prueba X e y, y use la prediccíón para dibujar una línea en el lugar más apropiado, entre las agrupaciones de datos del modelo.
```python
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.show()
```
![un diagrama de dispersión que muestra puntos de datos sobre la diabetes](./images/scatterplot.png)
✅ Piense un poco sobre lo que está pasando aquí. Una línea recta atraviesa muchos pequeños puntos de datos, pero ¿qué está haciendo excactamente? ¿Puede ver cómo debería poder usar esta línea para predecir dónde debe encajar un punto de datos nuevo y no visto en relación con el eje y del gráfico? Intente poner en palabras el uso práctico de este modelo.
Felicitaciones, construiste tu primer modelo de regresión lineal, creaste una predicción con él y lo mostraste en una gráfica!
---
## Desafío
Grafique una variable diferente de este conjunto de datos. Sugerencia: edite esta linea: `X = X[:, np.newaxis, 2]`. Dado el objetivo de este conjunto de datos,¿qué puede descubrir sobre la progresión de la diabetes?
## [Cuestionario posterior a la conferencia](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/10/)
## Revisión y autoestudio
En este tutorial, trabajó con regresión lineal simple, en lugar de regresión lineal univariante o múltiple. Lea un poco sobre las diferencias entre estos métodos o eche un vistazo a [este video](https://www.coursera.org/lecture/quantifying-relationships-regression-models/linear-vs-nonlinear-categorical-variables-ai2Ef)
Lea más sobre el concepto de regresión lineal y piense que tipo de preguntas se pueden responder con esta técnica.Tome este [tutorial](https://docs.microsoft.com/learn/modules/train-evaluate-regression-models?WT.mc_id=academic-15963-cxa) para profundizar su comprensión.
## Asignación
[Un conjunto de datos diferentes](assignment.md)

@ -4,7 +4,7 @@
> Catatan sketsa oleh [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Kuis Pra-ceramah](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/9/)
## [Kuis Pra-ceramah](https://white-water-09ec41f0f.azurestaticapps.net/quiz/9/)
## Pembukaan
Dalam keempat pelajaran ini, kamu akan belajar bagaimana membangun model regresi. Kita akan berdiskusi apa fungsi model tersebut dalam sejenak. Tetapi sebelum kamu melakukan apapun, pastikan bahwa kamu sudah mempunyai alat-alat yang diperlukan untuk memulai!
@ -195,7 +195,7 @@ Selamat, kamu telah membangun model regresi linear pertamamu, membuat sebuah pre
## Tantangan
Gambarkan sebuah variabel yang beda dari *dataset* ini. Petunjuk: edit baris ini: `X = X[:, np.newaxis, 2]`. Mengetahui target *dataset* ini, apa yang kamu bisa menemukan tentang kemajuan diabetes sebagai sebuah penyakit?
## [Kuis pasca-ceramah](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/10/)
## [Kuis pasca-ceramah](https://white-water-09ec41f0f.azurestaticapps.net/quiz/10/)
## Review & Pembelajaran Mandiri

@ -0,0 +1,211 @@
# Iniziare con Python e Scikit-learn per i modelli di regressione
![Sommario delle regressioni in uno sketchnote](../../../sketchnotes/ml-regression.png)
> Sketchnote di [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [Qui Pre-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/9/?loc=it)
## 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
[![Usare Python con Visual Studio Code](https://img.youtube.com/vi/7EXd4_ttIuw/0.jpg)](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
```
![VS Code con un notebook aperto](../images/notebook.png)
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()
```
![un grafico a dispersione che mostra i punti dati sul diabete](../images/scatterplot.png)
✅ 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://white-water-09ec41f0f.azurestaticapps.net/quiz/10/?loc=it)
## 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)

@ -4,7 +4,7 @@
> [Tomomi Imura](https://www.twitter.com/girlie_mac) によって制作されたスケッチノート
## [講義前クイズ](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/9/)
## [講義前クイズ](https://white-water-09ec41f0f.azurestaticapps.net/quiz/9?loc=ja)
## イントロダクション
@ -121,10 +121,10 @@ Scikit-learnは、モデルを構築し、評価を行って実際に利用す
組み込みの [diabetes dataset](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset) には、糖尿病に関する442サンプルのデータが含まれており、10個の変数が含まれています。
age: 年齢
bmi: ボディマス指数
bp: 平均血圧
s1 tc: T細胞(白血球の一種)
- age: 年齢
- bmi: ボディマス指数
- bp: 平均血圧
- s1 tc: T細胞(白血球の一種)
✅ このデータセットには、糖尿病に関する研究に重要な変数として「性別」の概念が含まれています。多くの医療データセットには、このようなバイナリ分類が含まれています。このような分類が、人口のある部分を治療から排除する可能性があることについて、少し考えてみましょう。
@ -205,7 +205,7 @@ s1 tc: T細胞(白血球の一種)
## 🚀チャレンジ
このデータセットから別の変数を選択してプロットしてください。ヒント: `X = X[:, np.newaxis, 2]` の行を編集する。今回のデータセットのターゲットである、糖尿病という病気の進行について、どのような発見があるのでしょうか?
## [講義後クイズ](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/10/)
## [講義後クイズ](https://white-water-09ec41f0f.azurestaticapps.net/quiz/10?loc=ja)
## レビュー & 自主学習
@ -215,4 +215,4 @@ s1 tc: T細胞(白血球の一種)
## 課題
[異なるデータセット](assignment.md)
[異なるデータセット](./assignment.ja.md)

@ -0,0 +1,213 @@
# Regression 모델을 위한 Python과 Scikit-learn 시작하기
![Summary of regressions in a sketchnote](../../../sketchnotes/ml-regression.png)
> Sketchnote by [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [강의 전 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/9/)
## 소개
4개의 강의에서, regression 모델을 어떻게 만드는 지에 대하여 탐험합니다. 무엇인지 곧 이야기할 것 입니다. 하지만 모든 것을 하기 전에, 프로세스를 시작할 때 올바른 도구가 있는 지 확인합니다!
이 강의에서는, 이와 같은 내용을 배웁니다:
- 로컬 머신러닝 작업을 위해서 컴퓨터를 구성합니다.
- Jupyter notebooks으로 작업합니다.
- 설치 과정을 포함해서, Scikit-learn 사용합니다.
- 직접 연습해보며 linear regression을 알아봅니다.
## 설치하고 구성하기
[![Using Python with Visual Studio Code](https://img.youtube.com/vi/7EXd4_ttIuw/0.jpg)](https://youtu.be/7EXd4_ttIuw "Using Python with Visual Studio Code")
> 🎥 영상 보려면 이미지 클릭: using Python within VS Code.
1. **Python 설치하기**. [Python](https://www.python.org/downloads/)이 컴퓨터에 설치되었는 지 확인합니다. 많은 데이터 사이언스와 머신러닝 작업에서 Python을 사용하게 됩니다. 대부분 컴퓨터 시스템은 이미 Python 애플리케이션을 미리 포함하고 있습니다. 사용자가 설치를 쉽게하는, 유용한 [Python Coding Packs](https://code.visualstudio.com/learn/educators/installers?WT.mc_id=academic-15963-cxa)이 존재합니다.
그러나, 일부 Python만 사용하면, 소프트웨어의 하나의 버전만 요구하지만, 다른 건 다른 버전을 요구합니다. 이런 이유로, [virtual environment](https://docs.python.org/3/library/venv.html)에서 작업하는 것이 유용합니다.
2. **Visual Studio Code 설치하기**. 컴퓨터에 Visual Studio Code가 설치되어 있는 지 확인합니다. 기본 설치로 [install Visual Studio Code](https://code.visualstudio.com/)를 따라합니다. Visual Studio Code에서 Python을 사용하므로 Python 개발을 위한 [configure Visual Studio Code](https://docs.microsoft.com/learn/modules/python-install-vscode?WT.mc_id=academic-15963-cxa)를 살펴봅니다.
> 이 [Learn modules](https://docs.microsoft.com/users/jenlooper-2911/collections/mp1pagggd5qrq7?WT.mc_id=academic-15963-cxa)의 모음을 통하여 Python에 익숙해집시다.
3. [these instructions](https://scikit-learn.org/stable/install.html)에 따라서, **Scikit-learn 설치하기**. Python 3을 사용하는 지 확인할 필요가 있습니다. 가상 환경으로 사용하는 것을 추천합니다. 참고로, M1 Mac에서 라이브러리를 설치하려면, 링크된 페이지에서 특별한 설치 방법을 따라합시다.
1. **Jupyter Notebook 설치하기**. [install the Jupyter package](https://pypi.org/project/jupyter/)가 필요합니다.
## ML 작성 환경
**notebooks**으로 Python 코드를 개발하고 머신러닝 모델도 만드려고 합니다. 이 타입 파일은 데이터 사이언티스트의 일반적인 도구이고, 접미사 또는 확장자 `.ipynb`로 찾을 수 있습니다.
노트북은 개발자가 코드를 작성하고 노트를 추가하며 코드 사이에 문서를 작성할 수 있는 대화형 환경으로서 실험적이거나 연구-중심 프로젝트에 매우 도움이 됩니다.
### 연습 - notebook으로 작업하기
이 폴더에서, _notebook.ipynb_ 파일을 찾을 수 있습니다.
1. Visual Studio Code에서 _notebook.ipynb_ 엽니다.
Jupyter 서버는 Python 3+ 이상에서 시작됩니다. 코드 조각에서, `run` 할 수 있는 노트북 영역을 찾습니다. 재생 버튼처럼 보이는 아이콘을 선택해서, 코드 블록을 실핼할 수 있습니다.
1. `md` 아이콘을 선택하고 markdown을 살짝 추가합니다, 그리고 **# Welcome to your notebook** 텍스트를 넣습니다.
다음으로, 약간의 Python 코드를 추가합니다.
1. 코드 블록에서 **print('hello notebook')** 입력합니다.
1. 코드를 실행하려면 화살표를 선택합니다.
출력된 구문이 보여야 합니다:
```output
hello notebook
```
![VS Code with a notebook open](../images/notebook.png)
코드에 주석을 넣어서 노트북이 자체적으로 문서화 할 수 있게 할 수 있습니다.
✅ 웹 개발자의 작업 환경이 데이터 사이언티스트와 어떻게 다른 지 잠시 알아보세요.
## Scikit-learn으로 시작하고 실행하기
이제 로컬 환경에 Python이 설정되었고, 그리고 Jupyter notebooks에 익숙해진 상태에서, Scikit-learn (`science`에서는 `sci`로 발음)도 익숙하게 하겠습니다. Scikit-learn은 ML 작업을 돕는 [extensive API](https://scikit-learn.org/stable/modules/classes.html#api-ref)가 제공됩니다.
[website](https://scikit-learn.org/stable/getting_started.html)에 따르면, "Scikit-learn is an open source machine learning library that supports supervised and unsupervised learning. It also provides various tools for model fitting, data preprocessing, model selection and evaluation, and many other utilities." 라고 언급되고 있습니다.
이 코스에서, Scikit-learn과 다른 도구를 사용하여 머신러닝 모델을 만들면서 'traditional machine learning' 작업이 진행됩니다. 곧 다가올 'AI for Beginners' 커리큘럼에서 더 잘 커버될 것이기 때문에, 신경망과 딥러닝은 제외했습니다.
Scikit-learn 사용하면 올바르게 모델을 만들고 사용하기 위해 평가할 수 있습니다. 주로 숫자 데이터에 포커스를 맞추고 학습 도구로 사용하기 위한 여러 ready-made 데이터셋이 포함됩니다. 또 학생들이 시도해볼 수 있도록 사전-제작된 모델을 포함합니다. 패키징된 데이터를 불러오고 기초 데이터와 Scikit-learn이 같이 있는 estimator first ML 모델로 프로세스를 찾아봅니다.
## 연습 - 첫 Scikit-learn notebook
> 이 튜토리얼은 Scikit-learn 웹사이트에 있는 [linear regression example](https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py)에서 영감 받았습니다.
이 강의에서 관련있는 _notebook.ipynb_ 파일에서, 'trash can' 아이콘을 누르면 모든 셀이 지워집니다.
이 세션에서, 학습 목적의 Scikit-learn에서 만든 작은 당뇨 데이터셋으로 다룹니다. 당뇨 환자를 위한 치료 방법을 테스트하고 싶다고 생각해보세요. 머신러닝 모델은 변수 조합을 기반으로, 어떤 환자가 더 잘 치료될 지 결정할 때 도울 수 있습니다. 매우 기초적인 regression 모델도, 시각화하면, 이론적인 임상 시험을 구성하는 데에 도움이 될 변수 정보를 보여줄 수 있습니다.
✅ Regression 방식에는 많은 타입이 있고, 어떤 것을 선택하는 지에 따라 다릅니다. 만약 주어진 나이의 사람이 클 수 있는 키에 대하여 예측하려고, **numeric value**를 구할 때, linear regression을 사용합니다. 만약 어떤 타입의 요리를 비건으로 분류해야 하는 지 알고 싶다면, logistic regression으로 **category assignment**을 찾습니다. logistic regression은 나중에 자세히 알아봅시다. 데이터에 대하여 물어볼 수 있는 몇 가지 질문과, 이 방식 중 어느 것이 적당한 지 생각해봅니다.
작업을 시작하겠습니다.
### 라이브러리 Import
작업을 하기 위하여 일부 라이브러리를 import 합니다:
- **matplotlib**. 유용한 [graphing tool](https://matplotlib.org/)이며 line plot을 만들 때 사용합니다.
- **numpy**. [numpy](https://numpy.org/doc/stable/user/whatisnumpy.html)는 Python애서 숫자를 핸들링할 때 유용한 라이브러리입니다.
- **sklearn**. [Scikit-learn](https://scikit-learn.org/stable/user_guide.html) 라이브러리 입니다.
작업을 도움받으려면 라이브러리를 Import 합니다.
1. 다음 코드를 타이핑해서 imports를 추가합니다:
```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model, model_selection
```
`matplottlib`, `numpy`를 가져오고 `sklearn` 에서 `datasets`, `linear_model`과 `model_selection`을 가져옵니다. `model_selection`은 데이터를 학습하고 테스트 셋으로 나누기 위하여 사용합니다.
### 당뇨 데이터셋
빌트-인된 [diabetes dataset](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset)은 당뇨에 대한 442개의 데이터 샘플이 있고, 10개의 feature 변수가 있으며, 그 일부는 아래와 같습니다:
- age: age in years
- bmi: body mass index
- bp: average blood pressure
- s1 tc: T-Cells (a type of white blood cells)
✅ 이 데이터셋에는 당뇨를 연구할 때 중요한 feature 변수인 '성' 컨셉이 포함되어 있습니다. 많은 의학 데이터셋에는 binary classification의 타입이 포함됩니다. 이처럼 categorizations이 치료에서 인구의 특정 파트를 제외할 수 있는 방법에 대하여 조금 고민해보세요.
이제, X 와 y 데이터를 불러옵니다.
> 🎓 다시 언급하지만, 지도 학습이며, 이름이 붙은 'y' 타겟이 필요합니다.
새로운 코드 셀에서, `load_diabetes()`를 호출하여 당뇨 데이터셋을 불러옵니다. 입력 `return_X_y=True`는 `X`를 data matrix, `y`를 regression 타겟으로 나타냅니다.
1. data matrix와 첫 요소의 모양을 보여주는 출력 명령을 몇 개 추가합니다:
```python
X, y = datasets.load_diabetes(return_X_y=True)
print(X.shape)
print(X[0])
```
응답하는 것은, tuple 입니다. 할 일은 tuple의 두 첫번째 값을 `X` 와 `y`에 각자 할당하는 것입니다. [about tuples](https://wikipedia.org/wiki/Tuple)을 봅시다.
데이터에 10개 요소의 배열로 이루어진 442개의 아이템이 보입니다:
```text
(442, 10)
[ 0.03807591 0.05068012 0.06169621 0.02187235 -0.0442235 -0.03482076
-0.04340085 -0.00259226 0.01990842 -0.01764613]
```
✅ 데이터와 regression 타겟의 관계를 잠시 생각해보세요. Linear regression은 feature X와 타겟 변수 y 사이 관계를 예측합니다. 문서에서 당뇨 데이터셋의 [target](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset)을 찾을 수 있나요? 타겟이 고려하면, 데이터셋은 무엇을 보여주나요?
2. 다음은, numpy의 `newaxis` 함수로 새로운 배열을 통해 플롯할 데이터셋의 일부를 선택합니다. 결정한 패턴에 맞춰서, 데이터의 값 사이에 라인을 생성하기 위하여 linear regression을 사용합니다.
```python
X = X[:, np.newaxis, 2]
```
✅ 언제나, 모양 확인 차 데이터를 출력할 수 있습니다.
3. 이제 데이터를 그릴 준비가 되었으므로, 머신이 데이터셋의 숫자 사이에서 논리적으로 판단하며 나누는 것을 도와주고 있는 지 확인할 수 있습니다. 그러면, 데이터 (X) 와 타겟 (y)를 테스트와 훈련 셋으로 나눌 필요가 있습니다. Scikit-learn에서는 간단한 방식이 존재합니다; 주어진 포인트에서 테스트 데이터를 나눌 수 있습니다.
```python
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33)
```
4. 이제 모델을 훈련할 준비가 되었습니다! linear regression 모델을 부르고 `model.fit()` 사용하여 X 와 y 훈련 셋으로 훈련합니다:
```python
model = linear_model.LinearRegression()
model.fit(X_train, y_train)
```
✅ `model.fit()`은 TensorFlow 처럼 많은 ML 라이브러리에서 볼 수 있는 함수입니다
5. 그러면, `predict()` 함수를 사용하여, 테스트 데이터로 prediction을 만듭니다. 데이터 그룹 사이에 라인을 그릴 때 사용합니다
```python
y_pred = model.predict(X_test)
```
6. 이제 plot으로 데이터를 나타낼 시간입니다. Matplotlib은 이 작업에서 매우 유용한 도구입니다. 모든 X 와 y 테스트 데이터의 scatterplot (산점도)를 만들고, prediction을 사용해서 모델의 데이터 그룹 사이, 가장 적절한 장소에 라인을 그립니다.
```python
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.xlabel('Scaled BMIs')
plt.ylabel('Disease Progression')
plt.title('A Graph Plot Showing Diabetes Progression Against BMI')
plt.show()
```
![a scatterplot showing datapoints around diabetes](.././images/scatterplot.png)
✅ 여기에 어떤 일이 생기는 지 생각합니다. 직선은 많은 데이터의 점을 지나지만, 무엇을 하고있나요? 라인으로 보이지 않는 데이터 포인트가 plot y 축으로 연관해서, 새롭게 맞출 지 예측하는 방식을 알 수 있을까요? 모델의 실제 사용 사례를 말 해봅니다.
축하드립니다. 첫 linear regression 모델을 만들고, 이를 통해서 prediction도 만들어서, plot에 보이게 했습니다!
---
## 🚀 도전
이 데이터셋은 다른 변수를 Plot 합니다. 힌트: 이 라인을 수정합니다: `X = X[:, np.newaxis, 2]`. 이 데이터셋의 타겟이 주어질 때, 질병으로 당뇨가 진행되면 어떤 것을 탐색할 수 있나요?
## [강의 후 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/10/)
## 검토 & 자기주도 학습
이 튜토리얼에서, univariate 또는 multiple linear regression이 아닌 simple linear regression으로 작업했습니다. 방식의 차이를 읽어보거나, [this video](https://www.coursera.org/lecture/quantifying-relationships-regression-models/linear-vs-nonlinear-categorical-variables-ai2Ef)를 봅니다.
regression의 개념에 대하여 더 읽고 기술로 답변할 수 있는 질문의 종류에 대하여 생각해봅니다. [tutorial](https://docs.microsoft.com/learn/modules/train-evaluate-regression-models?WT.mc_id=academic-15963-cxa)로 깊게 이해합니다.
## 과제
[A different dataset](../assignment.md)

@ -1,10 +1,10 @@
# 开始使用Python和Scikit学习回归模型
# 开始使用 Python 和 Scikit 学习回归模型
![回归](../../../sketchnotes/ml-regression.png)
> 作者[Tomomi Imura](https://www.twitter.com/girlie_mac)
> 作者 [Tomomi Imura](https://www.twitter.com/girlie_mac)
## [课前测](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/9/)
## [课前测](https://white-water-09ec41f0f.azurestaticapps.net/quiz/9/)
## 介绍
在这四节课中,你将了解如何构建回归模型。我们将很快讨论这些是什么。但在你做任何事情之前,请确保你有合适的工具来开始这个过程!
@ -12,45 +12,45 @@
在本课中,你将学习如何:
- 为本地机器学习任务配置你的计算机。
- 使用Jupyter notebooks。
- 使用Scikit-learn,包括安装。
- 使用 Jupyter notebooks。
- 使用 Scikit-learn,包括安装。
- 通过动手练习探索线性回归。
## 安装和配置
[![在 Visual Studio Code中使用 Python](https://img.youtube.com/vi/7EXd4_ttIuw/0.jpg)](https://youtu.be/7EXd4_ttIuw "在 Visual Studio Code中使用 Python")
[![在 Visual Studio Code 中使用 Python](https://img.youtube.com/vi/yyQM70vi7V8/0.jpg)](https://youtu.be/yyQM70vi7V8 "Setup Python with Visual Studio Code")
> 🎥 单击上图观看视频:在VS Code中使用Python。
> 🎥 单击上图观看视频:在 VS Code 中使用 Python。
1. **安装 Python**。确保你的计算机上安装了[Python](https://www.python.org/downloads/)。你将在许多数据科学和机器学习任务中使用 Python。大多数计算机系统已经安装了Python。也有一些有用的[Python编码包](https://code.visualstudio.com/learn/educations/installers?WT.mc_id=academic-15963-cxa)可用于简化某些用户的设置。
1. **安装 Python**。确保你的计算机上安装了 [Python](https://www.python.org/downloads/)。你将在许多数据科学和机器学习任务中使用 Python。大多数计算机系统已经安装了 Python。也有一些有用的 [Python 编码包](https://code.visualstudio.com/learn/educations/installers?WT.mc_id=academic-15963-cxa) 可用于简化某些用户的设置。
然而,Python的某些用法需要一个版本的软件,而其他用法则需要另一个不同的版本。 因此,在[虚拟环境](https://docs.python.org/3/library/venv.html)中工作很有用。
然而,Python 的某些用法需要一个版本的软件,而其他用法则需要另一个不同的版本。 因此,在 [虚拟环境](https://docs.python.org/3/library/venv.html) 中工作很有用。
2. **安装 Visual Studio Code**。确保你的计算机上安装了Visual Studio Code。按照这些说明[安装 Visual Studio Code](https://code.visualstudio.com/)进行基本安装。在本课程中,你将在Visual Studio Code中使用Python,因此你可能想复习如何[配置 Visual Studio Code](https://docs.microsoft.com/learn/modules/python-install-vscode?WT.mc_id=academic-15963-cxa)用于Python开发。
2. **安装 Visual Studio Code**。确保你的计算机上安装了 Visual Studio Code。按照这些说明 [安装 Visual Studio Code](https://code.visualstudio.com/) 进行基本安装。在本课程中,你将在 Visual Studio Code 中使用 Python,因此你可能想复习如何 [配置 Visual Studio Code](https://docs.microsoft.com/learn/modules/python-install-vscode?WT.mc_id=academic-15963-cxa) 用于 Python 开发。
> 通过学习这一系列的 [学习模块](https://docs.microsoft.com/users/jenlooper-2911/collections/mp1pagggd5qrq7?WT.mc_id=academic-15963-cxa)熟悉Python
> 通过学习这一系列的 [学习模块](https://docs.microsoft.com/users/jenlooper-2911/collections/mp1pagggd5qrq7?WT.mc_id=academic-15963-cxa) 熟悉 Python
3. **按照[这些说明]安装Scikit learn**(https://scikit-learn.org/stable/install.html)。由于你需要确保使用Python3,因此建议你使用虚拟环境。注意,如果你是在M1 Mac上安装这个库,在上面链接的页面上有特别的说明。
3. **按照 [这些说明](https://scikit-learn.org/stable/install.html) 安装 Scikit learn**。由于你需要确保使用 Python3,因此建议你使用虚拟环境。注意,如果你是在 M1 Mac 上安装这个库,在上面链接的页面上有特别的说明。
4. **安装Jupyter Notebook**。你需要[安装Jupyter包](https://pypi.org/project/jupyter/)。
4. **安装 Jupyter Notebook**。你需要 [安装 Jupyter 包](https://pypi.org/project/jupyter/)。
## 你的ML工作环境
## 你的 ML 工作环境
你将使用**notebooks**开发Python代码并创建机器学习模型。这种类型的文件是数据科学家的常用工具,可以通过后缀或扩展名`.ipynb`来识别它们。
你将使用 **notebooks** 开发 Python 代码并创建机器学习模型。这种类型的文件是数据科学家的常用工具,可以通过后缀或扩展名 `.ipynb` 来识别它们。
Notebooks是一个交互式环境,允许开发人员编写代码并添加注释并围绕代码编写文档,这对于实验或面向研究的项目非常有帮助。
Notebooks 是一个交互式环境,允许开发人员编写代码并添加注释并围绕代码编写文档,这对于实验或面向研究的项目非常有帮助。
### 练习 - 使用notebook
### 练习 - 使用 notebook
1. 在Visual Studio Code中打开_notebook.ipynb_。
1. 在 Visual Studio Code 中打开 _notebook.ipynb_。
Jupyter服务器将以python3+启动。你会发现notebook可以“运行”的区域、代码块。你可以通过选择看起来像播放按钮的图标来运行代码块。
Jupyter 服务器将以 python3+启动。你会发现 notebook 可以“运行”的区域、代码块。你可以通过选择看起来像播放按钮的图标来运行代码块。
2. 选择`md`图标并添加一点markdown,输入文字**#Welcome to your notebook**。
2. 选择 `md` 图标并添加一点 markdown,输入文字 **# Welcome to your notebook**。
接下来,添加一些Python代码。
接下来,添加一些 Python 代码。
1. 在代码块中输入**print("hello notebook")**。
1. 在代码块中输入 **print("hello notebook")**。
2. 选择箭头运行代码。
@ -60,43 +60,43 @@ Notebooks是一个交互式环境,允许开发人员编写代码并添加注
hello notebook
```
![打开notebook的VS Code](../images/notebook.png)
![打开 notebook 的 VS Code](../images/notebook.png)
你可以为你的代码添加注释,以便notebook可以自描述。
你可以为你的代码添加注释,以便 notebook 可以自描述。
✅ 想一想web开发人员的工作环境与数据科学家的工作环境有多大的不同。
✅ 想一想 web 开发人员的工作环境与数据科学家的工作环境有多大的不同。
## 启动并运行Scikit-learn
## 启动并运行 Scikit-learn
现在Python已在你的本地环境中设置好,并且你对Jupyter notebook感到满意,让我们同样熟悉Scikit-learn(在“science”中发音为“sci”)。 Scikit-learn提供了[大量的API](https://scikit-learn.org/stable/modules/classes.html#api-ref)来帮助你执行ML任务。
现在 Python 已在你的本地环境中设置好,并且你对 Jupyter notebook 感到满意,让我们同样熟悉 Scikit-learn(在“science”中发音为“sci”)。 Scikit-learn 提供了 [大量的 API](https://scikit-learn.org/stable/modules/classes.html#api-ref) 来帮助你执行 ML 任务。
根据他们的[网站](https://scikit-learn.org/stable/getting_started.html),“Scikit-learn是一个开源机器学习库,支持有监督和无监督学习。它还提供了各种模型拟合工具、数据预处理、模型选择和评估以及许多其他实用程序。”
根据他们的 [网站](https://scikit-learn.org/stable/getting_started.html),“Scikit-learn 是一个开源机器学习库,支持有监督和无监督学习。它还提供了各种模型拟合工具、数据预处理、模型选择和评估以及许多其他实用程序。”
在本课程中,你将使用Scikit-learn和其他工具来构建机器学习模型,以执行我们所谓的“传统机器学习”任务。我们特意避免了神经网络和深度学习,因为它们在我们即将推出的“面向初学者的人工智能”课程中得到了更好的介绍。
在本课程中,你将使用 Scikit-learn 和其他工具来构建机器学习模型,以执行我们所谓的“传统机器学习”任务。我们特意避免了神经网络和深度学习,因为它们在我们即将推出的“面向初学者的人工智能”课程中得到了更好的介绍。
Scikit-learn使构建模型和评估它们的使用变得简单。它主要侧重于使用数字数据,并包含几个现成的数据集用作学习工具。它还包括供学生尝试的预建模型。让我们探索加载预先打包的数据和使用内置的estimator first ML模型和Scikit-learn以及一些基本数据的过程。
Scikit-learn 使构建模型和评估它们的使用变得简单。它主要侧重于使用数字数据,并包含几个现成的数据集用作学习工具。它还包括供学生尝试的预建模型。让我们探索加载预先打包的数据和使用内置的 estimator first ML 模型和 Scikit-learn 以及一些基本数据的过程。
## 练习 - 你的第一个Scikit-learn notebook
## 练习 - 你的第一个 Scikit-learn notebook
> 本教程的灵感来自Scikit-learn网站上的[线性回归示例](https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py)。
> 本教程的灵感来自 Scikit-learn 网站上的 [线性回归示例](https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py)。
在与本课程相关的_notebook.ipynb_文件中,通过点击“垃圾桶”图标清除所有单元格。
在与本课程相关的 _notebook.ipynb_ 文件中,通过点击“垃圾桶”图标清除所有单元格。
在本节中,你将使用一个关于糖尿病的小数据集,该数据集内置于Scikit-learn中以用于学习目的。想象一下,你想为糖尿病患者测试一种治疗方法。机器学习模型可能会帮助你根据变量组合确定哪些患者对治疗反应更好。即使是非常基本的回归模型,在可视化时,也可能会显示有助于组织理论临床试验的变量信息。
在本节中,你将使用一个关于糖尿病的小数据集,该数据集内置于 Scikit-learn 中以用于学习目的。想象一下,你想为糖尿病患者测试一种治疗方法。机器学习模型可能会帮助你根据变量组合确定哪些患者对治疗反应更好。即使是非常基本的回归模型,在可视化时,也可能会显示有助于组织理论临床试验的变量信息。
✅ 回归方法有很多种,你选择哪一种取决于你正在寻找的答案。如果你想预测给定年龄的人的可能身高,你可以使用线性回归,因为你正在寻找**数值**。如果你有兴趣了解某种菜肴是否应被视为素食主义者,那么你正在寻找**类别分配**,以便使用逻辑回归。稍后你将了解有关逻辑回归的更多信息。想一想你可以对数据提出的一些问题,以及这些方法中的哪一个更合适。
✅ 回归方法有很多种,你选择哪一种取决于你正在寻找的答案。如果你想预测给定年龄的人的可能身高,你可以使用线性回归,因为你正在寻找**数值**。如果你有兴趣了解某种菜肴是否应被视为素食主义者,那么你正在寻找**类别分配**,以便使用逻辑回归。稍后你将了解有关逻辑回归的更多信息。想一想你可以对数据提出的一些问题,以及这些方法中的哪一个更合适。
让我们开始这项任务。
让我们开始这项任务。
### 导入库
对于此任务,我们将导入一些库:
- **matplotlib**。这是一个有用的[绘图工具](https://matplotlib.org/),我们将使用它来创建线图。
- **numpy**。 [numpy](https://numpy.org/doc/stable/user/whatisnumpy.html)是一个有用的库,用于在Python中处理数字数据。
- **sklearn**。这是Scikit-learn库。
- **matplotlib**。这是一个有用的 [绘图工具](https://matplotlib.org/),我们将使用它来创建线图。
- **numpy**。 [numpy](https://numpy.org/doc/stable/user/whatisnumpy.html) 是一个有用的库,用于在 Python 中处理数字数据。
- **sklearn**。这是 Scikit-learn 库。
导入一些库来帮助你完成任务。
导入一些库来帮助你完成任务。
1. 通过输入以下代码添加导入:
@ -106,24 +106,24 @@ Scikit-learn使构建模型和评估它们的使用变得简单。它主要侧
from sklearn import datasets, linear_model, model_selection
```
在上面的代码中,你正在导入`matplottlib`、`numpy`,你正在从`sklearn`导入`datasets`、`linear_model`和`model_selection`。 `model_selection`用于将数据拆分为训练集和测试集。
在上面的代码中,你正在导入 `matplottlib`、`numpy`,你正在从 `sklearn` 导入 `datasets`、`linear_model` 和 `model_selection`。 `model_selection` 用于将数据拆分为训练集和测试集。
### 糖尿病数据集
### 糖尿病数据集
内置的[糖尿病数据集](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset)包含442个围绕糖尿病的数据样本,具有10个特征变量,其中包括:
内置的 [糖尿病数据集](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset) 包含 442 个围绕糖尿病的数据样本,具有 10 个特征变量,其中包括:
age:岁数
bmi:体重指数
bp:平均血压
s1 tc:T细胞(一种白细胞)
- age:岁数
- bmi:体重指数
- bp:平均血压
- s1 tc:T 细胞(一种白细胞)
✅ 该数据集包括“性别”的概念,作为对糖尿病研究很重要的特征变量。许多医学数据集包括这种类型的二元分类。想一想诸如此类的分类如何将人群的某些部分排除在治疗之外。
✅ 该数据集包括“性别”的概念,作为对糖尿病研究很重要的特征变量。许多医学数据集包括这种类型的二元分类。想一想诸如此类的分类如何将人群的某些部分排除在治疗之外。
现在,加载X和y数据。
现在,加载 X 和 y 数据。
> 🎓 请记住,这是监督学习,我们需要一个命名为“y”的目标。
> 🎓 请记住,这是监督学习,我们需要一个命名为“y”的目标。
在新的代码单元中,通过调用`load_diabetes()`加载糖尿病数据集。输入`return_X_y=True`表示`X`将是一个数据矩阵,而`y`将是回归目标。
在新的代码单元中,通过调用 `load_diabetes()` 加载糖尿病数据集。输入 `return_X_y=True` 表示 `X` 将是一个数据矩阵,而`y`将是回归目标。
1. 添加一些打印命令来显示数据矩阵的形状及其第一个元素:
@ -133,9 +133,9 @@ s1 tc:T细胞(一种白细胞)
print(X[0])
```
作为响应返回的是一个元组。你正在做的是将元组的前两个值分别分配给`X`和`y`。了解更多 [关于元组](https://wikipedia.org/wiki/Tuple)。
作为响应返回的是一个元组。你正在做的是将元组的前两个值分别分配给 `X` 和 `y`。了解更多 [关于元组](https://wikipedia.org/wiki/Tuple)。
你可以看到这个数据有442个项目,组成了10个元素的数组:
你可以看到这个数据有 442 个项目,组成了 10 个元素的数组:
```text
(442, 10)
@ -143,38 +143,38 @@ s1 tc:T细胞(一种白细胞)
-0.04340085 -0.00259226 0.01990842 -0.01764613]
```
✅ 稍微思考一下数据和回归目标之间的关系。线性回归预测特征X和目标变量y之间的关系。你能在文档中找到糖尿病数据集的[目标](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset)吗?鉴于该目标,该数据集展示了什么?
✅ 稍微思考一下数据和回归目标之间的关系。线性回归预测特征 X 和目标变量 y 之间的关系。你能在文档中找到糖尿病数据集的 [目标](https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset) 吗?鉴于该目标,该数据集展示了什么?
2. 接下来,通过使用numpy的`newaxis`函数将其排列到一个新数组中来选择要绘制的该数据集的一部分。我们将使用线性回归根据它确定的模式在此数据中的值之间生成一条线。
2. 接下来,通过使用 numpy 的 `newaxis` 函数将数据集的一部分排列到一个新数组中。我们将使用线性回归根据它确定的模式在此数据中的值之间生成一条线。
```python
X = X[:, np.newaxis, 2]
```
✅ 随时打印数据以检查其形状。
✅ 随时打印数据以检查其形状。
3. 现在你已准备好绘制数据,你可以查看机器是否可以帮助确定此数据集中数字之间的逻辑分割。为此你需要将数据(X)和目标(y)拆分为测试集和训练集。Scikit-learn有一个简单的方法来做到这一点;你可以在给定点拆分测试数据。
3. 现在你已准备好绘制数据,你可以看到计算机是否可以帮助确定此数据集中数字之间的逻辑分割。为此你需要将数据 (X) 和目标 (y) 拆分为测试集和训练集。Scikit-learn 有一个简单的方法来做到这一点;你可以在给定点拆分测试数据。
```python
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.33)
```
4. 现在你已准备好训练你的模型!加载线性回归模型并使用`model.fit()`使用X和y训练集对其进行训练:
4. 现在你已准备好训练你的模型!加载线性回归模型并使用 `model.fit()` 使用 X 和 y 训练集对其进行训练:
```python
model = linear_model.LinearRegression()
model.fit(X_train, y_train)
```
✅ `model.fit()`是一个你会在许多机器学习库(例如 TensorFlow)中看到的函数
✅ `model.fit()` 是一个你会在许多机器学习库(例如 TensorFlow)中看到的函数
5. 然后,使用函数`predict()`,使用测试数据创建预测。这将用于绘制数据组之间的线
5. 然后,使用函数 `predict()`,使用测试数据创建预测。这将用于绘制数据组之间的线
```python
y_pred = model.predict(X_test)
```
6. 现在是时候在图中显示数据了。Matplotlib是完成此任务的非常有用的工具。创建所有X和y测试数据的散点图,并使用预测在模型的数据分组之间最合适的位置画一条线。
6. 现在是时候在图中显示数据了。Matplotlib 是完成此任务的非常有用的工具。创建所有 X 和 y 测试数据的散点图,并使用预测在模型的数据分组之间最合适的位置画一条线。
```python
plt.scatter(X_test, y_test, color='black')
@ -184,22 +184,24 @@ s1 tc:T细胞(一种白细胞)
![显示糖尿病周围数据点的散点图](../images/scatterplot.png)
✅ 想一想这里发生了什么。一条直线穿过许多小数据点,但它到底在做什么?你能看到你应该如何使用这条线来预测一个新的、未见过的数据点对应的y轴值吗?尝试用语言描述该模型的实际用途。
✅ 想一想这里发生了什么。一条直线穿过许多小数据点,但它到底在做什么?你能看到你应该如何使用这条线来预测一个新的、未见过的数据点对应的 y 轴值吗?尝试用语言描述该模型的实际用途。
恭喜,你构建了第一个线性回归模型,使用它创建了预测,并将其显示在绘图中!
恭喜,你构建了第一个线性回归模型,使用它创建了预测,并将其显示在绘图中!
---
## 🚀挑战
从这个数据集中绘制一个不同的变量。提示:编辑这一行:`X = X[:, np.newaxis, 2]`。鉴于此数据集的目标,你能够发现糖尿病作为一种疾病的进展情况吗?
## [课后测](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/10/)
## [课后测](https://white-water-09ec41f0f.azurestaticapps.net/quiz/10/)
## 复习与自学
在本教程中,你使用了简单线性回归,而不是单变量或多元线性回归。阅读一些关于这些方法之间差异的信息,或查看[此视频](https://www.coursera.org/lecture/quantifying-relationships-regression-models/linear-vs-nonlinear-categorical-variables-ai2Ef)
在本教程中,你使用了简单线性回归,而不是单变量或多元线性回归。阅读一些关于这些方法之间差异的信息,或查看 [此视频](https://www.coursera.org/lecture/quantifying-relationships-regression-models/linear-vs-nonlinear-categorical-variables-ai2Ef)
阅读有关回归概念的更多信息,并思考这种技术可以回答哪些类型的问题。用这个[教程](https://docs.microsoft.com/learn/modules/train-evaluate-regression-models?WT.mc_id=academic-15963-cxa)加深你的理解。
阅读有关回归概念的更多信息,并思考这种技术可以回答哪些类型的问题。用这个 [教程](https://docs.microsoft.com/learn/modules/train-evaluate-regression-models?WT.mc_id=academic-15963-cxa) 加深你的理解。
## 任务
[不同的数据集](../assignment.md)
[不同的数据集](./assignment.zh-cn.md)

@ -0,0 +1,14 @@
# Regresión con Scikit-learn
## Instrucciones
Eche un vistazo al [Linnerud _dataset_](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_linnerud.html#sklearn.datasets.load_linnerud) en Scikit-learn. Este _dataset_ tiene varios [objetivos](https://scikit-learn.org/stable/datasets/toy_dataset.html#linnerrud-dataset): 'Consiste en tres ejercicios (datos) y tres variables fisiológicas (objetivos) recopiladas de veinte hombres de mediana edad en un gimnasio'.
En sus palabras, describa como crear un modelo de regresión que trazaría la relación entre la cintura y la cantidad de abdominales que se realizan. Haga lo mismo con otros puntos de datos en el _dataset_.
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita Mejorar |
| ------------------------------ | ----------------------------------- | ----------------------------- | -------------------------- |
| Envíe un párrafo descriptivo | Se envía un párrafo bien escrito | Se envían algunas frases | No se proporciona ninguna descripción |

@ -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)で構成されています。
あなた自身の言葉で、ウエストラインと腹筋の回数との関係をプロットする回帰モデルの作成方法を説明してください。このデータセットの他のデータポイントについても同様に説明してみてください。
## ルーブリック
| 指標 | 模範的 | 適切 | 要改善 |
| ------------------------------ | ----------------------------------- | ----------------------------- | -------------------------- |
| 説明文を提出してください。 | よく書けた文章が提出されている。 | いくつかの文章が提出されている。 | 文章が提出されていません。 |

@ -0,0 +1,14 @@
# 用 Scikit-learn 实现一次回归算法
## 说明
先看看 Scikit-learn 中的 [Linnerud 数据集](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_linnerud.html#sklearn.datasets.load_linnerud)
这个数据集中有多个[目标变量(target)](https://scikit-learn.org/stable/datasets/toy_dataset.html#linnerrud-dataset),其中包含了三种运动(训练数据)和三个生理指标(目标变量)组成,这些数据都是从一个健身俱乐部中的 20 名中年男子收集到的。
之后用自己的方式,创建一个可以描述腰围和完成仰卧起坐个数关系的回归模型。用同样的方式对这个数据集中的其它数据也建立一下模型探究一下其中的关系。
## 评判标准
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
| ------------------------------ | ----------------------------------- | ----------------------------- | -------------------------- |
| 需要提交一段能描述数据集中关系的文字 | 很好的描述了数据集中的关系 | 只能描述少部分的关系 | 啥都没有提交 |

@ -1,9 +1,12 @@
# Build a regression model using Scikit-learn: prepare and visualize data
> ![Data visualization infographic](./images/data-visualization.png)
> Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded)
![Data visualization infographic](./images/data-visualization.png)
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/11/)
Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/11/)
> ### [This lesson is available in R!](./solution/R/lesson_2-R.ipynb)
## Introduction
@ -14,6 +17,10 @@ In this lesson, you will learn:
- How to prepare your data for model-building.
- How to use Matplotlib for data visualization.
[![Preparing and Visualizing data](https://img.youtube.com/vi/11AnOn_OAcE/0.jpg)](https://youtu.be/11AnOn_OAcE "Preparing and Visualizing data video - Click to Watch!")
> 🎥 Click the image above for a video covering key aspects of this lesson
## Asking the right question of your data
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.
@ -34,7 +41,7 @@ This data is in the public domain. It can be downloaded in many separate files,
What do you notice about this data? You already saw that there is a mix of strings, numbers, blanks and strange values that you need to make sense of.
What question can you ask of this data, using a Regression technique? What about "Predict the price of a pumpkin for sale during a given month". Looking again at the data, there are some changes you need to make to create the data structure necessary for the task.
What question can you ask of this data, using a Regression technique? What about "Predict the price of a pumpkin for sale during a given month". Looking again at the data, there are some changes you need to make to create the data structure necessary for the task.
## Exercise - analyze the pumpkin data
Let's use [Pandas](https://pandas.pydata.org/), (the name stands for `Python Data Analysis`) a tool very useful for shaping data, to analyze and prepare this pumpkin data.
@ -66,7 +73,7 @@ Open the _notebook.ipynb_ file in Visual Studio Code and import the spreadsheet
There is missing data, but maybe it won't matter for the task at hand.
1. To make your dataframe easier to work with, drop several of its columns, using `drop()`, keeping only the columns you need:
1. To make your dataframe easier to work with, drop several of its columns, using `drop()`, keeping only the columns you need:
```python
new_columns = ['Package', 'Month', 'Low Price', 'High Price', 'Date']
@ -83,9 +90,9 @@ Solution: take the average of the `Low Price` and `High Price` columns to popula
```python
price = (pumpkins['Low Price'] + pumpkins['High Price']) / 2
month = pd.DatetimeIndex(pumpkins['Date']).month
```
✅ Feel free to print any data you'd like to check using `print(month)`.
@ -122,7 +129,7 @@ Did you notice that the bushel amount varies per row? You need to normalize the
```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)
```
@ -134,7 +141,7 @@ Now, you can analyze the pricing per unit based on their bushel measurement. If
## Visualization Strategies
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.
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.
@ -189,7 +196,7 @@ To get charts to display useful data, you usually need to group the data somehow
Explore the different types of visualization that Matplotlib offers. Which types are most appropriate for regression problems?
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/12/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/12/)
## Review & Self Study

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

@ -0,0 +1 @@
This is a temporary placeholder

@ -0,0 +1,664 @@
{
"nbformat": 4,
"nbformat_minor": 2,
"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",
"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",
"\n",
"<p >\n",
" <img src=\"../../images/unruly_data.jpg\"\n",
" width=\"700\"/>\n",
" <figcaption>Artwork by @allison_horst</figcaption>\n",
"\n",
"\n",
"<!--![Artwork by \\@allison_horst](../../images/unruly_data.jpg)<br>Artwork by \\@allison_horst-->"
],
"metadata": {
"id": "Pg5aexcOPqAZ"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "dc5WhyVdXAjR"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"suppressWarnings(if(!require(\"pacman\")) install.packages(\"pacman\"))\n",
"pacman::p_load(tidyverse)"
],
"outputs": [],
"metadata": {
"id": "GqPYUZgfXOBt"
}
},
{
"cell_type": "markdown",
"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!"
],
"metadata": {
"id": "kvjDTPDSXRr2"
}
},
{
"cell_type": "code",
"execution_count": null,
"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)"
],
"outputs": [],
"metadata": {
"id": "VMri-t2zXqgD"
}
},
{
"cell_type": "markdown",
"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"
],
"metadata": {
"id": "REWcIv9yX29v"
}
},
{
"cell_type": "markdown",
"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`"
],
"metadata": {
"id": "Zxfb3AM5YbUe"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"pumpkins %>% \n",
" anyNA()"
],
"outputs": [],
"metadata": {
"id": "G--DQutAYltj"
}
},
{
"cell_type": "markdown",
"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`."
],
"metadata": {
"id": "mU-7-SB6YokF"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"pumpkins %>% \n",
" is.na() %>% \n",
" head(n = 7)"
],
"outputs": [],
"metadata": {
"id": "W-DxDOR4YxSW"
}
},
{
"cell_type": "markdown",
"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:"
],
"metadata": {
"id": "xUWxipKYY0o7"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"pumpkins %>% \n",
" is.na() %>% \n",
" colSums()"
],
"outputs": [],
"metadata": {
"id": "ZRBWV6P9ZArL"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "9gv-crB6ZD1Y"
}
},
{
"cell_type": "markdown",
"source": [
"## 3. Dplyr: A Grammar of Data Manipulation\n",
"\n",
"\n",
"<p >\n",
" <img src=\"../../images/dplyr_wrangling.png\"\n",
" width=\"569\"/>\n",
" <figcaption>Artwork by @allison_horst</figcaption>\n",
"\n",
"\n",
"<!--![Artwork by \\@allison_horst](../../images/dplyr_wrangling.png)<br/>Artwork by \\@allison_horst-->"
],
"metadata": {
"id": "o4jLY5-VZO2C"
}
},
{
"cell_type": "markdown",
"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"
],
"metadata": {
"id": "i5o33MQBZWWw"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "x3VGMAGBZiUr"
}
},
{
"cell_type": "code",
"execution_count": null,
"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)"
],
"outputs": [],
"metadata": {
"id": "F_FgxQnVZnM0"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "2KKo0Ed9Z1VB"
}
},
{
"cell_type": "code",
"execution_count": null,
"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)"
],
"outputs": [],
"metadata": {
"id": "5joszIVSZ6xe"
}
},
{
"cell_type": "markdown",
"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>"
],
"metadata": {
"id": "nIgLjNMCZ-6Y"
}
},
{
"cell_type": "code",
"execution_count": null,
"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)"
],
"outputs": [],
"metadata": {
"id": "Zo0BsqqtaJw2"
}
},
{
"cell_type": "markdown",
"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:"
],
"metadata": {
"id": "p77WZr-9aQAR"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Verify the distinct observations in Package column\n",
"pumpkins %>% \n",
" distinct(Package)"
],
"outputs": [],
"metadata": {
"id": "XISGfh0IaUy6"
}
},
{
"cell_type": "markdown",
"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>"
],
"metadata": {
"id": "7sMjiVujaZxY"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "L8Qfcs92ageF"
}
},
{
"cell_type": "code",
"execution_count": null,
"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)"
],
"outputs": [],
"metadata": {
"id": "hy_SGYREampd"
}
},
{
"cell_type": "markdown",
"source": [
"You can see that we have narrowed down to 415 or so rows of data containing pumpkins by the bushel.🤩\n",
"<br>"
],
"metadata": {
"id": "VrDwF031avlR"
}
},
{
"cell_type": "markdown",
"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"
],
"metadata": {
"id": "mLpw2jH4a0tx"
}
},
{
"cell_type": "code",
"execution_count": null,
"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)"
],
"outputs": [],
"metadata": {
"id": "P68kLVQmbM6I"
}
},
{
"cell_type": "markdown",
"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"
],
"metadata": {
"id": "pS2GNPagbSdb"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "qql1SowfbdnP"
}
},
{
"cell_type": "code",
"execution_count": null,
"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)"
],
"outputs": [],
"metadata": {
"id": "JJ1x6kw8bixF"
}
},
{
"cell_type": "markdown",
"source": [
"Good job!👌 You now have a clean, tidy dataset on which you can build your new regression model!\n",
"<br>"
],
"metadata": {
"id": "y8TJ0Za_bn5Y"
}
},
{
"cell_type": "markdown",
"source": [
"## 4. Data visualization with ggplot2\n",
"\n",
"<p >\n",
" <img src=\"../../images/data-visualization.png\"\n",
" width=\"600\"/>\n",
" <figcaption>Infographic by Dasani Madipalli</figcaption>\n",
"\n",
"\n",
"<!--![Infographic by Dasani Madipalli](../../images/data-visualization.png){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"
],
"metadata": {
"id": "mYSH6-EtbvNa"
}
},
{
"cell_type": "code",
"execution_count": null,
"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()"
],
"outputs": [],
"metadata": {
"id": "g2YjnGeOcLo4"
}
},
{
"cell_type": "markdown",
"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>"
],
"metadata": {
"id": "Ml7SDCLQcPvE"
}
},
{
"cell_type": "markdown",
"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."
],
"metadata": {
"id": "jMakvJZIcVkh"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Find the average price of pumpkins per month\r\n",
"new_pumpkins %>%\r\n",
" group_by(Month) %>% \r\n",
" summarise(mean_price = mean(Price))"
],
"outputs": [],
"metadata": {
"id": "6kVSUa2Bcilf"
}
},
{
"cell_type": "markdown",
"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!"
],
"metadata": {
"id": "Kds48GUBcj3W"
}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# Find the average price of pumpkins per month then plot a bar chart\r\n",
"new_pumpkins %>%\r\n",
" group_by(Month) %>% \r\n",
" summarise(mean_price = mean(Price)) %>% \r\n",
" ggplot(aes(x = Month, y = mean_price)) +\r\n",
" geom_col(fill = \"midnightblue\", alpha = 0.7) +\r\n",
" ylab(\"Pumpkin Price\")"
],
"outputs": [],
"metadata": {
"id": "VNbU1S3BcrxO"
}
},
{
"cell_type": "markdown",
"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!"
],
"metadata": {
"id": "zDm0VOzzcuzR"
}
}
]
}

@ -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.
![Artwork by \@allison_horst](../../images/unruly_data.jpg){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
![Artwork by \@allison_horst](../../images/dplyr_wrangling.png){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
![Infographic by Dasani Madipalli](../../images/data-visualization.png){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 prepared your data for model building, then uncovered more insights using visualizations!

@ -3,7 +3,7 @@
![Infografik visualisasi data](../images/data-visualization.png)
> Infografik oleh [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [Kuis pra-ceramah](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/11/)
## [Kuis pra-ceramah](https://white-water-09ec41f0f.azurestaticapps.net/quiz/11/)
## Pembukaan
@ -191,7 +191,7 @@ Untuk menjadikan sebuah grafik menjadi berguna, biasanya datanya harus dikelompo
Jelajahi jenis-jenis visualisasi yang beda dan yang disediakan Matplotlib. Jenis mana yang paling cocok untuk kasus regresi?
## [Kuis pasca-ceramah](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/12/)
## [Kuis pasca-ceramah](https://white-water-09ec41f0f.azurestaticapps.net/quiz/12/)
## Review & Pembelajaran Mandiri

@ -0,0 +1,201 @@
# Costruire un modello di regressione usando Scikit-learn: preparare e visualizzare i dati
> ![Infografica sulla visualizzazione dei dati](../images/data-visualization.png)
> Infografica di [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [Quiz pre-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/11/?loc=it)
## 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 grafico a dispersione che mostra la relazione tra prezzo e mese](../images/scatterplot.png)
È 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")
```
![Un grafico a barre che mostra la relazione tra prezzo e mese](../images/barchart.png)
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://white-water-09ec41f0f.azurestaticapps.net/quiz/12/?loc=it)
## 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)

@ -4,7 +4,7 @@
>
> [Dasani Madipalli](https://twitter.com/dasani_decoded) によるインフォグラフィック
## [講義前のクイズ](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/11/)
## [講義前のクイズ](https://white-water-09ec41f0f.azurestaticapps.net/quiz/11?loc=ja)
## イントロダクション
@ -61,7 +61,7 @@ Visual Studio Codeで _notebook.ipynb_ ファイルを開き、スプレッド
✅ 最後の5行を表示するには、どのような関数を使用しますか?
1. 現在のデータフレームに欠損データがあるかどうかをチェックします。
2. 現在のデータフレームに欠損データがあるかどうかをチェックします。
```python
pumpkins.isnull().sum()
@ -70,7 +70,7 @@ Visual Studio Codeで _notebook.ipynb_ ファイルを開き、スプレッド
欠損データがありましたが、今回のタスクには影響がなさそうです。
1. データフレームを扱いやすくするために、`drop()` 関数を使っていくつかの列を削除し、必要な列だけを残すようにします。
3. データフレームを扱いやすくするために、`drop()` 関数を使っていくつかの列を削除し、必要な列だけを残すようにします。
```python
new_columns = ['Package', 'Month', 'Low Price', 'High Price', 'Date']
@ -195,7 +195,7 @@ Jupyter notebookでうまく利用できるテータ可視化ライブラリの
Matplotlibが提供する様々なタイプのビジュアライゼーションを探ってみましょう。回帰の問題にはどのタイプが最も適しているでしょうか?
## [講義後クイズ](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/12/)
## [講義後クイズ](https://white-water-09ec41f0f.azurestaticapps.net/quiz/12?loc=ja)
## レビュー & 自主学習
@ -203,4 +203,4 @@ Matplotlibが提供する様々なタイプのビジュアライゼーション
## 課題
[ビジュアライゼーションの探求](assignment.md)
[ビジュアライゼーションの探求](./assignment.ja.md)

@ -0,0 +1,202 @@
# Scikit-learn 사용한 regression 모델 만들기: 데이터 준비와 시각화
> ![Data visualization infographic](.././images/data-visualization.png)
> Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [강의 전 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/11/)
## 소개
이제 Scikit-learn으로 머신러닝 모델을 만들기 시작할 때 필요한 도구를 세팅했으므로, 데이터에 대한 질문을 할 준비가 되었습니다. 데이터로 작업하고 ML 솔루션을 적용하려면, 데이터셋의 잠재력을 잘 분석하기 위하여 올바른 질문 방식을 이해하는 것이 매우 중요합니다.
이 강의에서, 다음을 배웁니다:
- 모델-제작 위한 데이터 준비하는 방식.
- 데이터 시각화 위한 Matplotlib 사용하는 방식.
## 데이터에 올바른 질문하기
답변이 필요한 질문에 따라서 활용할 ML 알고리즘의 타입이 결정됩니다. 그리고 받는 답변의 퀄리티는 데이터의 성격에 크게 의존됩니다.
이 강의에서 제공되는 [data](../data/US-pumpkins.csv)를 보세요. VS Code에서 .csv 파일을 열 수 있습니다. 빠르게 흝어보면 공백과 문자열과 숫자 데이터가 섞여진 것을 보여줍니다. 'Package'라고 불리는 이상한 열에 'sacks', 'bins'과 다른 값 사이에 섞인 데이터가 있습니다. 사실은, 조금 엉성합니다.
실제로, ML 모델을 바로 꺼내 만들면서 완벽하게 사용할 준비가 된 데이터셋을 주는 건 매우 평범하지 않습니다. 이 강의에서는, 표준 Python 라이브러리로 원본 데이터셋을 준비하는 과정을 배우게 됩니다. 데이터 시각화하는 다양한 기술을 배웁니다.
## 케이스 스터디: 'the pumpkin market'
이 폴더에서는 호박 시장에 대한 데이터 1757 라인이 도시별로 분류된 [US-pumpkins.csv](../../data/US-pumpkins.csv) 라고 불리는 최상위 `data` 폴더에서 .csv 파일을 찾을 수 있습니다. United States Department of Agriculture가 배포한 [Specialty Crops Terminal Markets Standard Reports](https://www.marketnews.usda.gov/mnp/fv-report-config-step1?type=termPrice)에서 원본 데이터를 추출했습니다.
### 데이터 준비하기
이 데이터는 공개 도메인에 존재합니다. USDA 웹사이트에서, 도시별로, 많은 여러개 파일을 내려받을 수 있습니다. 너무 많이 분리된 파일들을 피하기 위해서, 모든 도시 데이터를 한 개의 스프레드 시트에 연결했으므로, 미리 데이터를 조금 _준비_ 했습니다. 다음으로, 데이터를 가까이 봅니다.
### 호박 데이터 - 이른 결론
데이터에서 어떤 것을 눈치챘나요? 이해할 문자열, 숫자, 공백과 이상한 값이 섞여있다는 것을 이미 봤습니다.
Regression 기술을 사용해서, 데이터에 물어볼 수 있는 질문인가요? "Predict the price of a pumpkin for sale during a given month"는 어떤가요. 데이터를 다시보면, 작업에 필요한 데이터 구조를 만들기 위하여 조금 바꿀 점이 있습니다.
## 연습 - 호박 데이터 분석하기
호박 데이터를 분석하고 준비하며, 데이터를 구성할 때 매우 유용한 도구인, [Pandas](https://pandas.pydata.org/) (`Python Data Analysis`의 약자)를 사용해봅시다.
### 먼저, 누락된 날짜를 확인합니다.
먼저 누락된 데이터들을 확인하는 단계가 필요합니다:
1. 날짜를 월 포맷으로 변환합니다 (US 날짜라서 `MM/DD/YYYY` 포맷).
2. month를 새로운 열로 추출합니다.
visual Studio Code에서 _notebook.ipynb_ 파일을 열고 새로운 Pandas 데아터프레임에 spreadsheet를 가져옵니다.
1. 처음 5개 행을 보기 위하여 `head()` 함수를 사용합니다.
```python
import pandas as pd
pumpkins = pd.read_csv('../data/US-pumpkins.csv')
pumpkins.head()
```
✅ 마지막 5개 행을 보려면 어떤 함수를 사용하나요?
1. 지금 데이터프레임에 누락된 데이터가 있다면 확인합니다:
```python
pumpkins.isnull().sum()
```
누락된 데이터이지만, 당장 앞에 있는 작업에는 중요하지 않을 수 있습니다.
1. 데이터프레임 작업을 더 쉽게 하려면, `drop()`으로, 여러 열을 지우고, 필요한 행만 둡니다.
```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)
```
### 두번째로, 호박의 평균 가격을 결정합니다.
주어진 달에 호박의 평균 가격을 결정하는 방식에 대하여 생각합니다. 이 작업을 하기 위하여 어떤 열을 선택할까요? 힌트: 3개의 열이 필요합니다.
솔루션: `Low Price`와 `High Price` 열의 평균으로 새로운 가격 열을 채우고, 이 달만 보여주기 위해 날짜 열을 변환합니다. 다행히, 확인해보니, 누락된 날짜나 가격 데이터가 없습니다.
1. 평균을 계산하려면, 해당 코드를 추가합니다:
```python
price = (pumpkins['Low Price'] + pumpkins['High Price']) / 2
month = pd.DatetimeIndex(pumpkins['Date']).month
```
✅ `print(month)`로 확인하려는 데이터를 마음껏 출력해보세요.
2. 이제, 새로 만든 Pandas 데이터프레임으로 변환한 데이터를 복사해보세요:
```python
new_pumpkins = pd.DataFrame({'Month': month, 'Package': pumpkins['Package'], 'Low Price': pumpkins['Low Price'],'High Price': pumpkins['High Price'], 'Price': price})
```
데이터프레임을 출력해보면 새로운 regression 모델을 만들 수 있는 깨끗하고, 단정한 데이터셋이 보여집니다.
### 하지만 기다려주세요! 여기 무언가 있습니다
`Package` 열을 보면, 호박이 많이 다양한 구성으로 팔린 것을 볼 수 있습니다. 일부는 '1 1/9 bushel' 단위로 팔고, '1/2 bushel' 단위로 팔고, 호박 단위, 파운드 단위, 그리고 다양한 넓이의 큰 박스에도 넣어서 팔고 있습니다.
> 호박은 일정한 무게로 이루어지기 꽤 어려운 것 같습니다.
원본 데이터를 파다보면, 모든 항목에 인치, 박스 당, 또는 'each'로 이루어져서 `Unit of Sale`이 'EACH' 또는 'PER BIN'이라는 사실은 흥미롭습니다. 호박은 일정하게 무게를 달기가 매우 어려워서, `Package` 열에 'bushel' 문자열이 있는 호박만 선택해서 필터링하겟습니다.
1. 파일 상단, 처음 .csv import 하단에 필터를 추가합니다:
```python
pumpkins = pumpkins[pumpkins['Package'].str.contains('bushel', case=True, regex=True)]
```
지금 데이터를 출력해보면, bushel 호박 포함한 대략 415개의 행만 가져올 수 있습니다.
### 하지만 기다려주세요! 하나 더 있습니다
bushel 수량이 행마다 다른 것을 알았나요? bushel 단위로 가격을 보여줄 수 있도록 가격을 노말라이즈해야 되므로, 수학으로 일반화해야 합니다.
1. 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)
```
✅ [The Spruce Eats](https://www.thespruceeats.com/how-much-is-a-bushel-1389308)에 따르면, bushel의 무게는 볼륨 측정이므로, 농산물 타입에 따릅니다. "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." 모든 게 정말 복잡합니다! bushel에서 파운드로 변환하면서 신경쓰지 말고, bushel로 가격을 정합니다. 호박 bushels의 모든 연구는, 데이터의 특성을 이해하는 게 매우 중요하다는 것을 보여줍니다.
지금, bushel 측정을 기반으로 가격을 분석하는 게 가능해졌습니다. 만약 한 번 데이터를 출력하면, 표준화된 상태로 볼 수 있습니다.
✅ half-bushel로 파는 게 매우 비싸다는 사실을 파악했나요? 왜 그런 지 알 수 있나요? 힌트: 작은 호박은 큰 호박보다 비쌉니다, 큰 hollow 파이 호박 하나가 차지하는 빈 공간을 생각해보면, bushel 당 더 많습니다.
## 시각화 전략
데이터 사이언티스트 룰의 일부는 작업하고 있는 데이터의 품질과 특성을 증명하는 것입니다. 데이터의 다양한 측면을 보여주는, 흥미로운 시각화, 또는 plots, 그래프 그리고 차트를 만드는 경우가 자주 있습니다. 이렇게, 다른 방식으로 밝히기 힘든 관계와 간격을 시각적으로 표현할 수 있습니다.
시각화는 데이터에 가장 적합한 머신러닝 기술의 결정을 돕습니다. 라인을 따라가는 것처럼 보이는 scatterplot을(산점도) 예시로, 데이터가 linear regression 연습에 좋은 후보군이라는 것을 나타냅니다.
Jupyter notebooks에서 잘 작동하는 데이터 시각화 라이브러리는 (이전 강의에서 보았던) [Matplotlib](https://matplotlib.org/)입니다.
> [these tutorials](https://docs.microsoft.com/learn/modules/explore-analyze-data-with-python?WT.mc_id=academic-15963-cxa)에서 데이터 시각화 연습을 더 해보세요.
## 연습 - Matplotlib으로 실험하기
직전에 만든 새로운 데이터프레임을 출력하려면 기초 plot을 만듭시다. 기초 라인 plot은 어떻게 보여주나요?
1. 파일의 상단에, Pandas import 밑에서 Matplotlib을 Import 합니다:
```python
import matplotlib.pyplot as plt
```
1. 전체 노트북을 다시 실행해서 새로 고칩니다.
1. 노트북의 하단에, 데이터를 박스로 plot할 셀을 추가합니다:
```python
price = new_pumpkins.Price
month = new_pumpkins.Month
plt.scatter(price, month)
plt.show()
```
![A scatterplot showing price to month relationship](.././images/scatterplot.png)
쓸모있는 plot인가요? 어떤 것에 놀랬나요?
주어진 달에 대하여 점의 발산은 데이터에 보여질 뿐이므로 특별히 유용하지 않습니다.
### 유용하게 만들기
차트에서 유용한 데이터를 보여지게 하려면, 데이터를 어떻게든지 그룹으로 묶어야 합니다. y축이 달을 나타내면서 데이터의 분포를 나타내는 데이터로 plot을 만들어 보겠습니다.
1. 그룹화된 바 차트를 만들기 위한 셀을 추가합니다:
```python
new_pumpkins.groupby(['Month'])['Price'].mean().plot(kind='bar')
plt.ylabel("Pumpkin Price")
```
![A bar chart showing price to month relationship](.././images/barchart.png)
조금 더 유용한 데이터 시각화힙니다! 호박 가격이 가장 높았을 때는 9월과 10월로 보여집니다. 기대하던 목표에 부합하나요? 왜 그렇게 생각하나요?
---
## 🚀 도전
Matplotlib에서 제공하는 다양한 시각화 타입을 찾아보세요. regression 문제에 가장 적당한 타입은 무엇인가요?
## [강의 후 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/12/)
## 검토 & 자기주도 학습
데이터 시각화하는 많은 방식을 찾아보세요. 사용할 수 있는 다양한 라이브러리 목록을 만들고 2D visualizations vs. 3D visualizations 예시처럼, 주어진 작업의 타입에 적당한 라이브러리를 확인합니다. 어떤 것을 찾았나요?
## 과제
[Exploring visualization](../assignment.md)

@ -1,55 +1,56 @@
# 使用Scikit-learn构建回归模型:准备和可视化数据
# 使用 Scikit-learn 构建回归模型:准备和可视化数据
> ![数据可视化信息图](../images/data-visualization.png)
> 作者[Dasani Madipalli](https://twitter.com/dasani_decoded)
![数据可视化信息图](../images/data-visualization.png)
> 作者 [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [课前测](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/11/)
## [课前测](https://white-water-09ec41f0f.azurestaticapps.net/quiz/11/)
## 介绍
既然你已经设置了开始使用Scikit-learn处理机器学习模型构建所需的工具,你就可以开始对数据提出问题了。当你处理数据并应用ML解决方案时,了解如何提出正确的问题以正确释放数据集的潜力非常重要。
既然你已经设置了开始使用 Scikit-learn 处理机器学习模型构建所需的工具,你就可以开始对数据提出问题了。当你处理数据并应用ML解决方案时,了解如何提出正确的问题以正确释放数据集的潜力非常重要。
在本课中,你将学习:
- 如何为模型构建准备数据。
- 如何使用Matplotlib进行数据可视化。
- 如何使用 Matplotlib 进行数据可视化。
## 对你的数据提出正确的问题
## 对你的数据提出正确的问题
你需要回答的问题将决定你将使用哪种类型的ML算法。你得到的答案的质量将在很大程度上取决于你的数据的性质。
你提出的问题将决定你将使用哪种类型的 ML 算法。你得到的答案的质量将在很大程度上取决于你的数据的性质。
查看为本课程提供的[数据](../data/US-pumpkins.csv)。你可以在VS Code中打开这个.csv文件。快速浏览一下就会发现有空格,还有字符串和数字数据的混合。还有一个奇怪的列叫做“Package”,其中的数据是“sacks”、“bins”和其他值的混合。事实上,数据有点乱。
查看为本课程提供的[数据](../data/US-pumpkins.csv)。你可以在 VS Code 中打开这个 .csv 文件。快速浏览一下就会发现有空格,还有字符串和数字数据的混合。还有一个奇怪的列叫做“Package”,其中的数据是“sacks”、“bins”和其他值的混合。事实上,数据有点乱。
事实上,获得一个完全准备好用于创建开箱即用的ML模型的数据集并不是很常见。在本课中,你将学习如何使用标准Python库准备原始数据集。你还将学习各种技术来可视化数据。
事实上,得到一个完全准备好用于创建 ML 模型的开箱即用数据集并不是很常见。在本课中,你将学习如何使用标准 Python 库准备原始数据集。你还将学习各种技术来可视化数据。
## 案例研究:“南瓜市场”
你将在`data`文件夹中找到一个名为[US-pumpkins.csv](../data/US-pumpkins.csv)的.csv 文件,其中包含有关南瓜市场的1757行数据,已 按城市排序分组。这是从美国农业部分发的[特种作物终端市场标准报告](https://www.marketnews.usda.gov/mnp/fv-report-config-step1?type=termPrice)中提取的原始数据。
你将在 `data` 文件夹中找到一个名为 [US-pumpkins.csv](../data/US-pumpkins.csv) 的 .csv 文件,其中包含有关南瓜市场的 1757 行数据,已按城市排序分组。这是从美国农业部分发的[特种作物终端市场标准报告](https://www.marketnews.usda.gov/mnp/fv-report-config-step1?type=termPrice)中提取的原始数据。
### 准备数据
这些数据属于公共领域。它可以从美国农业部网站下载,每个城市有许多不同的文件。为了避免太多单独的文件,我们将所有城市数据合并到一个电子表格中,因此我们已经准备了一些数据。接下来,让我们仔细看看数据。
### 南瓜数据 - 早期结论
### 南瓜数据 - 早期结论
你对这些数据有什么看法?你已经看到了无法理解的字符串、数字、空格和奇怪值的混合体。
你可以使用回归技术对这些数据提出什么问题?“预测给定月份内待售南瓜的价格”怎么样?再次查看数据,你需要进行一些更改才能创建任务所需的数据结构。
## 练习 - 分析南瓜数据
你可以使用回归技术对这些数据提出什么问题?“预测给定月份内待售南瓜的价格”怎么样?再次查看数据,你需要进行一些更改才能创建任务所需的数据结构。
让我们使用[Pandas](https://pandas.pydata.org/),(“Python 数据分析”的意思)一个非常有用的工具,用于分析和准备南瓜数据。
## 练习 - 分析南瓜数据
让我们使用 [Pandas](https://pandas.pydata.org/),(“Python 数据分析” Python Data Analysis 的意思)一个非常有用的工具,用于分析和准备南瓜数据。
### 首先,检查遗漏的日期
你首先需要采取以下步骤来检查缺少的日期:
1. 将日期转换为月份格式(这些是美国日期,因此格式为`MM/DD/YYYY`)。
1. 将日期转换为月份格式(这些是美国日期,因此格式为 `MM/DD/YYYY`)。
2. 将月份提取到新列。
在 Visual Studio Code 中打开notebook.ipynb文件,并将电子表格导入到新的Pandas dataframe中。
在 Visual Studio Code 中打开 notebook.ipynb 文件,并将电子表格导入到新的 Pandas dataframe 中。
1. 使用 `head()`函数查看前五行。
1. 使用 `head()` 函数查看前五行。
```python
import pandas as pd
@ -57,9 +58,9 @@
pumpkins.head()
```
✅ 使用什么函数来查看最后五行?
✅ 使用什么函数来查看最后五行?
2. 检查当前dataframe中是否缺少数据:
2. 检查当前 dataframe 中是否缺少数据:
```python
pumpkins.isnull().sum()
@ -67,20 +68,20 @@
有数据丢失,但可能对手头的任务来说无关紧要。
3. 为了让你的dataframe更容易使用,使用`drop()`删除它的几个列,只保留你需要的列:
3. 为了让你的 dataframe 更容易使用,使用 `drop()` 删除它的几个列,只保留你需要的列:
```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)
```
### 然后,确定南瓜的平均价格
### 然后,确定南瓜的平均价格
考虑如何确定给定月份南瓜的平均价格。你会为此任务选择哪些列?提示:你需要3列。
考虑如何确定给定月份南瓜的平均价格。你会为此任务选择哪些列?提示:你需要 3 列。
解决方案:取`Low Price`和`High Price`列的平均值来填充新的Price列,将Date列转换成只显示月份。幸运的是,根据上面的检查,没有丢失日期或价格的数据。
解决方案:取 `Low Price` 和 `High Price` 列的平均值来填充新的 Price 列,将 Date 列转换成只显示月份。幸运的是,根据上面的检查,没有丢失日期或价格的数据。
1. 要计算平均值,请添加以下代码:
1. 要计算平均值,请添加以下代码:
```python
price = (pumpkins['Low Price'] + pumpkins['High Price']) / 2
@ -89,37 +90,37 @@
```
✅ 请随意使用`print(month)`打印你想检查的任何数据。
✅ 请随意使用 `print(month)` 打印你想检查的任何数据。
2. 现在,将转换后的数据复制到新的Pandas dataframe中:
2. 现在,将转换后的数据复制到新的 Pandas dataframe 中:
```python
new_pumpkins = pd.DataFrame({'Month': month, 'Package': pumpkins['Package'], 'Low Price': pumpkins['Low Price'],'High Price': pumpkins['High Price'], 'Price': price})
```
打印出的dataframe将向你展示一个干净整洁的数据集,你可以在此数据集上构建新的回归模型。
打印出的 dataframe 将向你展示一个干净整洁的数据集,你可以在此数据集上构建新的回归模型。
### 但是等等!这里有点奇怪
如果你看看`Package`(包装)一栏,南瓜有很多不同的配置。有的以1 1/9蒲式耳的尺寸出售,有的以1/2蒲式耳的尺寸出售,有的以每只南瓜出售,有的以每磅出售,有的以不同宽度的大盒子出售。
如果你看看 `Package`(包装)一栏,南瓜有很多不同的配置。有的以 1 1/9 蒲式耳的尺寸出售,有的以 1/2 蒲式耳的尺寸出售,有的以每只南瓜出售,有的以每磅出售,有的以不同宽度的大盒子出售。
> 南瓜似乎很难统一称重方式
深入研究原始数据,有趣的是,任何`Unit of Sale`等于“EACH”或“PER BIN”的东西也具有每英寸、每箱或“每个”的`Package`类型。南瓜似乎很难采用统一称重方式,因此让我们通过仅选择`Package`列中带有字符串“蒲式耳”的南瓜来过滤它们。
深入研究原始数据,有趣的是,任何 `Unit of Sale` 等于“EACH”或“PER BIN”的东西也具有每英寸、每箱或“每个”的 `Package` 类型。南瓜似乎很难采用统一称重方式,因此让我们通过仅选择 `Package` 列中带有字符串“蒲式耳”的南瓜来过滤它们。
1. 在初始.csv导入下添加过滤器:
1. 在初始 .csv 导入下添加过滤器:
```python
pumpkins = pumpkins[pumpkins['Package'].str.contains('bushel', case=True, regex=True)]
```
如果你现在打印数据,你可以看到你只获得了 415 行左右包含按蒲式耳计算的南瓜的数据。
如果你现在打印数据,你可以看到你只获得了 415 行左右包含按蒲式耳计算的南瓜的数据。
### 可是等等! 还有一件事要做
### 可是等等! 还有一件事要做
你是否注意到每行的蒲式耳数量不同?你需要对定价进行标准化,以便显示每蒲式耳的定价,因此请进行一些数学计算以对其进行标准化。
你是否注意到每行的蒲式耳数量不同?你需要对定价进行标准化,以便显示每蒲式耳的定价,因此请进行一些数学计算以对其进行标准化。
1. 在创建 new_pumpkins dataframe的代码块之后添加这些行:
1. 在创建 new_pumpkins dataframe 的代码块之后添加这些行:
```python
new_pumpkins.loc[new_pumpkins['Package'].str.contains('1 1/9'), 'Price'] = price/(1 + 1/9)
@ -129,33 +130,33 @@
✅ 根据 [The Spruce Eats](https://www.thespruceeats.com/how-much-is-a-bushel-1389308),蒲式耳的重量取决于产品的类型,因为它是一种体积测量。“例如,一蒲式耳西红柿应该重56 磅……叶子和蔬菜占据更多空间,重量更轻,所以一蒲式耳菠菜只有20磅。” 这一切都相当复杂!让我们不要费心进行蒲式耳到磅的转换,而是按蒲式耳定价。然而,所有这些对蒲式耳南瓜的研究表明,了解数据的性质是多么重要!
现在,你可以根据蒲式耳测量来分析每单位的定价。如果你再打印一次数据,你可以看到它是如何标准化的。
现在,你可以根据蒲式耳测量来分析每单位的定价。如果你再打印一次数据,你可以看到它是如何标准化的。
✅ 你有没有注意到半蒲式耳卖的南瓜很贵?你能弄清楚为什么吗?提示:小南瓜比大南瓜贵得多,这可能是因为考虑到一个大的空心馅饼南瓜占用的未使用空间,每蒲式耳的南瓜要多得多。
✅ 你有没有注意到半蒲式耳卖的南瓜很贵?你能弄清楚为什么吗?提示:小南瓜比大南瓜贵得多,这可能是因为考虑到一个大的空心馅饼南瓜占用的未使用空间,每蒲式耳的南瓜要多得多。
## 可视化策略
## 可视化策略
数据科学家的部分职责是展示他们使用的数据的质量和性质。为此,他们通常会创建有趣的可视化或绘图、图形和图表,以显示数据的不同方面。通过这种方式,他们能够直观地展示难以发现的关系和差距。
数据科学家的部分职责是展示他们使用的数据的质量和性质。为此,他们通常会创建有趣的可视化或绘图、图形和图表,以显示数据的不同方面。通过这种方式,他们能够直观地展示难以发现的关系和差距。
可视化还可以帮助确定最适合数据的机器学习技术。例如,似乎沿着一条线的散点图表明该数据是线性回归练习的良好候选者。
一个在Jupyter notebooks中运行良好的数据可视化库是[Matplotlib](https://matplotlib.org/)(你在上一课中也看到过)。
一个在 Jupyter notebooks 中运行良好的数据可视化库是 [Matplotlib](https://matplotlib.org/)(你在上一课中也看到过)。
> 在[这些教程](https://docs.microsoft.com/learn/modules/explore-analyze-data-with-python?WT.mc_id=academic-15963-cxa)中获得更多数据可视化经验。
> 在[这些教程](https://docs.microsoft.com/learn/modules/explore-analyze-data-with-python?WT.mc_id=academic-15963-cxa)中获得更多数据可视化经验。
## 练习 - 使用 Matplotlib 进行实验
## 练习 - 使用 Matplotlib 进行实验
尝试创建一些基本图形来显示你刚刚创建的新dataframe。基本线图会显示什么?
尝试创建一些基本图形来显示你刚刚创建的新 dataframe。基本线图会显示什么?
1. 在文件顶部导入Matplotlib:
1. 在文件顶部导入 Matplotlib:
```python
import matplotlib.pyplot as plt
```
2. 重新刷新以运行整个notebook。
2. 重新刷新以运行整个 notebook。
3. 在notebook底部,添加一个单元格以绘制数据:
3. 在 notebook 底部,添加一个单元格以绘制数据:
```python
price = new_pumpkins.Price
@ -170,33 +171,33 @@
它并不是特别有用,因为它所做的只是在你的数据中显示为给定月份的点数分布。
### 让它有用
### 让它有用
为了让图表显示有用的数据,你通常需要以某种方式对数据进行分组。让我们尝试创建一个图,其中y轴显示月份,数据显示数据的分布。
为了让图表显示有用的数据,你通常需要以某种方式对数据进行分组。让我们尝试创建一个图,其中 y 轴显示月份,数据显示数据的分布。
1. 添加单元格以创建分组条形图:
1. 添加单元格以创建分组柱状图:
```python
new_pumpkins.groupby(['Month'])['Price'].mean().plot(kind='bar')
plt.ylabel("Pumpkin Price")
```
![显示价格与月份关系的条形图](../images/barchart.png)
![显示价格与月份关系的柱状图](../images/barchart.png)
这是一个更有用的数据可视化!似乎表明南瓜的最高价格出现在9月和10月。这符合你的期望吗?为什么?为什么不?
这是一个更有用的数据可视化!似乎表明南瓜的最高价格出现在 9 月和 10 月。这符合你的期望吗?为什么?为什么不?
---
## 🚀挑战
探索Matplotlib提供的不同类型的可视化。哪种类型最适合回归问题?
探索 Matplotlib 提供的不同类型的可视化。哪种类型最适合回归问题?
## [课后测](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/12/)
## [课后测](https://white-water-09ec41f0f.azurestaticapps.net/quiz/12/)
## 复习与自学
请看一下可视化数据的多种方法。列出各种可用的库,并注意哪些库最适合给定类型的任务,例如2D可视化与3D可视化。你发现了什么?
请看一下可视化数据的多种方法。列出各种可用的库,并注意哪些库最适合给定类型的任务,例如 2D 可视化与 3D 可视化。你发现了什么?
## 任务
[探索可视化](../assignment.md)
[探索可视化](./assignment.zh-cn.md)

@ -0,0 +1,9 @@
# Explorando visualizaciones
Hay varias librerías diferentes que están disponibles para la visualización de los datos. Cree algunas visualizaciones utilizando los datos de 'Pumpkin' en esta lección con _matplotlib_ y _seaborn_ en un cuaderno de muestra.¿Con qué bibliotecas es más fácil trabajar?
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | --------- | -------- | ----------------- |
| | Se envía un cuaderno con dos exploraciones/visualizaciones | Se envía un cuadernos con una exploración/visualización | No se envía un cuaderno |

@ -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 @@
# ビジュアライゼーションの探求
データのビジュアライゼーションには、いくつかの異なるライブラリがあります。このレッスンのPumpkinデータを使って、matplotlibとseabornを使って、サンプルノートブックでいくつかのビジュアライゼーションを作ってみましょう。どのライブラリが作業しやすいでしょうか?
## ルーブリック
| 指標 | 模範的 | 適切 | 要改善 |
| -------- | --------- | -------- | ----------------- |
| | ノートブックには2つの活用法/可視化方法が示されている。 | ノートブックには1つの活用法/可視化方法が示されている。 | ノートブックが提出されていない。 |

@ -0,0 +1,9 @@
# 探索数据可视化
有好几个库都可以进行数据可视化。用 matplotlib 和 seaborn 对本课中涉及的 Pumpkin 数据集创建一些数据可视化的图标。并思考哪个库更容易使用?
## 评判标准
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
| -------- | --------- | -------- | ----------------- |
| | 提交了含有两种探索可视化方法的 notebook 工程文件 | 提交了只包含有一种探索可视化方法的 notebook 工程文件 | 没提交 notebook 工程文件 |

@ -2,7 +2,9 @@
![Linear vs polynomial regression infographic](./images/linear-polynomial.png)
> Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/13/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/13/)
> ### [This lesson is available in R!](./solution/R/lesson_3-R.ipynb)
### 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 Matplotlib.
@ -320,7 +322,7 @@ It does make sense, given the plot! And, if this is a better model than the prev
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/)
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/14/)
## Review & Self Study

Binary file not shown.

After

Width:  |  Height:  |  Size: 873 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 MiB

@ -0,0 +1 @@
This is a temporary placeholder

File diff suppressed because it is too large Load Diff

@ -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
![Infographic by Dasani Madipalli](../../images/linear-polynomial.png){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`.
>
> ![Infographic by Jen Looper](../../images/slope.png){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.
>
> ![Infographic by Jen Looper](../../images/calculation.png)
>
> 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**
![Artwork by \@allison_horst](../../images/janitor.jpg){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!
![Artwork by \@allison_horst](../images/recipes.png){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
![Infographic by Dasani Madipalli](../../images/linear-polynomial.png){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
![Infographic by Dasani Madipalli](../../images/linear-polynomial.png){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://white-water-09ec41f0f.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).

@ -2,7 +2,7 @@
![Infografik regresi linear vs polinomial](../images/linear-polynomial.png)
> Infografik oleh [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [Kuis pra-ceramah](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/13/)
## [Kuis pra-ceramah](https://white-water-09ec41f0f.azurestaticapps.net/quiz/13/)
### Pembukaan
Selama ini kamu telah menjelajahi apa regresi itu dengan data contoh yang dikumpulkan dari *dataset* harga labu yang kita akan gunakan terus sepanjang pelajaran ini. Kamu juga telah memvisualisasikannya dengan Matplotlib.
@ -324,7 +324,7 @@ Itu sangat masuk akal dengan bagan sebelumnya! Selain itu, jika ini model lebih
Coba-cobalah variabel-variabel yang lain di *notebook* ini untuk melihat bagaimana korelasi berhubungan dengan akurasi model.
## [Kuis pasca-ceramah](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/14/)
## [Kuis pasca-ceramah](https://white-water-09ec41f0f.azurestaticapps.net/quiz/14/)
## Review & Pembelajaran Mandiri

@ -0,0 +1,339 @@
# Costruire un modello di regressione usando Scikit-learn: regressione in due modi
![Infografica di regressione lineare e polinomiale](../images/linear-polynomial.png)
> Infografica di [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [Quiz pre-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/13/?loc=it)
### Introduzione
Finora si è esplorato cos'è la regressione con dati di esempio raccolti dall'insieme di dati relativo ai prezzi della zucca, che verrà usato in questa lezione. Lo si è anche visualizzato usando Matplotlib.
Ora si è pronti per approfondire la regressione per machine learning. In questa lezione si imparerà di più su due tipi di regressione: _regressione lineare di base_ e _regressione polinomiale_, insieme ad alcuni dei calcoli alla base di queste tecniche.
> In questo programma di studi, si assume una conoscenza minima della matematica, e si cerca di renderla accessibile agli studenti provenienti da altri campi, quindi si faccia attenzione a note, 🧮 didascalie, diagrammi e altri strumenti di apprendimento che aiutano la comprensione.
### Prerequisito
Si dovrebbe ormai avere familiarità con la struttura dei dati della zucca che si sta esaminando. Lo si può trovare precaricato e prepulito nel file _notebook.ipynb_ di questa lezione. Nel file, il prezzo della zucca viene visualizzato per bushel (staio) in un nuovo dataframe. Assicurasi di poter eseguire questi notebook nei kernel in Visual Studio Code.
### Preparazione
Come promemoria, si stanno caricando questi dati in modo da porre domande su di essi.
- Qual è il momento migliore per comprare le zucche?
- Che prezzo ci si può aspettare da una cassa di zucche in miniatura?
- Si devono acquistare in cestini da mezzo bushel o a scatola da 1 1/9 bushel? Si continua a scavare in questi dati.
Nella lezione precedente, è stato creato un dataframe Pandas e si è popolato con parte dell'insieme di dati originale, standardizzando il prezzo per lo bushel. In questo modo, tuttavia, si sono potuti raccogliere solo circa 400 punti dati e solo per i mesi autunnali.
Si dia un'occhiata ai dati precaricati nel notebook di accompagnamento di questa lezione. I dati sono precaricati e viene tracciato un grafico a dispersione iniziale per mostrare i dati mensili. Forse si può ottenere qualche dettaglio in più sulla natura dei dati pulendoli ulteriormente.
## Una linea di regressione lineare
Come si è appreso nella lezione 1, l'obiettivo di un esercizio di regressione lineare è essere in grado di tracciare una linea per:
- **Mostrare le relazioni tra variabili**.
- **Fare previsioni**. Fare previsioni accurate su dove cadrebbe un nuovo punto dati in relazione a quella linea.
È tipico della **Regressione dei Minimi Quadrati** disegnare questo tipo di linea. Il termine "minimi quadrati" significa che tutti i punti dati che circondano la linea di regressione sono elevati al quadrato e quindi sommati. Idealmente, quella somma finale è la più piccola possibile, perché si vuole un basso numero di errori, o `minimi quadrati`.
Lo si fa perché si vuole modellare una linea che abbia la distanza cumulativa minima da tutti i punti dati. Si esegue anche il quadrato dei termini prima di aggiungerli poiché interessa la grandezza piuttosto che la direzione.
> **🧮 Mostrami la matematica**
>
> Questa linea, chiamata _linea di miglior adattamento_ , può essere espressa da [un'equazione](https://en.wikipedia.org/wiki/Simple_linear_regression):
>
> ```
> Y = a + bX
> ```
>
> `X` è la "variabile esplicativa". `Y` è la "variabile dipendente". La pendenza della linea è `b` e `a` è l'intercetta di y, che si riferisce al valore di `Y` quando `X = 0`.
>
> ![calcolare la pendenza](../images/slope.png)
>
> Prima, calcolare la pendenza `b`. Infografica di [Jen Looper](https://twitter.com/jenlooper)
>
> In altre parole, facendo riferimento alla domanda originale per i dati sulle zucche: "prevedere il prezzo di una zucca per bushel per mese", `X` si riferisce al prezzo e `Y` si riferirisce al mese di vendita.
>
> ![completare l'equazione](../images/calculation.png)
>
> Si calcola il valore di Y. Se si sta pagando circa $4, deve essere aprile! Infografica di [Jen Looper](https://twitter.com/jenlooper)
>
> La matematica che calcola la linea deve dimostrare la pendenza della linea, che dipende anche dall'intercetta, o dove `Y` si trova quando `X = 0`.
>
> Si può osservare il metodo di calcolo per questi valori sul sito web [Math is Fun](https://www.mathsisfun.com/data/least-squares-regression.html) . Si visiti anche [questo calcolatore dei minimi quadrati](https://www.mathsisfun.com/data/least-squares-calculator.html) per vedere come i valori dei numeri influiscono sulla linea.
## Correlazione
Un altro termine da comprendere è il **Coefficiente di Correlazione** tra determinate variabili X e Y. Utilizzando un grafico a dispersione, è possibile visualizzare rapidamente questo coefficiente. Un grafico con punti dati sparsi in una linea ordinata ha un'alta correlazione, ma un grafico con punti dati sparsi ovunque tra X e Y ha una bassa correlazione.
Un buon modello di regressione lineare sarà quello che ha un Coefficiente di Correlazione alto (più vicino a 1 rispetto a 0) utilizzando il Metodo di Regressione dei Minimi Quadrati con una linea di regressione.
✅ Eseguire il notebook che accompagna questa lezione e guardare il grafico a dispersione City to Price. I dati che associano la città al prezzo per le vendite di zucca sembrano avere una correlazione alta o bassa, secondo la propria interpretazione visiva del grafico a dispersione?
## Preparare i dati per la regressione
Ora che si ha una comprensione della matematica alla base di questo esercizio, si crea un modello di regressione per vedere se si può prevedere quale pacchetto di zucche avrà i migliori prezzi per zucca. Qualcuno che acquista zucche per una festa con tema un campo di zucche potrebbe desiderare che queste informazioni siano in grado di ottimizzare i propri acquisti di pacchetti di zucca per il campo.
Dal momento che si utilizzerà Scikit-learn, non c'è motivo di farlo a mano (anche se si potrebbe!). Nel blocco di elaborazione dati principale del notebook della lezione, aggiungere una libreria da Scikit-learn per convertire automaticamente tutti i dati di tipo stringa in numeri:
```python
from sklearn.preprocessing import LabelEncoder
new_pumpkins.iloc[:, 0:-1] = new_pumpkins.iloc[:, 0:-1].apply(LabelEncoder().fit_transform)
```
Se si guarda ora il dataframe new_pumpkins, si vede che tutte le stringhe ora sono numeriche. Questo rende più difficile la lettura per un umano ma molto più comprensibile per Scikit-learn!
Ora si possono prendere decisioni più consapevoli (non solo basate sull'osservazione di un grafico a dispersione) sui dati più adatti alla regressione.
Si provi a trovare una buona correlazione tra due punti nei propri dati per costruire potenzialmente un buon modello predittivo. A quanto pare, c'è solo una debole correlazione tra la città e il prezzo:
```python
print(new_pumpkins['City'].corr(new_pumpkins['Price']))
0.32363971816089226
```
Tuttavia, c'è una correlazione leggermente migliore tra il pacchetto e il suo prezzo. Ha senso, vero? Normalmente, più grande è la scatola dei prodotti, maggiore è il prezzo.
```python
print(new_pumpkins['Package'].corr(new_pumpkins['Price']))
0.6061712937226021
```
Una buona domanda da porre a questi dati sarà: "Che prezzo posso aspettarmi da un determinato pacchetto di zucca?"
Si costruisce questo modello di regressione
## Costruire un modello lineare
Prima di costruire il modello, si esegue un altro riordino dei dati. Si eliminano tutti i dati nulli e si controlla ancora una volta che aspetto hanno i dati.
```python
new_pumpkins.dropna(inplace=True)
new_pumpkins.info()
```
Quindi, si crea un nuovo dataframe da questo set minimo e lo si stampa:
```python
new_columns = ['Package', 'Price']
lin_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
lin_pumpkins
```
```output
Package Price
70 0 13.636364
71 0 16.363636
72 0 16.363636
73 0 15.454545
74 0 13.636364
... ... ...
1738 2 30.000000
1739 2 28.750000
1740 2 25.750000
1741 2 24.000000
1742 2 24.000000
415 rows × 2 columns
```
1. Ora si possono assegnare i dati delle coordinate X e y:
```python
X = lin_pumpkins.values[:, :1]
y = lin_pumpkins.values[:, 1:2]
```
Cosa sta succedendo qui? Si sta usando [la notazione slice Python](https://stackoverflow.com/questions/509211/understanding-slice-notation/509295#509295) per creare array per popolare `X` e `y`.
2. Successivamente, si avvia le routine di creazione del modello di regressione:
```python
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
lin_reg = LinearRegression()
lin_reg.fit(X_train,y_train)
pred = lin_reg.predict(X_test)
accuracy_score = lin_reg.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
Poiché la correlazione non è particolarmente buona, il modello prodotto non è molto accurato.
```output
Model Accuracy: 0.3315342327998987
```
3. Si può visualizzare la linea tracciata nel processo:
```python
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, pred, color='blue', linewidth=3)
plt.xlabel('Package')
plt.ylabel('Price')
plt.show()
```
![Un grafico a dispersione che mostra il rapporto tra pacchetto e prezzo](../images/linear.png)
4. Si testa il modello contro una varietà ipotetica:
```python
lin_reg.predict( np.array([ [2.75] ]) )
```
Il prezzo restituito per questa varietà mitologica è:
```output
array([[33.15655975]])
```
Quel numero ha senso, se la logica della linea di regressione è vera.
🎃 Congratulazioni, si è appena creato un modello che può aiutare a prevedere il prezzo di alcune varietà di zucche. La zucca per le festività sarà bellissima. Ma probabilmente si può creare un modello migliore!
## Regressione polinomiale
Un altro tipo di regressione lineare è la regressione polinomiale. Mentre a volte c'è una relazione lineare tra le variabili - più grande è il volume della zucca, più alto è il prezzo - a volte queste relazioni non possono essere tracciate come un piano o una linea retta.
✅ Ecco [alcuni altri esempi](https://online.stat.psu.edu/stat501/lesson/9/9.8) di dati che potrebbero utilizzare la regressione polinomiale
Si dia un'altra occhiata alla relazione tra Varietà e Prezzo nel tracciato precedente. Questo grafico a dispersione deve essere necessariamente analizzato da una linea retta? Forse no. In questo caso, si può provare la regressione polinomiale.
✅ I polinomi sono espressioni matematiche che possono essere costituite da una o più variabili e coefficienti
La regressione polinomiale crea una linea curva per adattare meglio i dati non lineari.
1. Viene ricreato un dataframe popolato con un segmento dei dati della zucca originale:
```python
new_columns = ['Variety', 'Package', 'City', 'Month', 'Price']
poly_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
poly_pumpkins
```
Un buon modo per visualizzare le correlazioni tra i dati nei dataframe è visualizzarli in un grafico "coolwarm":
2. Si usa il metodo `Background_gradient()` con `coolwarm` come valore dell'argomento:
```python
corr = poly_pumpkins.corr()
corr.style.background_gradient(cmap='coolwarm')
```
Questo codice crea una mappa di calore:
![Una mappa di calore che mostra la correlazione dei dati](../images/heatmap.png)
Guardando questo grafico, si può visualizzare la buona correlazione tra Pacchetto e Prezzo. Quindi si dovrebbe essere in grado di creare un modello un po' migliore dell'ultimo.
### Creare una pipeline
Scikit-learn include un'API utile per la creazione di modelli di regressione polinomiale: l'[API](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html?highlight=pipeline#sklearn.pipeline.make_pipeline) `make_pipeline`. Viene creata una 'pipeline' che è una catena di stimatori. In questo caso, la pipeline include caratteristiche polinomiali o previsioni che formano un percorso non lineare.
1. Si costruiscono le colonne X e y:
```python
X=poly_pumpkins.iloc[:,3:4].values
y=poly_pumpkins.iloc[:,4:5].values
```
2. Si crea la pipeline chiamando il metodo `make_pipeline()` :
```python
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(PolynomialFeatures(4), LinearRegression())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
pipeline.fit(np.array(X_train), y_train)
y_pred=pipeline.predict(X_test)
```
### Creare una sequenza
A questo punto, è necessario creare un nuovo dataframe con dati _ordinati_ in modo che la pipeline possa creare una sequenza.
Si aggiunge il seguente codice:
```python
df = pd.DataFrame({'x': X_test[:,0], 'y': y_pred[:,0]})
df.sort_values(by='x',inplace = True)
points = pd.DataFrame(df).to_numpy()
plt.plot(points[:, 0], points[:, 1],color="blue", linewidth=3)
plt.xlabel('Package')
plt.ylabel('Price')
plt.scatter(X,y, color="black")
plt.show()
```
Si è creato un nuovo dataframe chiamato `pd.DataFrame`. Quindi si sono ordinati i valori chiamando `sort_values()`. Alla fine si è creato un grafico polinomiale:
![Un grafico polinomiale che mostra la relazione tra pacchetto e prezzo](../images/polynomial.png)
Si può vedere una linea curva che si adatta meglio ai dati.
Si verifica la precisione del modello:
```python
accuracy_score = pipeline.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
E voilà!
```output
Model Accuracy: 0.8537946517073784
```
Ecco, meglio! Si prova a prevedere un prezzo:
### Fare una previsione
E possibile inserire un nuovo valore e ottenere una previsione?
Si chiami `predict()` per fare una previsione:
```python
pipeline.predict( np.array([ [2.75] ]) )
```
Viene data questa previsione:
```output
array([[46.34509342]])
```
Ha senso, visto il tracciato! Se questo è un modello migliore del precedente, guardando gli stessi dati, si deve preventivare queste zucche più costose!
Ben fatto! Sono stati creati due modelli di regressione in una lezione. Nella sezione finale sulla regressione, si imparerà a conoscere la regressione logistica per determinare le categorie.
---
## 🚀 Sfida
Testare diverse variabili in questo notebook per vedere come la correlazione corrisponde all'accuratezza del modello.
## [Quiz post-lezione](https://white-water-09ec41f0f.azurestaticapps.net/quiz/14/?loc=it)
## Revisione e Auto Apprendimento
In questa lezione si è appreso della regressione lineare. Esistono altri tipi importanti di regressione. Leggere le tecniche Stepwise, Ridge, Lazo ed Elasticnet. Un buon corso per studiare per saperne di più è il [corso Stanford Statistical Learning](https://online.stanford.edu/courses/sohs-ystatslearning-statistical-learning)
## Compito
[Costruire un modello](assignment.it.md)

@ -0,0 +1,334 @@
# Scikit-learnを用いた回帰モデルの構築: 回帰を行う2つの方法
![線形回帰 vs 多項式回帰 のインフォグラフィック](../images/linear-polynomial.png)
> [Dasani Madipalli](https://twitter.com/dasani_decoded) によるインフォグラフィック
## [講義前のクイズ](https://white-water-09ec41f0f.azurestaticapps.net/quiz/13/)
### イントロダクション
これまで、このレッスンで使用するカボチャの価格データセットから集めたサンプルデータを使って、回帰とは何かを探ってきました。また、Matplotlibを使って可視化を行いました。
これで、MLにおける回帰をより深く理解する準備が整いました。このレッスンでは、2種類の回帰について詳しく説明します。基本的な線形回帰 (_basic linear regression_)と多項式回帰 (_polynomial regression_)の2種類の回帰について、その基礎となる数学を学びます。
> このカリキュラムでは、最低限の数学の知識を前提とし、他の分野の学生にも理解できるようにしていますので、理解を助けるためのメモ、🧮吹き出し、図などの学習ツールをご覧ください。
### 事前確認
ここでは、パンプキンデータの構造について説明しています。このレッスンの_notebook.ipynb_ファイルには、事前に読み込まれ、整形されたデータが入っています。このファイルでは、カボチャの価格がブッシェル単位で新しいデータフレームに表示されています。 これらのノートブックを、Visual Studio Codeのカーネルで実行できることを確認してください。
### 準備
忘れてはならないのは、データを読み込んだら問いかけを行うことです。
- カボチャを買うのに最適な時期はいつですか?
- ミニカボチャ1ケースの価格はどのくらいでしょうか?
- 半ブッシェルのバスケットで買うべきか、1 1/9ブッシェルの箱で買うべきか。
データを掘り下げていきましょう。
前回のレッスンでは、Pandasのデータフレームを作成し、元のデータセットの一部を入力して、ブッシェル単位の価格を標準化しました。しかし、この方法では、約400のデータポイントしか集めることができず、しかもそれは秋の期間のものでした。
このレッスンに付属するノートブックで、あらかじめ読み込んでおいたデータを見てみましょう。データが事前に読み込まれ、月毎のデータが散布図として表示されています。データをもっと綺麗にすることで、データの性質をもう少し知ることができるかもしれません。
## 線形回帰
レッスン1で学んだように、線形回帰の演習では、以下のような線を描けるようになることが目標です。
- **変数間の関係を示す。**
- **予測を行う。** 新しいデータポイントが、その線のどこに位置するかを正確に予測することができる。
このような線を描くことは、**最小二乗回帰 (Least-Squares Regression)** の典型的な例です。「最小二乗」という言葉は、回帰線を囲むすべてのデータポイントとの距離が二乗され、その後加算されることを意味しています。理想的には、最終的な合計ができるだけ小さくなるようにします。これはエラーの数、つまり「最小二乗」の値を小さくするためです。
これは、すべてのデータポイントからの累積距離が最小となる直線をモデル化したいためです。また、方向ではなく大きさに注目しているので、足す前に項を二乗します。
> **🧮 Show me the math**
>
> この線は、_line of best fit_ と呼ばれ、[方程式](https://en.wikipedia.org/wiki/Simple_linear_regression) で表すことができます。
>
> ```
> Y = a + bX
> ```
>
> `X`は「説明変数」です。`Y`は「目的変数」です。`a`は切片で`b`は直線の傾きを表します。`X=0`のとき、`Y`の値は切片`a`となります。
>
>![傾きの計算](../images/slope.png)
>
> はじめに、傾き`b`を計算してみます。[Jen Looper](https://twitter.com/jenlooper) によるインフォグラフィック。
>
> カボチャのデータに関する最初の質問である、「月毎のブッシェル単位でのカボチャの価格を予測してください」で言い換えてみると、`X`は価格を、`Y`は販売された月を表しています。
>
>![方程式の計算](../images/calculation.png)
>
> Yの値を計算してみましょう。$4前後払っているなら、4月に違いありません![Jen Looper](https://twitter.com/jenlooper) によるインフォグラフィック。
>
> 直線を計算する数学は、直線の傾きを示す必要がありますが、これは切片、つまり「X = 0」のときに「Y」がどこに位置するかにも依存します。
>
> これらの値の計算方法は、[Math is Fun](https://www.mathsisfun.com/data/least-squares-regression.html) というサイトで見ることができます。また、[this Least-squares calculator](https://www.mathsisfun.com/data/least-squares-calculator.html) では、値が線にどのような影響を与えるかを見ることができます。
## 相関関係
もう一つの理解すべき用語は、与えられたXとYの変数間の**相関係数 (Correlation Coefficient)** です。散布図を使えば、この係数をすぐに可視化することができます。データポイントがきれいな直線上に散らばっているプロットは、高い相関を持っていますが、データポイントがXとYの間のあらゆる場所に散らばっているプロットは、低い相関を持っています。
良い線形回帰モデルとは、最小二乗法によって求めた回帰線が高い相関係数 (0よりも1に近い)を持つものです。
✅ このレッスンのノートを開いて、「都市と価格」の散布図を見てみましょう。散布図の視覚的な解釈によると、カボチャの販売に関する「都市」と「価格」の関連データは、相関性が高いように見えますか、それとも低いように見えますか?
## 回帰に用いるデータの準備
この演習の背景にある数学を理解したので、回帰モデルを作成して、どのパッケージのカボチャの価格が最も高いかを予測できるかどうかを確認してください。休日のパンプキンパッチ用にパンプキンを購入する人は、パッチ用のパンプキンパッケージの購入を最適化するために、この情報を必要とするかもしれません。
ここではScikit-learnを使用するので、手作業で行う必要はありません。レッスンノートのメインのデータ処理ブロックに、Scikit-learnのライブラリを追加して、すべての文字列データを自動的に数字に変換します。
```python
from sklearn.preprocessing import LabelEncoder
new_pumpkins.iloc[:, 0:-1] = new_pumpkins.iloc[:, 0:-1].apply(LabelEncoder().fit_transform)
```
new_pumpkinsデータフレームを見ると、すべての文字列が数値になっているのがわかります。これにより、人が読むのは難しくなりましたが、Scikit-learnにとってはとても分かりやすくなりました。
これで、回帰に最も適したデータについて、(散布図を見ただけではなく)より高度な判断ができるようになりました。
良い予測モデルを構築するために、データの2点間に良い相関関係を見つけようとします。その結果、「都市」と「価格」の間には弱い相関関係しかないことがわかりました。
```python
print(new_pumpkins['City'].corr(new_pumpkins['Price']))
0.32363971816089226
```
しかし、パッケージと価格の間にはもう少し強い相関関係があります。これは理にかなっていると思いますか?通常、箱が大きければ大きいほど、価格は高くなります。
```python
print(new_pumpkins['Package'].corr(new_pumpkins['Price']))
0.6061712937226021
```
このデータに対する良い質問は、次のようになります。「あるカボチャのパッケージの価格はどのくらいになるか?」
この回帰モデルを構築してみましょう!
## 線形モデルの構築
モデルを構築する前に、もう一度データの整理をしてみましょう。NULLデータを削除し、データがどのように見えるかをもう一度確認します。
```python
new_pumpkins.dropna(inplace=True)
new_pumpkins.info()
```
そして、この最小セットから新しいデータフレームを作成し、それを出力します。
```python
new_columns = ['Package', 'Price']
lin_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
lin_pumpkins
```
```output
Package Price
70 0 13.636364
71 0 16.363636
72 0 16.363636
73 0 15.454545
74 0 13.636364
... ... ...
1738 2 30.000000
1739 2 28.750000
1740 2 25.750000
1741 2 24.000000
1742 2 24.000000
415 rows × 2 columns
```
1. これで、XとYの座標データを割り当てることができます。
```python
X = lin_pumpkins.values[:, :1]
y = lin_pumpkins.values[:, 1:2]
```
✅ ここでは何をしていますか? Pythonの[スライス記法](https://stackoverflow.com/questions/509211/understanding-slice-notation/509295#509295) を使って、`X`と`y`の配列を作成しています。
2. 次に、回帰モデル構築のためのルーチンを開始します。
```python
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
lin_reg = LinearRegression()
lin_reg.fit(X_train,y_train)
pred = lin_reg.predict(X_test)
accuracy_score = lin_reg.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
相関関係があまり良くないので、生成されたモデルもあまり正確ではありません。
```output
Model Accuracy: 0.3315342327998987
```
3. 今回の過程で描かれた線を可視化します。
```python
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, pred, color='blue', linewidth=3)
plt.xlabel('Package')
plt.ylabel('Price')
plt.show()
```
![パッケージと価格の関係を表す散布図](../images/linear.png)
4. 架空の値に対してモデルをテストする。
```python
lin_reg.predict( np.array([ [2.75] ]) )
```
この架空の値に対して、以下の価格が返されます。
```output
array([[33.15655975]])
```
回帰の線が正しく引かれていれば、その数字は理にかなっています。
🎃 おめでとうございます!数種類のカボチャの価格を予測するモデルを作成しました。休日のパンプキンパッチは美しいものになるでしょう。でも、もっと良いモデルを作れるかもしれません。
## 多項式回帰
線形回帰のもう一つのタイプは、多項式回帰です。時には変数の間に直線的な関係 (カボチャの量が多いほど、価格は高くなる)があることもありますが、これらの関係は、平面や直線としてプロットできないこともあります。
✅ 多項式回帰を使うことができる、[いくつかの例](https://online.stat.psu.edu/stat501/lesson/9/9.8) を示します。
先ほどの散布図の「品種」と「価格」の関係をもう一度見てみましょう。この散布図は、必ずしも直線で分析しなければならないように見えますか?そうではないかもしれません。このような場合は、多項式回帰を試してみましょう。
✅ 多項式とは、1つ以上の変数と係数で構成される数学的表現である。
多項式回帰では、非線形データをよりよく適合させるために曲線を作成します。
1. 元のカボチャのデータの一部を入力したデータフレームを作成してみましょう。
```python
new_columns = ['Variety', 'Package', 'City', 'Month', 'Price']
poly_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
poly_pumpkins
```
データフレーム内のデータ間の相関関係を視覚化するには、「coolwarm」チャートで表示するのが良いでしょう。
2. `Background_gradient()` メソッドの引数に `coolwarm` を指定して使用します。
```python
corr = poly_pumpkins.corr()
corr.style.background_gradient(cmap='coolwarm')
```
  このコードはヒートマップを作成します。
![データの相関関係を示すヒートマップ](../images/heatmap.png)
このチャートを見ると、「パッケージ」と「価格」の間に正の相関関係があることが視覚化されています。つまり、前回のモデルよりも多少良いモデルを作ることができるはずです。
### パイプラインの作成
Scikit-learnには、多項式回帰モデルを構築するための便利なAPIである`make_pipeline` [API](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html?highlight=pipeline#sklearn.pipeline.make_pipeline) が用意されています。「パイプライン」は推定量の連鎖で作成されます。今回の場合、パイプラインには多項式の特徴量、非線形の経路を形成する予測値が含まれます。
1. X列とy列を作ります。
```python
X=poly_pumpkins.iloc[:,3:4].values
y=poly_pumpkins.iloc[:,4:5].values
```
2. `make_pipeline()` メソッドを呼び出してパイプラインを作成します。
```python
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(PolynomialFeatures(4), LinearRegression())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
pipeline.fit(np.array(X_train), y_train)
y_pred=pipeline.predict(X_test)
```
### 系列の作成
この時点で、パイプラインが系列を作成できるように、ソートされたデータで新しいデータフレームを作成する必要があります。
以下のコードを追加します。
```python
df = pd.DataFrame({'x': X_test[:,0], 'y': y_pred[:,0]})
df.sort_values(by='x',inplace = True)
points = pd.DataFrame(df).to_numpy()
plt.plot(points[:, 0], points[:, 1],color="blue", linewidth=3)
plt.xlabel('Package')
plt.ylabel('Price')
plt.scatter(X,y, color="black")
plt.show()
```
`pd.DataFrame` を呼び出して新しいデータフレームを作成しました。次に`sort_values()` を呼び出して値をソートしました。最後に多項式のプロットを作成しました。
![パッケージと価格の関係を示す多項式のプロット](../images/polynomial.png)
よりデータにフィットした曲線を確認することができます。
モデルの精度を確認してみましょう。
```python
accuracy_score = pipeline.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
これで完成です!
```output
Model Accuracy: 0.8537946517073784
```
いい感じです!価格を予測してみましょう。
### 予測の実行
新しい値を入力し、予測値を取得できますか?
`predict()` メソッドを呼び出して、予測を行います。
```python
pipeline.predict( np.array([ [2.75] ]) )
```
以下の予測結果が得られます。
```output
array([[46.34509342]])
```
プロットを見てみると、納得できそうです!そして、同じデータを見て、これが前のモデルよりも良いモデルであれば、より高価なカボチャのために予算を組む必要があります。
🏆 お疲れ様でした!1つのレッスンで2つの回帰モデルを作成しました。回帰に関する最後のセクションでは、カテゴリーを決定するためのロジスティック回帰について学びます。
---
## 🚀チャレンジ
このノートブックでいくつかの異なる変数をテストし、相関関係がモデルの精度にどのように影響するかを確認してみてください。
## [講義後クイズ](https://white-water-09ec41f0f.azurestaticapps.net/quiz/14/)
## レビュー & 自主学習
このレッスンでは、線形回帰について学びました。回帰には他にも重要な種類があります。Stepwise、Ridge、Lasso、Elasticnetなどのテクニックをご覧ください。より詳しく学ぶには、[Stanford Statistical Learning course](https://online.stanford.edu/courses/sohs-ystatslearning-statistical-learning) が良いでしょう。
## 課題
[モデル構築](./assignment.ja.md)

@ -0,0 +1,338 @@
# Scikit-learn을 사용한 regression 모델 만들기: regression 2가지 방식
![Linear vs polynomial regression infographic](.././images/linear-polynomial.png)
> Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [강의 전 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/13/)
### 소개
지금까지 이 강의에서 사용할 호박 가격 데이터셋에서 모은 샘플 데이터로 regression이 무엇인지 찾아보았습니다. Matplotlib을 사용하여 시각화했습니다.
이제 ML의 regression에 대하여 더 깊게 파고 들 준비가 되었습니다. 이 강의에서, 2가지 타입의 regression에 대해 배웁니다: 이 기술의 기반이 되는 수학의 일부와 함께, _basic linear regression_ 과 _polynomial regression_.
> 이 커리큘럼 대부분에 걸쳐서, 수학에 대한 최소한의 지식을 가정하고, 다른 필드에서 온 학생들이 수학에 접근할 수 있도록 노력하므로, 이해를 돕기 위하여 노트, 🧮 callouts, 다이어그램과 기타 학습 도구를 찾아보세요.
### 필요한 조건
지금즈음 조사하고 있던 호박 데이터의 구조에 익숙해집니다. 이 강의의 _notebook.ipynb_ 파일에서 preloaded와 pre-cleaned된 것을 찾을 수 있습니다. 파일에서, 호박 가격은 새로운 데이터프레임에서 bushel per로 보여집니다. Visual Studio Code의 커널에서 이 노트북을 실행할 수 있는 지 확인합니다.
### 준비하기
참고하자면, 이러한 질문을 물어보기 위해서 이 데이터를 불러오고 있습니다.
- 호박을 사기 좋은 시간은 언제인가요?
- 작은 호박 케이스의 가격은 얼마인가요?
- half-bushel 바구니 또는 1 1/9 bushel 박스로 사야 하나요?
이 데이터로 계속 파봅시다.
이전 강의에서, Pandas 데이터프레임을 만들고 원본 데이터셋의 일부를 채웠으며, bushel로 가격을 표준화했습니다. 그렇게 했지만, 가을에만 400개의 데이터 포인트를 모을 수 있었습니다.
이 강의에 첨부된 notebook에서 미리 불러온 데이터를 봅시다. 데이터를 미리 불러오고 초기 scatterplot(산점도)이 월 데이터를 보여주도록 차트로 만듭니다. 더 정리하면 데이터의 특성에 대하여 조금 더 자세히 알 수 있습니다.
## Linear regression 라인
1 강의에서 배웠던 것처럼, linear regression 연습의 목표는 라인을 그릴 수 있어야 합니다:
- **변수 관계 보이기**. 변수 사이 관게 보이기
- **예상하기**. 새로운 데이터 포인트가 라인과 관련해서 어디에 있는지 정확하게 예측합니다.
이런 타입의 선을 그리는 것은 **Least-Squares Regression** 의 전형적입니다. 'least-squares'이라는 말은 regression 라인을 두른 모든 데이터 포인트가 제곱된 다음에 더하는 것을 의미합니다. 이상적으로, 적은 수의 오류, 또는 `least-squares`를 원하기 때문에, 최종 합계는 가능한 작아야 합니다.
모든 데이터 포인트에서 누적 거리가 가장 짧은 라인을 모델링하기 원합니다. 방향보다 크기에 관심있어서 항을 더하기 전에 제곱합니다.
> **🧮 Show me the math**
>
> _line of best fit_ 이라고 불리는 이 선은, [an equation](https://en.wikipedia.org/wiki/Simple_linear_regression)으로 표현할 수 있습니다:
>
> ```
> Y = a + bX
> ```
>
> `X` 는 '독립(설명) 변수'입니다. `Y`는 '종속 변수'입니다. 라인의 기울기는 `b`이고 `a`는 y-절편이며, `X = 0`일 떄 `Y`의 값을 나타냅니다.
>
>![calculate the slope](../images/slope.png)
>
> 우선, 기울기 `b`를 구합니다. Infographic by [Jen Looper](https://twitter.com/jenlooper)
>
> 즉, 호박의 원본 질문을 참조해봅니다 : "predict the price of a pumpkin per bushel by month", `X`는 가격을 나타내고 `Y`는 판매한 달을 나타냅니다.
>
>![complete the equation](../images/calculation.png)
>
> Y의 값을 구합니다. 만약 4달러 정도 준다면, 4월만 가능합니다! Infographic by [Jen Looper](https://twitter.com/jenlooper)
>
> 라인을 구하는 수학은 절편, 또는 `X = 0`일 때 `Y`가 위치한 곳에 따라, 달라지는 라인의 기울기를 볼 수 있어야 합니다.
>
> [Math is Fun](https://www.mathsisfun.com/data/least-squares-regression.html) 웹사이트에서 값을 구하는 방식을 지켜볼 수 있습니다. 그리고 [this Least-squares calculator](https://www.mathsisfun.com/data/least-squares-calculator.html)를 찾아가서 숫자 값이 라인에 어떤 영향을 주는 지 볼 수 있습니다.
## 상관 관계
이해할 하나의 용어는 주어진 X와 Y 변수 사이의 **Correlation Coefficient**입니다. scatterplot(산점도)를 사용해서, 이 계수를 빠르게 시각화할 수 있습니다. 데이터 포인트를 깔끔한 라인으로 흩어 둔 plot은 상관 관계가 높지만, 데이터 포인트가 X와 Y 사이 어디에나 흩어진 plot은 상관 관계가 낮습니다.
좋은 linear regression 모델은 regression 라인과 같이 Least-Squares Regression 방식을 사용하여 (0 보다 1에 가까운) 높은 상관 계수를 가집니다.
✅ 이 강위에서 같이 주는 노트북을 실행하고 City to Price의 scatterplot (산점도)를 봅니다. scatterplot (산점도)의 시각적 해석에 따르면, 호박 판매를 도시와 가격에 연관지으면 데이터가 높거나 낮은 상관 관계를 보이는 것 같나요?
## Regression를 위한 데이터 준비하기
지금부터 연습에 기반한 수학을 이해했으므로, Regression 모델을 만들어서 호박 가격이 괜찮은 호박 패키지를 예측할 수 있는 지 봅니다. holiday pumpkin patch를 위해서 호박을 사는 사람은 이 정보로 패치용 호박 패키지를 최적으로 사고 싶습니다.
Scikit-learn을 사용할 예정이기 때문에, (할 수 있지만) 손으로 직접 할 필요가 없습니다. 수업 노트북의 주 데이터-처리 블록에서, Scikit-learn의 라이브러리를 추가하여 모든 문자열 데이터를 숫자로 자동 변환합니다:
```python
from sklearn.preprocessing import LabelEncoder
new_pumpkins.iloc[:, 0:-1] = new_pumpkins.iloc[:, 0:-1].apply(LabelEncoder().fit_transform)
```
new_pumpkins 데이터프레임을 보면, 모든 문자열은 이제 숫자로 보입니다. 직접 읽기는 힘들지만 Scikit-learn은 더욱 더 이해하기 쉽습니다!
지금부터 regression에 잘 맞는 데이터에 대하여 (scatterplot(산점도) 지켜보는 것 말고도) 교육적인 결정을 할 수 있습니다.
잠재적으로 좋은 예측 모델을 만드려면 데이터의 두 포인트 사이 좋은 상관 관계를 찾아야 합니다. 도시와 가격 사이에는 약한 상관 관계만 있다는, 사실이 밝혀졌습니다:
```python
print(new_pumpkins['City'].corr(new_pumpkins['Price']))
0.32363971816089226
```
하지만 패키지와 가격 사이에는 조금 더 큰 상관 관계가 있습니다. 이해가 되나요? 일반적으로, 농산물 박스가 클수록, 가격도 높습니다.
```python
print(new_pumpkins['Package'].corr(new_pumpkins['Price']))
0.6061712937226021
```
데이터에 물어보기 좋은 질문은 이렇습니다: 'What price can I expect of a given pumpkin package?'
regression 모델을 만들어봅니다
## linear 모델 만들기
모델을 만들기 전에, 데이터를 다시 정리합니다. Null 데이터를 드랍하고 데이터가 어떻게 보이는 지 다시 확인합니다.
```python
new_pumpkins.dropna(inplace=True)
new_pumpkins.info()
```
그러면, 최소 셋에서 새로운 데이터프레임을 만들고 출력합니다:
```python
new_columns = ['Package', 'Price']
lin_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
lin_pumpkins
```
```output
Package Price
70 0 13.636364
71 0 16.363636
72 0 16.363636
73 0 15.454545
74 0 13.636364
... ... ...
1738 2 30.000000
1739 2 28.750000
1740 2 25.750000
1741 2 24.000000
1742 2 24.000000
415 rows × 2 columns
```
1. 이제 X와 Y 좌표 데이터를 대입합니다:
```python
X = lin_pumpkins.values[:, :1]
y = lin_pumpkins.values[:, 1:2]
```
✅ 어떤 일이 생기나요? [Python slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation/509295#509295)으로 `X` 와 `y`를 채울 배열을 생성합니다.
2. 다음으로, regression model-building 루틴을 시작합니다:
```python
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
lin_reg = LinearRegression()
lin_reg.fit(X_train,y_train)
pred = lin_reg.predict(X_test)
accuracy_score = lin_reg.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
상관 관계가 좋지 못해서, 만들어진 모델은 딱히 정확하지 않습니다.
```output
Model Accuracy: 0.3315342327998987
```
3. 프로세스에서 그려진 라인을 시각화할 수 있습니다:
```python
plt.scatter(X_test, y_test, color='black')
plt.plot(X_test, pred, color='blue', linewidth=3)
plt.xlabel('Package')
plt.ylabel('Price')
plt.show()
```
![A scatterplot showing package to price relationship](.././images/linear.png)
4. 가상의 Variety에 대하여 모델을 테스트합니다:
```python
lin_reg.predict( np.array([ [2.75] ]) )
```
전설적 Variety의 반품된 가격입니다:
```output
array([[33.15655975]])
```
regression 라인의 로직이 사실이라면, 숫자는 의미가 있습니다.
🎃 축하드립니다. 방금 전에 몇 호박 종의 가격 예측하는 모델을 만들었습니다. holiday pumpkin patch는 아릅답습니다. 하지만 더 좋은 모델을 만들 수 있습니다!
## Polynomial regression
linear regression의 또 다른 타입은 polynomial regression 입니다. 때때로 변수 사이 linear 관계가 있지만 - 호박 볼륨이 클수록, 가격이 높아지는 - 이런 관계를 평면 또는 직선으로 그릴 수 없습니다.
✅ polynomial regression을 사용할 수 있는 데이터의 [some more examples](https://online.stat.psu.edu/stat501/lesson/9/9.8)입니다.
이전 plot에서 다양성과 가격 사이 관계를 봅니다. scatterplot(산점도)이 반드시 직선으로 분석되어야 하는 것처럼 보이나요? 아마 아닐겁니다. 이 케이스에서, polynomial regression을 시도할 수 있습니다.
✅ Polynomials는 하나 또는 더 많은 변수와 계수로 이루어 질 수 있는 수학적 표현식입니다.
Polynomial regression은 nonlinear 데이터에 더 맞는 곡선을 만듭니다.
1. 원본 호박 데이터의 세그먼트로 채워진 데이터프레임을 다시 만듭니다:
```python
new_columns = ['Variety', 'Package', 'City', 'Month', 'Price']
poly_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
poly_pumpkins
```
데이터프레임의 데이터 사이 상관 관계를 시각화하는 좋은 방식은 'coolwarm' 차트에 보여주는 것입니다:
2. 인수 값으로 `coolwarm`을 `Background_gradient()` 메소드에 사용합니다:
```python
corr = poly_pumpkins.corr()
corr.style.background_gradient(cmap='coolwarm')
```
이 코드로 heatmap을 만듭니다:
![A heatmap showing data correlation](.././images/heatmap.png)
이 차트를 보고 있으면, 패키지와 가격 사이 좋은 상관 관계를 시각화할 수 있습니다. 그래서 이전의 모델보다 약간 좋게 만들 수 있어야 합니다.
### 파이프라인 만들기
Scikit-learn에는 polynomial regression 모델을 만들 때 도움을 받을 수 있는 API가 포함되어 있습니다 - the `make_pipeline` [API](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html?highlight=pipeline#sklearn.pipeline.make_pipeline). 추정량의 체인인 'pipeline'이 만들어집니다. 이 케이스는, 파이프라인에 polynomial features, 또는 nonlinear 경로를 만들 예측이 포함됩니다.
1. X 와 y 열을 작성합니다:
```python
X=poly_pumpkins.iloc[:,3:4].values
y=poly_pumpkins.iloc[:,4:5].values
```
2. `make_pipeline()` 메소드를 불러서 파이프라인을 만듭니다:
```python
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
pipeline = make_pipeline(PolynomialFeatures(4), LinearRegression())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
pipeline.fit(np.array(X_train), y_train)
y_pred=pipeline.predict(X_test)
```
### 시퀀스 만들기
이 지점에서, 파이프라인이 시퀀스를 만들 수 있도록 _sorted_ 데이터로 새로운 데이터프레임을 만들 필요가 있습니다.
해당 코드를 추가합니다:
```python
df = pd.DataFrame({'x': X_test[:,0], 'y': y_pred[:,0]})
df.sort_values(by='x',inplace = True)
points = pd.DataFrame(df).to_numpy()
plt.plot(points[:, 0], points[:, 1],color="blue", linewidth=3)
plt.xlabel('Package')
plt.ylabel('Price')
plt.scatter(X,y, color="black")
plt.show()
```
`pd.DataFrame`을 불러서 새로운 데이터프레임을 만듭니다. 그러면 `sort_values()`도 불러서 값을 정렬합니다. 마지막으로 polynomial plot을 만듭니다:
![A polynomial plot showing package to price relationship](.././images/polynomial.png)
데이터에 더 맞는 곡선을 볼 수 있습니다.
모델의 정확도를 확인합시다:
```python
accuracy_score = pipeline.score(X_train,y_train)
print('Model Accuracy: ', accuracy_score)
```
그리고 짠!
```output
Model Accuracy: 0.8537946517073784
```
더 좋습니다! 가격을 예측해봅시다:
### 예측하기
새로운 값을 넣고 예측할 수 있나요?
`predict()`를 불러서 예측합니다:
```python
pipeline.predict( np.array([ [2.75] ]) )
```
이렇게 예측됩니다:
```output
array([[46.34509342]])
```
주어진 plot에서, 의미가 있습니다! 그리고, 이전보다 모델이 더 좋아졌다면, 같은 데이터를 보고, 더 비싼 호박을 위한 예산이 필요합니다!
🏆 좋습니다! 이 강의에서 두가지 regression 모델을 만들었습니다. regression의 마지막 섹션에서, 카테고리를 결정하기 위한 logistic regression에 대하여 배우게 됩니다.
---
## 🚀 도전
노트북에서 다른 변수를 테스트하면서 상관 관계가 모델 정확도에 어떻게 대응되는 지 봅니다.
## [강의 후 퀴즈](https://white-water-09ec41f0f.azurestaticapps.net/quiz/14/)
## 검토 & 자기주도 학습
이 강의에서 Linear Regression에 대하여 배웠습니다. Regression의 다른 중요 타입이 있습니다. Stepwise, Ridge, Lasso 와 Elasticnet 기술에 대하여 읽어봅니다. 더 배우기 위해서 공부하기 좋은 코스는 [Stanford Statistical Learning course](https://online.stanford.edu/courses/sohs-ystatslearning-statistical-learning)입니다.
## 과제
[Build a Model](../assignment.md)

@ -1,19 +1,21 @@
# 使用Scikit-learn构建回归模型:两种方式的回归
# 使用 Scikit-learn 构建回归模型:两种方式的回归
![线性与多项式回归信息图](../images/linear-polynomial.png)
> 作者[Dasani Madipalli](https://twitter.com/dasani_decoded)
## [课前测](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/13/)
### 介绍
> 作者 [Dasani Madipalli](https://twitter.com/dasani_decoded)
到目前为止,你已经通过从我们将在本课程中使用的南瓜定价数据集收集的样本数据探索了什么是回归。你还使用Matplotlib对其进行了可视化。
## [课前测](https://white-water-09ec41f0f.azurestaticapps.net/quiz/13/)
现在你已准备好深入研究ML的回归。 在本课中,你将详细了解两种类型的回归:_基本线性回归_和_多项式回归_,以及这些技术背后的一些数学知识。
### 介绍
到目前为止,你已经通过从我们将在本课程中使用的南瓜定价数据集收集的样本数据探索了什么是回归。你还使用 Matplotlib 对其进行了可视化。
现在你已准备好深入研究 ML 的回归。 在本课中,你将详细了解两种类型的回归:_基本线性回归_ 和 _多项式回归_,以及这些技术背后的一些数学知识。
> 在整个课程中,我们假设数学知识最少,并试图让来自其他领域的学生也能接触到它,因此请使用笔记、🧮标注、图表和其他学习工具以帮助理解。
### 前提
你现在应该熟悉我们正在检查的南瓜数据的结构。你可以在本课的_notebook.ipynb_文件中找到它。 在这个文件中,南瓜的价格显示在一个新的dataframe 中。确保可以在Visual Studio Code代码的内核中运行这些notebooks。
你现在应该熟悉我们正在检查的南瓜数据的结构。你可以在本课的 _notebook.ipynb_ 文件中找到它。 在这个文件中,南瓜的价格显示在一个新的 dataframe 中。确保可以在 Visual Studio Code 代码的内核中运行这些 notebooks。
### 准备
@ -21,61 +23,62 @@
- 什么时候买南瓜最好?
- 一箱微型南瓜的价格是多少?
- 我应该买半蒲式耳还是1 1/9蒲式耳?
- 我应该买半蒲式耳还是 1 1/9 蒲式耳?
让我们继续深入研究这些数据。
在上一课中,你创建了一个Pandas dataframe并用原始数据集的一部分填充它,按蒲式耳标准化定价。但是,通过这样做,你只能收集大约400个数据点,而且只能收集秋季月份的数据。
在上一课中,你创建了一个 Pandas dataframe 并用原始数据集的一部分填充它,按蒲式耳标准化定价。但是,通过这样做,你只能收集大约 400 个数据点,而且只能收集秋季月份的数据。
看看我们在本课随附的notebook中预加载的数据。数据已预加载,并绘制了初始散点图以显示月份数据。也许我们可以通过更多地清理数据来获得更多关于数据性质的细节。
看看我们在本课随附的 notebook 中预加载的数据。数据已预加载,并绘制了初始散点图以显示月份数据。也许我们可以通过更多地清理数据来获得更多关于数据性质的细节。
## 线性回归线
正如你在第1课中学到的,线性回归练习的目标是能够绘制一条线以便:
正如你在第 1 课中学到的,线性回归练习的目标是能够绘制一条线以便:
- **显示变量关系**。 显示变量之间的关系
- **作出预测**。 准确预测新数据点与该线的关系。
绘制这种类型的线是**最小二乘回归**的典型做法。术语“最小二乘法”意味着将回归线周围的所有数据点平方,然后相加。理想情况下,最终和尽可能小,因为我们希望错误数量较少,或“最小二乘法”。
我们这样做是因为我们想要对一条与所有数据点的累积距离最小的线进行建模。我们还在添加它们之前对这些项进行平方,因为我们关心的是它的大小而不是它的方向。
> **🧮 数学知识**
>
> 这条线称为_最佳拟合线_,可以用[一个等式](https://en.wikipedia.org/wiki/Simple_linear_regression)表示:
>
> **🧮 数学知识**
>
> 这条线称为 _最佳拟合线_,可以用[一个等式](https://en.wikipedia.org/wiki/Simple_linear_regression)表示:
>
> ```
> Y = a + bX
> ```
>
> `X`是“解释变量”。`Y`是“因变量”。直线的斜率是`b`,`a`是y轴截距,指的是`X = 0`时`Y`的值。
> `X` 是“解释变量”。`Y` 是“因变量”。直线的斜率是 `b`,`a` 是 y 轴截距,指的是 `X = 0` 时 `Y` 的值。
>
>![计算斜率](../images/slope.png)
>
> 首先,计算斜率`b`。作者[Jen Looper](https://twitter.com/jenlooper)
> 首先,计算斜率 `b`。作者 [Jen Looper](https://twitter.com/jenlooper)
>
> 换句话说,参考我们的南瓜数据的原始问题:“按月预测每蒲式耳南瓜的价格”,`X`指的是价格,`Y`指的是销售月份。
> 换句话说,参考我们的南瓜数据的原始问题:“按月预测每蒲式耳南瓜的价格”,`X` 指的是价格,`Y` 指的是销售月份。
>
>![完成等式](../images/calculation.png)
> ![完成等式](../images/calculation.png)
>
> 计算Y的值。如果你支付大约4美元,那一定是四月!作者[Jen Looper](https://twitter.com/jenlooper)
> 计算 Y 的值。如果你支付大约 4 美元,那一定是四月!作者 [Jen Looper](https://twitter.com/jenlooper)
>
> 计算直线的数学必须证明直线的斜率,这也取决于截距,或者当`X = 0`时`Y`所在的位置。
> 计算直线的数学必须证明直线的斜率,这也取决于截距,或者当 `X = 0` 时 `Y` 所在的位置。
>
> 你可以在[Math is Fun](https://www.mathsisfun.com/data/least-squares-regression.html)网站上观察这些值的计算方法。另请访问[这个最小二乘计算器](https://www.mathsisfun.com/data/least-squares-calculator.html)以观察数字的值如何影响直线。
> 你可以在 [Math is Fun](https://www.mathsisfun.com/data/least-squares-regression.html) 网站上观察这些值的计算方法。另请访问[这个最小二乘计算器](https://www.mathsisfun.com/data/least-squares-calculator.html)以观察数字的值如何影响直线。
## 相关性
另一个需要理解的术语是给定X和Y变量之间的**相关系数**。使用散点图,你可以快速可视化该系数。数据点散布在一条直线上的图具有高相关性,但数据点散布在X和Y之间的图具有低相关性。
另一个需要理解的术语是给定 X 和 Y 变量之间的**相关系数**。使用散点图,你可以快速可视化该系数。数据点散布在一条直线上的图具有高相关性,但数据点散布在 X 和 Y 之间的图具有低相关性。
一个好的线性回归模型将是一个用最小二乘回归法与直线回归得到的高(更接近于1)相关系数的模型。
一个好的线性回归模型将是一个用最小二乘回归法与直线回归得到的高(更接近于 1)相关系数的模型。
✅ 运行本课随附的notebook并查看City to Price散点图。根据你对散点图的视觉解释,将南瓜销售的城市与价格相关联的数据似乎具有高相关性或低相关性?
✅ 运行本课随附的 notebook 并查看 City to Price 散点图。根据你对散点图的视觉解释,将南瓜销售的城市与价格相关联的数据似乎具有高相关性或低相关性?
## 为回归准备数据
现在你已经了解了本练习背后的数学原理,可以创建一个回归模型,看看你是否可以预测哪个南瓜包装的南瓜价格最优惠。为节日购买南瓜的人可能希望此信息能够优化他们如何购买南瓜包装。
由于你将使用Scikit-learn,因此没有理由手动执行此操作(尽管你可以!)。在课程notebook的主要数据处理块中,从Scikit-learn添加一个库以自动将所有字符串数据转换为数字:
由于你将使用 Scikit-learn,因此没有理由手动执行此操作(尽管你可以!)。在课程 notebook 的主要数据处理块中,从 Scikit-learn 添加一个库以自动将所有字符串数据转换为数字:
```python
from sklearn.preprocessing import LabelEncoder
@ -83,7 +86,7 @@ from sklearn.preprocessing import LabelEncoder
new_pumpkins.iloc[:, 0:-1] = new_pumpkins.iloc[:, 0:-1].apply(LabelEncoder().fit_transform)
```
如果你现在查看new_pumpkins dataframe,你会看到所有字符串现在都是数字。这让你更难阅读,但对Scikit-learn来说更容易理解!
如果你现在查看 new_pumpkins dataframe,你会看到所有字符串现在都是数字。这让你更难阅读,但对 Scikit-learn 来说更容易理解!
现在,你可以对最适合回归的数据做出更有根据的决策(不仅仅是基于观察散点图)。
@ -103,7 +106,7 @@ print(new_pumpkins['Package'].corr(new_pumpkins['Price']))
对这些数据提出的一个很好的问题是:“我可以期望给定的南瓜包装的价格是多少?”
让我们建立这个回归模型
让我们建立这个回归模型
## 建立线性模型
@ -114,7 +117,7 @@ new_pumpkins.dropna(inplace=True)
new_pumpkins.info()
```
然后,从这个最小集合创建一个新的dataframe并将其打印出来:
然后,从这个最小集合创建一个新的 dataframe 并将其打印出来:
```python
new_columns = ['Package', 'Price']
@ -139,13 +142,14 @@ lin_pumpkins
415 rows × 2 columns
```
1. 现在你可以分配X和y坐标数据:
1. 现在你可以分配 X 和 y 坐标数据:
```python
X = lin_pumpkins.values[:, :1]
y = lin_pumpkins.values[:, 1:2]
```
✅ 这里发生了什么?你正在使用[Python slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation/509295#509295)来创建数组来填充`X`和`y`。
✅ 这里发生了什么?你正在使用 [Python slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation/509295#509295) 来创建数组来填充 `X` 和 `y`。
2. 接下来,开始回归模型构建例程:
@ -181,6 +185,7 @@ lin_pumpkins
plt.show()
```
![散点图显示包装与价格的关系](../images/linear.png)
4. 针对假设的品种测试模型:
@ -188,7 +193,7 @@ lin_pumpkins
```python
lin_reg.predict( np.array([ [2.75] ]) )
```
这个神话般的品种的价格是:
```output
@ -211,7 +216,8 @@ lin_pumpkins
多项式回归创建一条曲线以更好地拟合非线性数据。
1. 让我们重新创建一个填充了原始南瓜数据片段的dataframe:
1. 让我们重新创建一个填充了原始南瓜数据片段的 dataframe:
```python
new_columns = ['Variety', 'Package', 'City', 'Month', 'Price']
poly_pumpkins = new_pumpkins.drop([c for c in new_pumpkins.columns if c not in new_columns], axis='columns')
@ -219,31 +225,32 @@ lin_pumpkins
poly_pumpkins
```
可视化dataframe中数据之间相关性的一种好方法是将其显示在“coolwarm”图表中:
可视化 dataframe 中数据之间相关性的一种好方法是将其显示在“coolwarm”图表中:
2. 使用`Background_gradient()`方法和`coolwarm`作为其参数值:
2. 使用 `Background_gradient()` 方法和 `coolwarm` 作为其参数值:
```python
corr = poly_pumpkins.corr()
corr.style.background_gradient(cmap='coolwarm')
```
这段代码创建了一个热图:
![显示数据相关性的热图](../images/heatmap.png)
查看此图表,你可以直观地看到Package和Price之间的良好相关性。所以你应该能够创建一个比上一个更好的模型。
查看此图表,你可以直观地看到 Package 和 Price 之间的良好相关性。所以你应该能够创建一个比上一个更好的模型。
### 创建管道
Scikit-learn包含一个用于构建多项式回归模型的有用API - `make_pipeline` [API](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html?highlight=pipeline#sklearn.pipeline.make_pipeline)。 创建了一个“管道”,它是一个估计器链。 在这种情况下,管道包括多项式特征或形成非线性路径的预测。
Scikit-learn 包含一个用于构建多项式回归模型的有用 API - `make_pipeline` [API](https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.make_pipeline.html?highlight=pipeline#sklearn.pipeline.make_pipeline)。 创建了一个“管道”,它是一个估计器链。在这种情况下,管道包括多项式特征或形成非线性路径的预测。
1. 构建X和y列:
1. 构建 X 和 y 列:
```python
X=poly_pumpkins.iloc[:,3:4].values
y=poly_pumpkins.iloc[:,4:5].values
```
2. 通过调用`make_pipeline()`方法创建管道:
2. 通过调用 `make_pipeline()` 方法创建管道:
```python
from sklearn.preprocessing import PolynomialFeatures
@ -260,7 +267,7 @@ Scikit-learn包含一个用于构建多项式回归模型的有用API - `make_pi
### 创建序列
此时,你需要使用_排序好的_数据创建一个新的dataframe ,以便管道可以创建序列。
此时,你需要使用_排序好的_数据创建一个新的 dataframe ,以便管道可以创建序列。
添加以下代码:
@ -276,7 +283,7 @@ Scikit-learn包含一个用于构建多项式回归模型的有用API - `make_pi
plt.show()
```
你通过调用`pd.DataFrame`创建了一个新的dataframe。然后通过调用`sort_values()`对值进行排序。最后你创建了一个多项式图:
你通过调用 `pd.DataFrame` 创建了一个新的 dataframe。然后通过调用 `sort_values()` 对值进行排序。最后你创建了一个多项式图:
![显示包装与价格关系的多项式图](../images/polynomial.png)
@ -301,11 +308,12 @@ Scikit-learn包含一个用于构建多项式回归模型的有用API - `make_pi
我们可以输入一个新值并得到一个预测吗?
调用`predict()`进行预测:
调用 `predict()` 进行预测:
```python
pipeline.predict( np.array([ [2.75] ]) )
```
你会得到这样的预测:
```output
@ -314,19 +322,20 @@ Scikit-learn包含一个用于构建多项式回归模型的有用API - `make_pi
参照图像,这确实有道理!而且,如果这是一个比前一个更好的模型,看同样的数据,你需要为这些更昂贵的南瓜做好预算!
🏆 干得不错!你在一节课中创建了两个回归模型。在回归的最后一节中,你将了解逻辑回归以确定类别。
🏆 干得不错!你在一节课中创建了两个回归模型。在回归的最后一节中,你将了解逻辑回归以确定类别。
---
## 🚀挑战
在此notebook中测试几个不同的变量,以查看相关性与模型准确性的对应关系。
在此 notebook 中测试几个不同的变量,以查看相关性与模型准确性的对应关系。
## [课后测](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/14/)
## [课后测](https://white-water-09ec41f0f.azurestaticapps.net/quiz/14/)
## 复习与自学
在本课中,我们学习了线性回归。还有其他重要的回归类型。了解Stepwise、Ridge、Lasso和Elasticnet技术。学习更多信息的好课程是[斯坦福统计学习课程](https://online.stanford.edu/courses/sohs-ystatslearning-statistical-learning)
在本课中,我们学习了线性回归。还有其他重要的回归类型。了解 Stepwise、Ridge、Lasso 和 Elasticnet 技术。学习更多信息的好课程是 [斯坦福统计学习课程](https://online.stanford.edu/courses/sohs-ystatslearning-statistical-learning)
## 任务
## 任务
[构建模型](../assignment.md)
[构建模型](./assignment.zh-cn.md)

@ -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,11 @@
# 回帰モデルの作成
## 課題の指示
このレッスンでは、線形回帰と多項式回帰の両方を使ってモデルを構築する方法を紹介しました。この知識をもとに、自分でデータセットを探すか、Scikit-learnのビルトインセットの1つを使用して、新しいモデルを構築してください。手法を選んだ理由をノートブックに書き、モデルの精度を示してください。精度が十分でない場合は、その理由も説明してください。
## ルーブリック
| 指標 | 模範的 | 適切 | 要改善 |
| -------- | ------------------------------------------------------------ | -------------------------- | ------------------------------- |
| | ドキュメント化されたソリューションを含む完全なノートブックを提示する。 | 解決策が不完全である。 | 解決策に欠陥またはバグがある。 |

@ -0,0 +1,12 @@
# 创建自己的回归模型
## 说明
在这节课中你学到了如何用线性回归和多项式回归建立一个模型。利用这些只是,找到一个你感兴趣的数据集或者是 Scikit-learn 内置的数据集来建立一个全新的模型。用你的 notebook 来解释为什么用了这种技术来对这个数据集进行建模,并且证明出你的模型的准确度。如果它没你想象中准确,请思考一下并解释一下原因。
## 评判标准
| 标准 | 优秀 | 中规中矩 | 仍需努力 |
| -------- | ------------------------------------------------------------ | -------------------------- | ------------------------------- |
| | 提交了一个完整的 notebook 工程文件,其中包含了解集,并且可读性良好 | 不完整的解集 | 解集是有缺陷或者有错误的 |

@ -2,7 +2,9 @@
![Logistic vs. linear regression infographic](./images/logistic-linear.png)
> Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [Pre-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/15/)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/15/)
> ### [This lesson is available in R!](./solution/R/lesson_4-R.ipynb)
## Introduction
@ -140,7 +142,7 @@ Now that we have an idea of the relationship between the binary categories of co
> **🧮 Show Me The Math**
>
> Remember how linear regression often used ordinary least squares to arrive at a value? Logistic regression relies on the concept of 'maximum likelihood' using [sigmoid functions](https://wikipedia.org/wiki/Sigmoid_function). A 'Sigmoid Function' on a plot looks like an 'S' shape. It takes a value and maps it to somewhere between 0 and 1. Its curve is also called a 'logistic curve'. Its formula looks like thus:
> Remember how linear regression often used ordinary least squares to arrive at a value? Logistic regression relies on the concept of 'maximum likelihood' using [sigmoid functions](https://wikipedia.org/wiki/Sigmoid_function). A 'Sigmoid Function' on a plot looks like an 'S' shape. It takes a value and maps it to somewhere between 0 and 1. Its curve is also called a 'logistic curve'. Its formula looks like this:
>
> ![logistic function](images/sigmoid.png)
>
@ -206,7 +208,7 @@ While you can get a scoreboard report [terms](https://scikit-learn.org/stable/mo
> 🎓 A '[confusion matrix](https://wikipedia.org/wiki/Confusion_matrix)' (or 'error matrix') is a table that expresses your model's true vs. false positives and negatives, thus gauging the accuracy of predictions.
1. To use a confusion metrics, call `confusin_matrix()`:
1. To use a confusion metrics, call `confusion_matrix()`:
```python
from sklearn.metrics import confusion_matrix
@ -220,26 +222,35 @@ While you can get a scoreboard report [terms](https://scikit-learn.org/stable/mo
[ 33, 0]])
```
What's going on here? Let's say our model is asked to classify items between two binary categories, category 'pumpkin' and category 'not-a-pumpkin'.
In Scikit-learn, confusion matrices Rows (axis 0) are actual labels and columns (axis 1) are predicted labels.
- If your model predicts something as a pumpkin and it belongs to category 'pumpkin' in reality we call it a true positive, shown by the top left number.
- If your model predicts something as not a pumpkin and it belongs to category 'pumpkin' in reality we call it a false positive, shown by the top right number.
- If your model predicts something as a pumpkin and it belongs to category 'not-a-pumpkin' in reality we call it a false negative, shown by the bottom left number.
- If your model predicts something as not a pumpkin and it belongs to category 'not-a-pumpkin' in reality we call it a true negative, shown by the bottom right number.
| | 0 | 1 |
| :---: | :---: | :---: |
| 0 | TN | FP |
| 1 | FN | TP |
![Confusion Matrix](images/confusion-matrix.png)
What's going on here? Let's say our model is asked to classify pumpkins between two binary categories, category 'orange' and category 'not-orange'.
> Infographic by [Jen Looper](https://twitter.com/jenlooper)
- If your model predicts a pumpkin as not orange and it belongs to category 'not-orange' in reality we call it a true negative, shown by the top left number.
- If your model predicts a pumpkin as orange and it belongs to category 'not-orange' in reality we call it a false negative, shown by the bottom left number.
- If your model predicts a pumpkin as not orange and it belongs to category 'orange' in reality we call it a false positive, shown by the top right number.
- If your model predicts a pumpkin as orange and it belongs to category 'orange' in reality we call it a true positive, shown by the bottom right number.
As you might have guessed it's preferable to have a larger number of true positives and true negatives and a lower number of false positives and false negatives, which implies that the model performs better.
✅ Q: According to the confusion matrix, how did the model do? A: Not too bad; there are a good number of true positives but also several false negatives.
How does the confusion matrix relate to precision and recall? Remember, the classification report printed above showed precision (0.83) and recall (0.98).
Precision = tp / (tp + fp) = 162 / (162 + 33) = 0.8307692307692308
Recall = tp / (tp + fn) = 162 / (162 + 4) = 0.9759036144578314
✅ Q: According to the confusion matrix, how did the model do? A: Not too bad; there are a good number of true negatives but also several false negatives.
Let's revisit the terms we saw earlier with the help of the confusion matrix's mapping of TP/TN and FP/FN:
🎓 Precision: TP/(TP + FN) The fraction of relevant instances among the retrieved instances (e.g. which labels were well-labeled)
🎓 Precision: TP/(TP + FP) The fraction of relevant instances among the retrieved instances (e.g. which labels were well-labeled)
🎓 Recall: TP/(TP + FP) The fraction of relevant instances that were retrieved, whether well-labeled or not
🎓 Recall: TP/(TP + FN) The fraction of relevant instances that were retrieved, whether well-labeled or not
🎓 f1-score: (2 * precision * recall)/(precision + recall) A weighted average of the precision and recall, with best being 1 and worst being 0
@ -252,6 +263,7 @@ Let's revisit the terms we saw earlier with the help of the confusion matrix's m
🎓 Weighted Avg: The calculation of the mean metrics for each label, taking label imbalance into account by weighting them by their support (the number of true instances for each label).
✅ Can you think which metric you should watch if you want your model to reduce the number of false negatives?
## Visualize the ROC curve of this model
This is not a bad model; its accuracy is in the 80% range so ideally you could use it to predict the color of a pumpkin given a set of variables.
@ -284,8 +296,9 @@ In future lessons on classifications, you will learn how to iterate to improve y
---
## 🚀Challenge
There's a lot more to unpack regarding logistic regression! But the best way to learn is to experiment. Find a dataset that lends itself to this type of analysis and build a model with it. What do you learn? tip: try [Kaggle](https://kaggle.com) for interesting datasets.
## [Post-lecture quiz](https://jolly-sea-0a877260f.azurestaticapps.net/quiz/16/)
There's a lot more to unpack regarding logistic regression! But the best way to learn is to experiment. Find a dataset that lends itself to this type of analysis and build a model with it. What do you learn? tip: try [Kaggle](https://www.kaggle.com/search?q=logistic+regression+datasets) for interesting datasets.
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/16/)
## Review & Self Study

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save