Upgrade to Pro — share decks privately, control downloads, hide ads and more …

El Agrónomo Digital - PyDay Cali 2023

Juan Roa
November 30, 2024

El Agrónomo Digital - PyDay Cali 2023

Juan Roa

November 30, 2024
Tweet

More Decks by Juan Roa

Other Decks in Science

Transcript

  1. Project members Camilo Estrella Villarreal – Ingeniero Civil y Tecnólogo

    en Atención Pre-hospitalaria de la Universidad del Valle. Consultor en Soil Net LLC / Magíster en Data Analysis y estudiante del Doctorado en Estadística Multivariante Aplicada en la Universidad de Salamanca, España. https://www.linkedin.com/in/camiloestrella/ Juan David Roa Valencia – Ingeniero de Software, contribuidor open-source en comunidades, Co-organizador de Rails Girls Cali. Investigador en Soil Net LLC / Magíster en Ciencias de la Computación de la University of Wisconsin-Whitewater, Estados Unidos. https://www.linkedin.com/in/roadev/
  2. Data Owner - Soil Net LLC Erosion and Dust control

    Solid-liquid separation Oil & Biodiesel Treatment Fiber Treatment Liquid and Solid superabsorbent Soil and Plant Analysis
  3. Data Owner - Soil Net LLC Dr. Aicardo Roa-Espinosa, CEO

    of Soil Net LLC. PhD, Biological System Engineer University of Wisconsin-Madison. Ingeniero Agrónomo Universidad Nacional de Palmira. Extensive experience in Agro-industrial R&D. Autor de +18 patentes en EEUU. https://www.researchgate.net/profile/Aicardo-Roa-Espinosa
  4. Motivación • La agricultura sigue siendo una piedra angular de

    las economías mundiales y depende en gran medida de los avances tecnológicos continuos para lograr sostenibilidad y eficiencia. • Desafíos: La industria se enfrenta a los altos costos y complejidades del análisis de nutrientes del suelo, lo que obstaculiza directamente la productividad agrícola óptima. • Al reducir los costos asociados con el análisis de nutrientes y mejorar la precisión de los datos gracias a las predicciones del rendimiento de los cultivos y la gestión del suelo, permitiendo prácticas agrícolas más innovadoras, sostenibles y sustentables con el medio ambiente.
  5. • Objetivo: Desarrollar un sistema integrado realizando Análisis de datos

    y Machine Learning para mejorar el análisis de los nutrientes del suelo. • Actividades principales: ◦ Recopilación de datos: Recopilación de datos extensos sobre el suelo de diversas fuentes para garantizar capacidades de análisis integrales. ◦ Machine Learning Application: Uso de Machine Learning para predecir con precisión los niveles de nutrientes del suelo. • Resultado: El proyecto tiene como objetivo reducir la complejidad y los costos asociados con los métodos tradicionales de análisis del suelo, lo que permite prácticas agrícolas más precisas y sustentables. Definición del proyecto
  6. 1. Data Cleaning and Processing (imputation) Understanding the available data

    and transforming it. 2. Database Design and Construction Creation of the relational database and deployment. 3. Algorithms Design and Implementation Design, implementation and selection of the most suitable machine learning model. 0. Theoretical understanding and information gathering State of the art, soil theory and complete understanding of the initial dataset and concepts. 0 1 2 3 Approach
  7. ¿Cómo obtenemos los datos? • Antes de los datos, vamos

    a adentrarnos un poco en Química Analítica :) • Identifica y cuantifica los elementos presentes en una muestra, espectrometría de masas.
  8. ¿Con qué lo hacemos? Instrumento: Quadrupole ICP-MS Método: Inductively Coupled

    Plasma Mass Spectrometry (ICP) Fabricante: Thermo Fisher Scientific Instrumento: Portable XRF S1 TITAN Método: X-ray Fluorescence Fabricante: Bruker Instrumento: MAX Cube C:N organic Método: Inductively Coupled Plasma Mass Spectrometry (ICP) Fabricante: Elementar
  9. • Pre-procesamiento de los datos de Suelo ◦ Transformación del

    dataset initial. ◦ Evaluación de datos categóricos / no numéricos. • Transformación de los datos de Suelo ◦ Análisis de imputación de datos faltantes. ◦ Construcción del primer Script de Python para transformación de datos. ◦ Análisis de preimputación. • Imputación de datos faltantes de Suelo ◦ Imputación Teórica. ◦ Implementación de algoritmos robustos de imputación. ◦ Evaluación de imputación y selección de algoritmos. Fase 1 - Data Cleaning and Processing
  10. Review and management of outliers Outliers were evaluated with 3

    statistical methods and imputed with two algorithms, the best being K-Nearest Neighbors (KNN). Correlation of the 'soil' variable The level of correlation between the categorical variable 'soil' and the other variables was evaluated. It was decided to include it in the analyses. Evaluation of missing data What type of behavior the missing data had and how it was distributed was reviewed. Imputation and evaluation 7 imputation techniques were applied in a sequence of 3 staggered imputations, choosing the best according to several evaluation methods. Final dataset The final dataset was created with the appropriate imputations for each column.
  11. variable p-value B 1.15278847820179 x 10-22 Mg 3.300040645261104 x 10-18

    P 2.925897943316241 x 10-14 S 1.697231260328347 x 10-19 Ca 2.8082234651365656 x 10-35 Cu 1.791211202442479 x 10-24 Exploración del Dataset -> Análisis de Distribución
  12. Boro (B) 62.36 % Azufre (S) 58.68 % Magnesio (Mg)

    5.83 % Calcio (Ca) 3.04 % Cobre (Cu) 0.89 % Fósforo (P) 0.13 % Potasio (K) 0 % Manganeso (Mn) 0 % Hierro (Fe) 0 % Zinc (Zn) 0 % Imputación de los datos faltantes de Suelo: Paso 2. Porcentaje de datos faltantes.
  13. • Los datos en la vida real son representados como

    matrices. ◦ Tenemos muchos datos (filas) y características (columnas) ◦ ¿Recuerdan una única matriz fácil de operar era de 2x2? ◦ De resto, una multiplicación te podía tomar horas o toda la vida… ◦ Operar (m) filas contra (n) columnas es muy costoso computacionalmente Machine Learning es mucha Álgebra Lineal + mucha Estadística
  14. La regresión Logística es usada para entender el comportamiento de

    los Datos. 1 2 1. The df_missing dataframe is created where each value is converted to binary, indicating whether the original value was absent ('1') or present ('0'), via the isnull() method, followed by .astype(int) to convert booleans into integers. 2. An empty list is initialized to store the results of the logistic regressions that will be performed for each variable as the dependent variable. Exploración del Dataset -> Naturaleza de los Datos faltantes
  15. Este bucle for itera sobre cada columna del dataframe df_missing,

    tratando a cada una como la variable dependiente en una regresión logística separada. Missing values in X are imputed using the average of the other observations in the same column. This is necessary to fit the logistic regression model as it cannot directly handle missing values. A logistic regression model is fit to the data, where X_imputed are the independent variables (with imputed values) and y is the dependent variable. liblinear: It is an algorithm based on the LIBLINEAR library, very effective for binary classification problems. It is especially good for small datasets. The log loss is calculated to evaluate the performance of the model. Log loss measures how well the model predicts the dependent variable; Lower values indicate a better fit. Exploración del Dataset -> Naturaleza de los Datos faltantes
  16. Los resultados de Log Loss son presentados para cada una

    de las variables con valores faltantes Exploración del Dataset -> Naturaleza de los Datos faltantes
  17. Se aplicó un Análisis Multivariante de Varianza al subconjunto complete_cases2

    para evaluar si existía una relación entre la variable 'soil' (categórica) y las otras variables (numéricas). Variable resultante Función MANOVA In statsmodels, the from_formula method is used to create models from formulas described in a text string. Variables dependientes Variable independiente Dataframe utilizado Exploración del Dataset -> MANOVA
  18. El resultado obtenido a través de todas las pruebas muestra

    que existe una relación entre la columna 'soil' y las variables numéricas. Exploración del Dataset -> MANOVA
  19. El dataframe inicial soil_mix_df_final es el dataframe final obtenido en

    el script etl_soil.py, después de la imputación teórica de los datos del método de análisis HHXRF sobre los datos ICP. There are two dataframes that are generated, one without all the categorical columns 'soil', 'sample' and 'rep', and another that includes the column 'soil' which contains the soil series to which the sample belongs. Preparación del Dataframe
  20. Two subsets that do not contain missing values are extracted,

    so that rows that contain at least one missing value in any of their columns are eliminated. The result is two dataframes, one of size 198x10 and the other of 198x11, the latter being the one corresponding to the dataframe that includes the 'soil' variable. Preparación del Dataframe
  21. Utilizamos los siguientes métodos para la imputación de datos faltantes:

    • Expectation-Maximization (EM) • K-Nearest Neighbors (KNN) • Linear Regression (LR) • Random Forest • Multiple Imputation by Chained Equations (MICE) • Singular Value Decomposition (SVD) Cobre 1ra imputación Calcio 1ra imputación con la columna ‘soil’ Fósforo 1ra imputación Magnesio 1ra imputación Boro 2da imputación Azufre 3ra imputación con la columna ‘soil’ Imputación de datos de Suelo
  22. La Imputación de datos faltantes fue realizada usando el método

    K-Nearest Neighbors (KNN) que viene en el paquete de Sklearn An instance of StandardScaler, a sklearn tool used to standardize features by scaling each to have mean 0 and variance 1, is created. This is especially important for algorithms like KNN, which depend on the distance between points; fit_transform fits the StandardScaler to the soil_mix_cleaned data set (calculating the mean and standard deviation of each feature) and then transforms the data set by scaling it. soil_mix_cleaned is the original data set with missing values. Primera Imputación -> KNN
  23. Specific function of the sklearn package to run the KNN.

    Indicates that the imputator should use the 5 nearest neighbors for each point with missing values when performing imputation. It means that all neighbors contribute equally to the imputed value. Parámetros de la función Primera Imputación -> KNN
  24. • Usado desde sistema de recomendación (como Netflix cuando le

    atina a películas que te pueden gustar) hasta infinidad de aplicaciones. En nuestro caso nos interesa la Reducción de Dimensión. SVD: Singular Value Decomposition
  25. Imputation of missing data is implemented using Singular Value Decomposition

    (SVD), a statistical method that decomposes a matrix into its singular factors. The library used to implement this method was fancyimpute. Creates an instance of the SoftImpute object, which implements a version of the SVD-based imputation algorithm known as Soft-Impute. This method iterates over the input matrix, gradually replacing missing values with those estimated using SVD Set the seed of NumPy's random number generator to 6 to ensure that the results are reproducible fit_transform fits the model to the data set and then transforms (imputes) the missing values in the same step. Primera Imputación -> SVD
  26. The imputation was carried out on the dataframe that included

    the categorical data column 'soil', which contains the soil series. Primera Imputación incluyendo la columna ‘soil’
  27. Before being able to execute the different imputation methods, they

    had to be organized in such a way that the algorithms could then be applied easily, taking into account that these are created for numerical data and not for categorical data. Extracts all columns containing numeric data from the DataFrame soil_mix_cleaned2. Extracts all non-numeric columns, i.e. categorical variables, from the same DataFrame. Primera Imputación incluyendo la columna ‘soil’ -> Preprocesamiento
  28. The OneHotEncoder method is used to convert categorical variables into

    a format that can be provided to machine learning algorithms, which typically require numerical input. This is a scikit-learn class used to convert categorical variables into a numerical form that can be more easily used by machine learning models. It does this by creating a new binary column for each unique category in the original column. During data transformation, it may occur that categories appear that were not present in the original data set during encoder training. By default, OneHotEncoder returns a sparse array to save memory, especially useful when there are many categories. However, by setting sparse=False, the encoder will return a dense array of NumPy. Primera Imputación incluyendo la columna ‘soil’ -> Preprocesamiento
  29. The distribution of Z scores (standardized) for the original dataset

    and the imputed datasets is calculated and graphed to find the imputation that is close to the original. Apparently the best is between SVD2, although it is difficult to say Evaluación de Imputación -> Comparación de Distribuciones
  30. Furthermore, the sum of absolute differences between the original and

    imputed correlations was calculated, with the best being NN with a sum of differences of approximately 3.65, followed by SVD with 4.24. EM 5.8749 MICE2 8.5186 EM2 5.5629 RF 8.6716 KNN 5.6883 RF2 7.6303 KNN2 7.3817 SVD 4.3149 LR 6.7866 SVD2 7.9668 LR2 4.0979 MICE 8.3963 Evaluación de Imputación -> Análisis de correlaciones
  31. La comparación de la distribución de cada una de las

    variables del subconjunto inicialmente creado sin valores faltantes se realiza contra cada variable de los diferentes métodos de imputación. Evaluación de Imputación -> Comparación con subset
  32. El promedio, la mediana y la desviación estándar fueron calculados

    para cada columna de cada método. En general, el mejor método fue: SVD2. Evaluación de Imputación -> Medidas de Tendencia y Dispersión
  33. Evaluación de Imputación -> Medidas de Tendencia y Dispersión Los

    Resultados se presentan por cada variable, incluyendo el mejor método y la menor de las sumas de las diferencias absolutas. • B: SVD con diferencia de 5.74. • Ca: KNN2 con diferencia de 22.36. • Cu: KNN con diferencia de 0.07. • Mg: SVD con diferencia de 56.31. • P: MICE con diferencia de 1.10. • S: SVD2 con diferencia de 61.07.
  34. • According to the results obtained from the 3 stepwise

    imputations, the final dataset is constructed by replacing the columns of the 6 variables that had missing values with the corresponding columns of the methods that gave the best results for each variable. 3ra imputación Resultados de la variable Azufre. 1ra imputación Resultados de las variables con menos cantidad de valores faltantes: Cobre, Calcio, Fósforo, y Magnesio. 2da imputación Resultados de la variable Boro. Imputación de datos faltantes de Suelo
  35. Conclusión De acuerdo a los resultados obtenidos de las imputación

    de 3 pasos, el Dataset final se construyó reemplazando las columnas de las 6 variables que tenían datos faltantes con los resultados correspondientes de las imputaciones. • B -> SVD de la segunda imputación. • Mg -> SVD de la primera imputación. • P -> MICE de la primera imputación. • S -> SVD2 de la tercera imputación. • Ca -> KNN2 de la primera imputación. • Cu -> KNN de la primera imputación.
  36. Diseño e implementación de Algoritmos • Aumento del tamaño del

    Dataset. ◦ Uso de Bootstrapping para el aumento del tamaño del dataset. • Machine Learning Model building (imputación) ◦ Evaluación de varios algoritmos: Decision Tree, Random Forest, Polynomial Regression, Support Vector Regression, entre otros. ◦ Elección del modelo que más se ajuste. ◦ Evaluación de otros modelos de ser necesario.
  37. Bootstrapping para incrementar tamaño del Dataset In addition to the

    two original python pandas dataframes of 789 rows (with and without the categorical variable 'soil'), three more sizes were constructed, represented in six dataframes of 1.5, 2 and 2.5 times the size of the original dataframe.
  38. Modelos de Machine Learning utilizados • K-Nearest Neighbors (KNN) •

    Linear Regression • Polynomial Regression • Lasso Regression • Ridge Regression • Singular Value Decomposition to reduce dimensionality • Support Vector Regression (SVR) • Decision Trees • Random Forest • Gradient Boost • AdaBoost
  39. Resultados del proyecto Comprensión Teórica The result of this process

    was the dataset with fewer missing values than at the beginning. Imputación The result of this process was the complete dataset, without missing values. Diseño de la base de datos Functional, scalable, and accessible database for executing queries as needed. Machine Learning The result shows that the best model applied is Random Forest
  40. Current work • Implementación del proceso para Plantas. • Software

    Development para el producto final. • Reducción de costos en el análisis elemental debido a la predicción de nutrientes y datos faltantes. • Soporte para la calibración de los instrumentos de Química Analítica. • Condiciones Climáticas.
  41. 5