From 563ec789d9b8da2ede75524f5791034feacba152 Mon Sep 17 00:00:00 2001 From: Angel Mendez Date: Sat, 29 Jan 2022 16:56:22 -0600 Subject: [PATCH] feat: (spanish) Add translation for file * `2-Regression/2-Data/README.md` --- 2-Regression/2-Data/translations/README.es.md | 158 +++++++++--------- 1 file changed, 79 insertions(+), 79 deletions(-) diff --git a/2-Regression/2-Data/translations/README.es.md b/2-Regression/2-Data/translations/README.es.md index 18faac8e..2e7e6e3e 100644 --- a/2-Regression/2-Data/translations/README.es.md +++ b/2-Regression/2-Data/translations/README.es.md @@ -1,61 +1,61 @@ -# Build a regression model using Scikit-learn: prepare and visualize data +# Construye un modelo de regresión usando Scikit-learn: prepara y visualiza los datos -![Data visualization infographic](./images/data-visualization.png) +![Infografía de visualización de datos](../images/data-visualization.png) -Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded) +Infografía por [Dasani Madipalli](https://twitter.com/dasani_decoded) -## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/11/) +## [Examen previo a la lección](https://white-water-09ec41f0f.azurestaticapps.net/quiz/11/) -> ### [This lesson is available in R!](./solution/R/lesson_2-R.ipynb) +> ### [Esta lección se encuentra disponible en R!](../solution/R/lesson_2-R.ipynb) -## Introduction +## Introducción -Now that you are set up with the tools you need to start tackling machine learning model building with Scikit-learn, 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. +Ahora que has configurado las herramientas necesarias para iniciar el trabajo con la construcción de modelo de aprendizaje automático con Scikit-learn, estás listo para comenzar a realizar preguntas a tus datos. Mientras trabajas con los datos y aplicas soluciones de ML, es muy importante entender cómo realizar las preguntas correctas para desbloquear el potencial de tu conunto de datos. -In this lesson, you will learn: +En esta lección, aprenderás: -- How to prepare your data for model-building. -- How to use Matplotlib for data visualization. +- Cómo preparar tus datos para la construcción de modelos. +- Cómo usar Matplotlib para visualización de datos. -[![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 +[![Preparación y visualización de datos](https://img.youtube.com/vi/11AnOn_OAcE/0.jpg)](https://youtu.be/11AnOn_OAcE "Video de preparación y visualizción de datos - ¡Clic para ver!") +> 🎥 Da clic en la imagen superior para ver un video de los aspectos clave de esta lección -## Asking the right question of your data +## Realizando la pregunta correcta a tus datos -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. +La pregunta para la cual necesitas respuesta determinará qué tipo de algoritmos de ML requerirás. Y la calidad de la respuesta que obtendas será altamente dependiente de la naturaleza de tus datos. -Take a look at the [data](../data/US-pumpkins.csv) provided for this lesson. You can open this .csv file in VS Code. A quick skim immediately shows that there are blanks and a mix of strings and numeric data. 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. +Echa un vistazo a los [datos](../../data/US-pumpkins.csv) provistos para esta lección. Puedes abrir este archivo .csv en VS Code. Un vistazo rápido muestra inmediatamente que existen campos en blanco y una mezcla de datos numéricos y de cadena. También hay una columna extraña llamada 'Package' donde los datos están mezclados entre los valores 'sacks', 'bins' y otros. Los datos de hecho, son un pequeño desastre. -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. In this lesson, you will learn how to prepare a raw dataset using standard Python libraries. You will also learn various techniques to visualize the data. +De hecho, no es muy común obtener un conjunto de datos que esté totalmente listo para su uso en un modelo de ML. En esta lección, aprenderás cómo preparar un conjunto de datos en crudo usando librerías estándares de Python. También aprenderás varias técnicas para visualizar los datos. -## Case study: 'the pumpkin market' +## Caso de estudio: 'El mercado de calabazas' -In this folder you will find a .csv file in the root `data` folder called [US-pumpkins.csv](../data/US-pumpkins.csv) which includes 1757 lines of data about the market for pumpkins, sorted into groupings by city. This is raw data extracted from the [Specialty Crops Terminal Markets Standard Reports](https://www.marketnews.usda.gov/mnp/fv-report-config-step1?type=termPrice) distributed by the United States Department of Agriculture. +En este directorio encontrarás un archivo .cvs in la raíz del directorio `data` llamado [US-pumpkins.csv](../../data/US-pumpkins.csv), el cual incluye 1757 líneas de datos acerca del mercado de calabazas, ordenados en agrupaciones por ciudad. Estos son loas datos extraídos de [Reportes estándar de mercados terminales de cultivos especializados](https://www.marketnews.usda.gov/mnp/fv-report-config-step1?type=termPrice) distribuido por el Departamento de Agricultura de los Estados Unidos. -### Preparing data +### Preparando los datos -This data is in the public domain. It can be downloaded in many separate files, per city, from the USDA web site. To avoid too many separate files, we have concatenated all the city data into one spreadsheet, thus we have already _prepared_ the data a bit. Next, let's take a closer look at the data. +Estos datos son de dominio público. Puede ser descargado en varios archivos por separado, por ciudad, desde el sitio web de USDA. para evitar demasiados archivos por separado, hemos concatenado todos los datos de ciudad en una hoja de cálculo, así ya hemos _preparado_ los datos un poco. Lo siguiente es dar un vistazo más a fondo a los datos. -### The pumpkin data - early conclusions +### Los datos de las calabazas - conclusiones iniciales -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. +¿Qué notas acerca de los datos? Ya has visto que hay una mezcla de cadenas, números, blancos y valores extraños a los cuales debes encontrarle sentido. -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 +¿Qué preguntas puedes hacerle a los datos usando una técnica de regresión? Qué tal el "predecir el precio de la venta de calabaza durante un mes dado". Viendo nuevamente los datos, hay algunos cambios que necesitas hacer para crear las estructuras de datos necesarias para la tarea. +## Ejercicio - Analiza los datos de la calabaza -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. +Usemos [Pandas](https://pandas.pydata.org/), (el nombre es un acrónimo de `Python Data Analysis`) a tool very useful for shaping data, to analyze and prepare this pumpkin data. -### First, check for missing dates +### Primero, revisa las fechas faltantes -You will first need to take steps to check for missing dates: +Necesitarás realizar algunos pasos para revisar las fechas faltantes: -1. Convert the dates to a month format (these are US dates, so the format is `MM/DD/YYYY`). -2. Extract the month to a new column. +1. Convertir las fechas a formato de mes (las fechas están en formato de EE.UU., por lo que el formato es `MM/DD/YYYY`). +2. Extrae el mes en una nueva columna. -Open the _notebook.ipynb_ file in Visual Studio Code and import the spreadsheet in to a new Pandas dataframe. +Abre el archivo _notebook.ipynb_ en Visual Studio Code e importa la hoja de cálculo en un nuevo dataframe de Pandas. -1. Use the `head()` function to view the first five rows. +1. Usa la función `head()` para visualizar las primeras cinco filas. ```python import pandas as pd @@ -63,30 +63,30 @@ Open the _notebook.ipynb_ file in Visual Studio Code and import the spreadsheet pumpkins.head() ``` - ✅ What function would you use to view the last five rows? + ✅ ¿Qué función usarías para ver las últimas cinco filas? -1. Check if there is missing data in the current dataframe: +1. Revisa si existen datos faltantes en el dataframe actual: ```python pumpkins.isnull().sum() ``` - There is missing data, but maybe it won't matter for the task at hand. + Hay datos faltabtes, pero quizá no importen para la tarea en cuestión. -1. To make your dataframe easier to work with, drop several of its columns, using `drop()`, keeping only the columns you need: +1. Para facilitar el trabajo con tu dataframe, elimina varias de sus columnas usando `drop()`, manteniendo sólo las columnas que necesitas: ```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) ``` -### Second, determine average price of pumpkin +### Segundo, determina el precio promedio de la calabaza -Think about how to determine the average price of a pumpkin in a given month. What columns would you pick for this task? Hint: you'll need 3 columns. +Piensa en cómo determinar el precio promedio de la calabaza en un mes dado. ¿Qué columnas eligirás para esa tarea? Pista: necesitarás 3 columnas. -Solution: take the average of the `Low Price` and `High Price` columns to populate the new Price column, and convert the Date column to only show the month. Fortunately, according to the check above, there is no missing data for dates or prices. +Solución: toma el promedio de las columnas `Low Price` y `High Price` para poblar la nueva columna `Price` y convierte la columna `Date` para mostrar únicamente el mes, Afortunadamente, de acuerdo a la revisión de arriba, no hay datos faltantes para las fechas o precios. -1. To calculate the average, add the following code: +1. Para calcular el promedio, agrega el siguiente código: ```python price = (pumpkins['Low Price'] + pumpkins['High Price']) / 2 @@ -95,37 +95,37 @@ Solution: take the average of the `Low Price` and `High Price` columns to popula ``` - ✅ Feel free to print any data you'd like to check using `print(month)`. + ✅ Siéntete libre de imprimir cualquier dato que desees verificar, usando `print(month)`. -2. Now, copy your converted data into a fresh Pandas dataframe: +2. Ahora, copia tus datos convertidos en un nuevo dataframe de Pandas: ```python new_pumpkins = pd.DataFrame({'Month': month, 'Package': pumpkins['Package'], 'Low Price': pumpkins['Low Price'],'High Price': pumpkins['High Price'], 'Price': price}) ``` - Printing out your dataframe will show you a clean, tidy dataset on which you can build your new regression model. + Imprimir tu dataframe te mostrará un conjunto de datos limpio y ordenado, en el cual puedes construir tu nuevo modelo de regresión. -### But wait! There's something odd here +### ¡Pero espera!, Hay algo raro aquí -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. +Si observas la columna `Package`, las calabazas se venden en distintas configuraciones. Algunas son vendidas en medidas de '1 1/9 bushel', y otras en '1/2 bushel', algunas por pieza, algunas por libra y otras en grandes cajas de ancho variable. -> Pumpkins seem very hard to weigh consistently +> Las calabazas parecen muy difíciles de pesar consistentemente. -Digging into the original data, it's interesting that anything with `Unit of Sale` equalling 'EACH' or 'PER BIN' also have the `Package` type per inch, per bin, or 'each'. Pumpkins seem to be very hard to weigh consistently, so let's filter them by selecting only pumpkins with the string 'bushel' in their `Package` column. +Indagando en los datos originales, es interesante que cualquiera con el valor `Unit of Sale` igualado a 'EACH' o 'PER BIN' también tiene el tipo de `Package` por pulgada, por cesto, o 'each'. Las calabazas parecen muy difíciles de pesar consistentemente, por lo que las filtraremos seleccionando solo aquellas calabazas con el string 'bushel' en su columna `Package`. -1. Add a filter at the top of the file, under the initial .csv import: +1. Agrega un filtro al inicio del archivo, debajo de la importación inicial del .csv: ```python pumpkins = pumpkins[pumpkins['Package'].str.contains('bushel', case=True, regex=True)] ``` - If you print the data now, you can see that you are only getting the 415 or so rows of data containing pumpkins by the bushel. + Si imprimes los datos ahora, puedes ver que solo estás obteniendo alrededor de 415 filas de datos que contienen calabazas por fanegas. -### But wait! There's one more thing to do +### ¡Pero espera! Aún hay algo más que hacer -Did you notice that the bushel amount varies per row? You need to normalize the pricing so that you show the pricing per bushel, so do some math to standardize it. +¿Notaste que la cantidad de fanegas varían por fila? Necesitas normalizar el precio para así mostrar el precio por fanega, así que haz los cálculos para estandarizarlo. -1. Add these lines after the block creating the new_pumpkins dataframe: +1. Agrega estas líneas después del bloque para así crear el dataframe new_pumpkins: ```python new_pumpkins.loc[new_pumpkins['Package'].str.contains('1 1/9'), 'Price'] = price/(1 + 1/9) @@ -133,34 +133,34 @@ Did you notice that the bushel amount varies per row? You need to normalize the new_pumpkins.loc[new_pumpkins['Package'].str.contains('1/2'), 'Price'] = price/(1/2) ``` -✅ 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! +✅ De acuerdo a [The Spruce Eats](https://www.thespruceeats.com/how-much-is-a-bushel-1389308), el peso de una fanega depende del tipo de producto, ya que es una medida de volumen. "Una fanega de tomates, por ejemplo, se supone pese 56 libras... Las hojas y verduras usan más espacio con menos peso, por lo que una fanega de espinaca es de sólo 20 libras." ¡Todo es tan complicado! No nos molestemos en realizar una conversión fanega-a-libra, y en su lugar hagámosla por precio de fanega. ¡Todo este estudio de las fanegas de calabazas nos mostrará cuán importante es comprender la naturaleza de tus datos! -Now, you can analyze the pricing per unit based on their bushel measurement. If you print out the data one more time, you can see how it's standardized. +Ahora, puedes analizar el precio por unidad basándote en su medida de fanega. Si imprimes los datos una vez más, verás que ya están estandarizados. -✅ 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. +✅ ¿Notaste que las calabazas vendidas por media fanega son más caras? ¿Puedes descubrir la razón? Ayuda: Las calabazas pequeñas son mucho más caras que las grandes, probablemente porque hay muchas más de ellas por fanega, dado el espacio sin usar dejado por una calabaza grande. -## Visualization Strategies +## Estrategias de visualizació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. +parte del rol de un científico de datos es el demostrar la calidad y naturaleza de los dato con los que está trabajando. Para hacerlo, usualmente crean visualizaciones interesantes, o gráficos, grafos, y gráficas, mostrando distintos aspectos de los datos. De esta forma, son capaces de mostrar visualmente las relaciones y brechas de que otra forma son difíciles de descubrir. -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. +Las visualizaciones también ayudan a determinar la técnica de aprendizaje automático más apropiada para los datos. Por ejemplo, un gráfico de dispersión que parece seguir una línea, indica que los datos son un buen candidato para un ejercicio de regresión lineal. -One data visualization library that works well in Jupyter notebooks is [Matplotlib](https://matplotlib.org/) (which you also saw in the previous lesson). +Una librería de visualización de datos que funciona bien en los notebooks de Jupyter es [Matplotlib](https://matplotlib.org/) (la cual también viste en la lección anterior). -> Get more experience with data visualization in [these tutorials](https://docs.microsoft.com/learn/modules/explore-analyze-data-with-python?WT.mc_id=academic-15963-cxa). +> Obtén más experiencia con la visualización de datos en [estos tutoriales](https://docs.microsoft.com/learn/modules/explore-analyze-data-with-python?WT.mc_id=academic-15963-cxa). -## Exercise - experiment with Matplotlib +## Ejercicio - experimenta con Matplotlib -Try to create some basic plots to display the new dataframe you just created. What would a basic line plot show? +Intenta crear algunas gráficas básicas para mostrar el nuevo dataframe que acabas de crear. ¿Qué mostraría una gráfica de línea básica? -1. Import Matplotlib at the top of the file, under the Pandas import: +1. Importa Matplotlib al inicio del archivo, debajo de la importación de Pandas: ```python import matplotlib.pyplot as plt ``` -1. Rerun the entire notebook to refresh. -1. At the bottom of the notebook, add a cell to plot the data as a box: +1. Vuelve a correr todo el notebook para refrescarlo. +1. Al final del notebook, agrega una celda para graficar los datos como una caja: ```python price = new_pumpkins.Price @@ -169,39 +169,39 @@ Try to create some basic plots to display the new dataframe you just created. Wh plt.show() ``` - ![A scatterplot showing price to month relationship](./images/scatterplot.png) + ![Una gráfica de dispersión mostrando la relación precio a mes](../images/scatterplot.png) - Is this a useful plot? Does anything about it surprise you? + ¿La gráfica es útil? ¿Hay algo acerca de ésta que te sorprenda? - It's not particularly useful as all it does is display in your data as a spread of points in a given month. + No es particularmente útil ya que todo lo que hace es mostrar tus datos como puntos dispersos en un mes dado. -### Make it useful +### Hacerlo útil -To get charts to display useful data, you usually need to group the data somehow. Let's try creating a plot where the y axis shows the months and the data demonstrates the distribution of data. +Para obtener gráficas para mostrar datos útiles, necesitas agrupar los datos de alguna forma. Probemos creando un gráfico donde el eje y muestre los meses y los datos demuestren la distribución de los datos. -1. Add a cell to create a grouped bar chart: +1. Agrega una celda para crear una gráfica de barras agrupadas: ```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) + ![Una gráfica de bsarras mostrando la relación precio a mes](../images/barchart.png) - 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? + ¡Esta es una visualización de datos más útil! Parece indicar que el precio más alto para las calabazas ocurre en Septiembre y Octubre. ¿Cumple esto con tus expectativas? ¿por qué sí o por qué no? --- -## 🚀Challenge +## 🚀Desafío -Explore the different types of visualization that Matplotlib offers. Which types are most appropriate for regression problems? +Explora los distintos tipos de visualización que ofrece Matplotlib. ¿Qué tipos son los más apropiados para problemas de regresión? -## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/12/) +## [Examen posterior a la lección](https://white-water-09ec41f0f.azurestaticapps.net/quiz/12/) -## Review & Self Study +## Revisión y autoestudio -Take a look at the many ways to visualize data. Make a list of the various libraries available and note which are best for given types of tasks, for example 2D visualizations vs. 3D visualizations. What do you discover? +Dale un vistazo a las distintas forma de visualizar los datos. Haz un lista de las distintas librerías disponibles y nota cuales son mejores para cierto tipo de tareas, por ejemplo visualizaciones 2D vs visualizaciones 3D. ¿Qué descubriste? -## Assignment +## Asignación -[Exploring visualization](assignment.md) +[Explorando la visualización](assignment.es.md)