scieee AI-readable full text Open interactive document viewer

Desarrollo de modelos para la identificación de variedades y fitopatologías mediante técnicas fotónicas

Borraz Martínez, Sergio

Abstract

In the cultivation of fruit trees, the most common is to work with cuttings. In this way, the grafted fruit tree variety offers specific fruit qualities and the rootstock offers certain agronomic and adaptation characteristics. The grafts that come from varieties of the same species usually present a great genetic proximity, which makes them very difficult to identify by means of agro-morphological characters. For this reason, it is necessary to implement more complex methods to be able to distinguish them. Nowadays, the most widely used methods for varietal identification are based on DNA analysis, which allow obtaining molecular profiles. However, these biomolecular techniques require sophisticated instruments and facilities, time consuming, and are expensive. These drawbacks make the implementation of molecular techniques unfeasible as methods for the routine analysis of large volumes of samples. In this context, the nursery plant sector demands a rapid, no-destructive, accurate, and economic methods. The main objective of this thesis is to develop a method that allows identifying and differentiating varieties at the nursery plant level, together with the ability to assess their physiological status. The thesis is articulated in 4 articles published in indexed journals together with essays presented in the present work. The main results are to a) Protocols have been developed for the use of near infrared spectroscopy techniques, hyperspectral camera and artificial vision coupled to deep learning in fruit cuttings and cherry rootstocks; b) Near-infrared spectroscopy proved to be a technique capable of differentiating, with a very high degree of specificity, six varieties of almond (Prunus dulcis), but it presented limitations for its implementation in a production line; c) The use of the hyperspectral camera has proven adequate for the differentiation of three rootstock varieties and the analysis of the physiological state, including the premature detection of Pseudomonas syringae; d) The use of artificial vision coupled with deep learning has proven to be effective in the differentiation of almond varieties; e) The joint analysis of the results indicates that the best solution to be implemented in a production line would go through the implementation of the spectral camera for the control of the physiological state of the plants and the artificial vision coupled to deep learning for the varietal identification.

Full text

UNIVERSITAT POLITÈCNICA DE CATALUNYA DEPARTAMENTO DE INGENIERÍA AGROALIMENTARIA Y BIOTECNOLOGÍA PROGRAMA DE DOCTORADOS INDUSTRIALES DOCTORADO EN TECNOLOGÍA AGROALIMENTARIA Y BIOTECNOLOGÍA Desarrollo de modelos para la identificación de variedades y fitopatologías mediante técnicas fotónicas Tesis presentada por Sergio Borraz Martínez Tesis realizada en el Departamento de Ingeniería Agroalimentaria y Biotecnología bajo la dirección de: Directora: D. Anna Gras Moreu Departamento de Ingeniería Agroalimentaria y Biotecnología (DEAB) Co-director: D. Joan Simó Cruanyes Fundació Miquel Agustí y DEAB Colaboración: Ricard Boqué Martí Universitat Rovira i Virgili Departamento de Química Analítica y Orgánica Colaboración: Francesc Tarrés Ruiz Universitat Politècnica de Catalunya Departamento de Teoría de la señal y comunicaciones Castelldefels, 2021 <<Nada en la vida es para ser temido, sino para ser entendido. Ahora es el momento de entender más, de modo que podamos temer menos>> Marie Curie A mi familia, porque siempre me ha apoyado Agradecimientos Agradecimientos Este proyecto no hubiera sido posible sin no hubiera contado con la ayuda y el apoyo de muchas personas, las cuales me han ayudado a mantenerme erguido ante la adversidad, y me han dado energías para avanzar. Por tanto, en las siguientes líneas, me gustaría agradecerles su ayuda durante el doctorado. A Agromillora Iberia por haberme escogido para llevar a cabo este proyecto, brindándome la oportunidad de poder crecer profesionalmente. En especial a mi tutora de tesis en la empresa, Mariàngela Mestre, y a Joan Torrents, por apostar por las nuevas tecnologías. Y como no, agradecer a todos mis compañeros/as del Centro de Materiales Iniciales, por aguantarme durante estos 3 años. También a Mireia Bordas, por su esfuerzo y apoyo, además de por todo lo que me enseñó del cultivo de plantas in vitro. A Natalia, Nora e Inma, con las que compartí mis preocupaciones, en ocasiones frustraciones, y sobre todo grandes momentos, los cuales guardo con gran cariño en mi memoria. Agradecer también a Agromillora Sur su gran hospitalidad durante los tres meses de mi estancia en Chile. A Ely Chernilo, por haberme ofrecido la oportunidad de vivir esa gran experiencia. A Natalia Torres y el resto del equipo de QA y de Producción, por todo ese trabajo (“la pega”) que realizamos juntos, el cual, entre risas y momentos para enmarcar, conseguisteis que se me hiciera mucho más ameno. A mi amigo y compañero de piso Román Toro, con el cual aprendí muchísimo de la cultura chilena, mediante nuestras extensas charlas acompañadas con un vaso de Coca-cola. Gracias por hacerme sentir como en casa, aun estando a más de 11.000 km de ella. Llegados a este syringae; d) El uso de la visión artificial acoplada a deep learning ha demostrado ser eficaz en la diferenciación de variedades de almendro; e) El análisis conjunto de los resultados indican que la mejor solución para ser implementada en una línea de producción pasaría por la implementación de la cámara espectral para el control del estado fisiológico de las plantas y la visión artificial acoplada a deep learning para la identificación varietal. Palabras clave: Espectroscopia de infrarrojo cercano, Cámara hiperespectral, Visión artificial, Deep learning, Quimiometría, Control varietal, Detección de fitopatologías, Prunus dulcis. Abstract In the cultivation of fruit trees, the most common is to work with cuttings. In this way, the grafted fruit tree variety offers specific fruit qualities and the rootstock offers certain agronomic and adaptation characteristics. The grafts that come from varieties of the same species usually present a great genetic proximity, which makes them very difficult to identify by means of agro-morphological characters. For this reason, it is necessary to implement more complex methods to be able to distinguish them. Nowadays, the most widely used methods for varietal identification are based on DNA analysis, which allow obtaining molecular profiles. However, these biomolecular techniques require sophisticated instruments and facilities, time consuming, and are expensive. These drawbacks make the implementation of molecular techniques unfeasible as methods for the routine analysis of large volumes of samples. In this context, the nursery plant sector demands a rapid, no-destructive, accurate, and economic methods. The main objective of this thesis is to develop a method that allows identifying and differentiating varieties at the nursery plant level, together with the ability to assess their physiological status. The thesis is articulated in 4 articles published in indexed journals together with essays presented in the present work. The main results are to a) Protocols have been developed for the use of near infrared spectroscopy techniques, hyperspectral camera and artificial vision coupled to deep learning in fruit cuttings and cherry rootstocks; b) Near-infrared spectroscopy proved to be a technique capable of differentiating, with a very high degree of specificity, six varieties of almond (Prunus dulcis), but it presented limitations for its implementation in a production line; c) The use of the hyperspectral camera has proven adequate for the differentiation of three rootstock varieties and the analysis of the physiological state, including the premature detection of Pseudomonas syringae; d) The use of artificial vision coupled with deep learning has proven to be effective in the differentiation of almond varieties; e) The joint analysis of the results indicates that the best solution to be implemented in a production line would go through the implementation of the spectral camera for the control of the physiological state of the plants and the artificial vision coupled to deep learning for the varietal identification. Keywords: Near-infrared spectroscopy, Hyperspectral camera, Computer vision, Deep learning, Chemometric, Varietal control, Phytopathology detection, Prunus dulcis. Abreviaciones ASCA: Analysis of variance – simultaneous component analysis CNN: Convolutional neural network CV: Computer vision CV-DL: Computer vision coupled deep learning CPs: Componentes principales DI: Doctorado industrial DL: Deep learning ELISA: Enzyme-Linked ImmunoSorbent Assay FAO: Food and Agriculture Organization HSV: Valor de saturación / Hue, Saturation, Value en inglés IA: Inteligencia artificial IoT: Internet de las cosas / Internet of the things en inglés IOA: Índice de orientación agrícola IRTA: Institut de Recerca i Tecnologia Agroalimentàries ML: Machine learning MSC: Multiplicative Scatter Correction NIR: Near infrared NIRS: Near-infrared spectroscopy NW: Norris-Williams PCA: Principal Component Analysis PCR: polymerase chain reaction PIB: Producto interior bruto PLS: Partial Least Squares PLS-DA: Partial Least Squares Discriminant Analysis PLS-R: Partial Least Squares Regression RGB: Red-green-blue RMESCV: Root Mean Square Error of Cross-Validation SG: Savitzky-Golay SGD: Stochastic Gradient Descent SIMCA: Soft independent modelling by class analogy SNP: Single nucleotide polymorphisms SNV: Standard Normal Variate UFC: Unidades formadoras de colonias VL: Variable latente VNIR: Visible – infrarrojo cercano Índice Índice Contexto ..................................................................................................................... 27 1.1 Empresa ............................................................................................................ 29 1.2 Motivación ........................................................................................................ 31 Introducción ............................................................................................................... 33 2.1 Innovación en la agricultura ............................................................................. 35 2.2 Fundamentos de las técnicas fotónicas ........................................................... 36 2.3 Fundamentos de la espectroscopia de infrarrojo cercano (NIRS) .................... 40 2.3.1 Conceptos de la vibración molecular en el infrarrojo cercano ................. 41 2.3.2 Espectro NIR .............................................................................................. 45 2.4 Cámara espectral .............................................................................................. 48 2.5 Visión artificial junto con Deep learning (CV-DL) ............................................. 53 2.5.1 Inteligencia artificial y Machine learning .................................................. 53 2.5.2 Conceptos del aprendizaje profundo o Deep learning .............................. 56 2.5.3 Arquitectura de las redes neuronales computacionales ........................... 59 2.5.4 Entrenamiento de una red ........................................................................ 64 2.5.5 Transfer learning ....................................................................................... 70 2.5.6 Aumento de datos (data augmentation) .................................................. 70 2.5.7 Arquitectura red neuronal convolucional VGG16 ..................................... 71 2.6 Análisis de datos multivariantes ....................................................................... 72 2.6.1 Métodos quimiométricos de análisis ........................................................ 74 Objetivos .................................................................................................................... 85 Capítulo 1. Development of a Methodology to Analyze Leaves from Prunus dulcis Varieties Using Near-Infrared Spectroscopy .............................................................. 89 Capítulo 2. Multivariate Classification of Prunus dulcis Varieties Using Leaves of Nursery Plants and Near-Infrared Spectroscopy ...................................................... 101 Capítulo 3. Diferenciación varietal y control del estado fisiológico mediante cámara hiperespectral .......................................................................................................... 113 Capítulo 4. Varietal Quality Control in the Nursery Plant Industry Using Computer Vision and Deep Learning Techniques ..................................................................... 129 Capítulo 5. Combining Computer Vision and Deep Learning to Classify Varieties of Prunus dulcis for the Nursery Plant Industry ........................................................... 143 Discusión .................................................................................................................. 155 4.1 Espectroscopia de infrarrojo cercano ............................................................ 157 4.2 Cámara hiperespectral .................................................................................. 161 4.3 Visión artificial junto Deep learning (CV-DL) ................................................. 165 4.4 Aplicación de los métodos estudiados .......................................................... 168 4.5 Nivel de maduración tecnológica .................................................................. 170 Conclusiones ............................................................................................................ 173 Bibliografía ............................................................................................................... 177 Contexto Desarrollo de modelos mediante técnicas fotónicas 35 Introducción 2.1 Innovación en la agricultura La Food and Agriculture Organization (FAO) [14] considera de vital importancia la inversión en innovación en el sector agrícola para intensificar la producción agrícola de manera sostenible, además de una pieza clave para lograr acabar con el hambre y la malnutrición en el mundo. Es tal la importancia de la investigación, desarrollo e implementación de nuevos sistemas productivos que permitan mejorar el rendimiento y la eficiencia del sector agrícola, que hace que estos formen parte de los objetivos sobre el desarrollo sostenible incluidos en la agenda 2030 [15]. Por lo tanto, para poder afrontar los retos, presentes y de futuro, es indispensable la continua actualización del sistema productivo agrícola. Actualmente, se está produciendo una modernización del sector agrícola, impulsada por la innovación y la incorporación de tecnologías emergentes. Tal es así, que se habla de la cuarta revolución agrícola o de la agricultura 4.0 [16]. Este cambio viene impulsado por la introducción en el sector de tecnologías emergentes como el Internet de las cosas (IoT), la computación en la nube, la robótica, la inteligencia artificial (IA) o el Big Data [17–20]. Además, este desembarco tecnológico se ve favorecido por encontrar, en el sector agrícola, un fértil campo donde poder extenderse y echar raíces, ya que posibilidades y nichos de implantación no le faltan. Agrupados bajo el paraguas de la agricultura inteligente o agricultura digital, están surgiendo aplicaciones en áreas tan diversas como en el control de plagas [21], en la optimización en el uso de pesticidas y herbicidas [22], en la elección de la fecha óptima de siembra [23], la monitorización de cultivos mediante el uso de vehículos aéreos no tripulados (agricultura de precisión) [24–26], la implementación del big data en agricultura [27,28]. También se están abriendo un hueco las ciencias robóticas mediante la utilización de robots para cosechar productos que hasta ahora Introducción 36 solo podían ser cosechados a mano [29,30]. La mayor parte de estas tecnologías se basan en el continuo monitoreo de los cultivos con el fin de obtener una gran cantidad y variedad de datos que permitan tener un conocimiento más profundo del estado del cultivo. Además, el análisis de dichos datos se emplea para interpretar el presente y, de esta forma, intentar predecir el futuro, y así poder tomar decisiones más precisas y oportunas [31]. A pesar de los grandes beneficios de la innovación, es importante tener en cuenta que también puede acarrear efectos negativos. De esta forma, la tecnología es un arma de doble filo porque tiene el potencial de causar daño, además de proporcionar beneficios [32]. La mayor parte de las consecuencias negativas hacen referencia a cuestiones sociales y medioambientales [18]. Por ello, es importante apostar por una innovación sostenible. Un aspecto que puede poner en peligro la revolución de la agricultura 4.0 es la reducción en la financiación pública. Tal y como se muestra en el informe Seguimiento de los progresos relativos a los indicadores de los ODS relacionados con la alimentación y la agricultura correspondientes a 2020 [33] realizado por la FAO, el gasto público en agricultura ha disminuido en la mayoría de las regiones del mundo desde el año 2000. El índice de orientación agrícola (IOA) para los gastos públicos, el cual compara la contribución a la agricultura por parte del país con la contribución al PIB del sector, muestra que del 2001 a 2018, el IOA para los gastos públicos cayó del 0,42 al 0,28 en todo el mundo [33]. Por lo tanto, para una plena consolidación de la agricultura 4.0 en todo el sector, es necesario revertir esta situación. 2.2 Fundamentos de las técnicas fotónicas En el presente estudio, se han aplicado diferentes técnicas que van desde la espectroscopia de infrarrojo cercano (Near infrared spectroscopy, NIRS) hasta la visión artificial (Computer vision, CV), incluyendo la utilización de imágenes hiperespectrales. Pese a que se tratan de técnicas distintas, pertenecientes a campos Desarrollo de modelos mediante técnicas fotónicas 37 de la ciencia diferentes, todas ellas tienen en común los mismos principios de interacción entre la radiación electromagnética y la materia. En lo que realmente se diferencian es en la manera en la que se estudia y se observa dicha interacción. En la espectroscopia se obtiene un espectro, en la visión artificial se trabaja con una imagen y mediante las cámaras espectrales se obtiene un cubo de datos que contiene información de la imagen y del espectro al mismo tiempo. Para poder entender mejor los fundamentos teóricos de las técnicas empleadas, es importante tener presente los conceptos básicos que se exponen a continuación, los cuales son comunes para todas ellas. Radiación electromagnética La radiación electromagnética es una forma de energía que se compone de ondas electromagnéticas. Según la teoría electromagnética de Maxwell [34], las ondas electromagnéticas surgen de la combinación de un campo eléctrico y un campo magnético que oscilan en planos individuales dispuestos perpendicularmente el uno del otro. Ambos campos oscilan en fase y se propagan como una onda sinusoidal. Por otra parte, la mecánica cuántica describe las ondas electromagnéticas como una combinación de onda y partícula (fotón) [35], ya que, en base a esta rama de la física, las ondas electromagnéticas presentan un comportamiento dual [36]. Las propiedades de la radiación electromagnética vienen definidas por tres factores: La frecuencia (), la longitud de onda (λ) y la energía de un fotón (E) [37]. ➢ La frecuencia es el número de ciclos de onda por unidad de tiempo. = 𝑐 𝜆 (1) ➢ La longitud de onda es la distancia entre dos máximos consecutivos de la onda. 𝜆= 𝑐 𝑓 (2) Introducción 38 ➢ La energía de un fotón depende de la frecuencia de la onda electromagnética. 𝐸= ℎ𝑐 𝜆=ℎ (3) donde c es la velocidad de la luz en el vacío (299,792,458 m/s) y h es la constante de Planck (6,62607015 · 10−34 J·s). Las ondas electromagnéticas se clasifican y agrupan en base a su frecuencia o longitud de onda, formando lo que se conoce como el espectro electromagnético. La longitud de onda (wavelength en inglés) es una unidad de distancia, que normalmente se expresa en múltiplos o submúltiplos del metro. No obstante, otra unidad comúnmente utilizada es el número de onda (wavenumber en inglés), que consiste en el número de ondas en una longitud de un centímetro y se expresa como cm-1. La Figura 2 muestra el espectro electromagnético, el cual va desde los rayos gamma, las ondas con mayor frecuencia, menor longitud de onda y mayor energía, hasta las ondas de radio, las cuales tiene poca frecuencia, gran longitud de onda y poca energía. Se conocen múltiples formas de interacción entre la radiación y la materia, la mayoría de ellas se encuentran descritas gráficamente en la Figura 3 [37]. De todas Figura 2. Espectro electromagnético. Fuente: Imagen de internet libre de licencia. Desarrollo de modelos mediante técnicas fotónicas 39 ellas, las únicas dos interacciones que generan un cambio en el estado energético de la materia son la absorción y la emisión de radiación, ya que en ambas se produce un fenómeno de transferencia de energía. Por otro lado, la suma del conjunto de interacciones radiación – materia, dentro del rango electromagnético del visible, es lo que da lugar a la imagen. Todas las interacciones aportan información sobre la composición y estructura de la materia [38]. Dependiendo de la técnica empleada se estudian una o varias de estas interacciones. En el presente estudio, las tecnologías de espectroscopia de infrarrojo cercano y la cámara espectral se basan en la detección de la reflectancia, ya que la fuente de radiación y el detector se encuentran en el mismo lado del objeto investigado (geometría de reflexión). En el caso de la espectroscopia de infrarrojo cercano, a partir del espectro de reflectancia se calculó el de absorbancia (4), con el cual se trabajó, mediante la siguiente transformación: 𝑎𝑏𝑠=log ( 1 𝑅𝑒𝑓𝑙𝑒𝑐𝑡𝑎𝑛𝑐𝑖𝑎) (4) Por lo que respecta a la cámara espectral, se empleó directamente el espectro de reflectancia. En cambio, mediante la cámara digital empleada en la visión artificial, se trabajó con la transmitancia, debido a que el detector se encontraba en el lado opuesto al de la fuente de luz (geometría de transmisión). Figura 3. Posibles interacciones entre un objeto y una onda electromagnética [37]. Introducción 40 2.3 Fundamentos de la espectroscopia de infrarrojo cercano (NIRS) La espectroscopia estudia la interacción entre la radiación electromagnética y la materia con la finalidad de poder analizar y explicar dichas interacciones. En el caso de la espectroscopia de infrarrojo cercano se emplea el rango de longitudes de onda que van des del final del espectro visible (Vis), 780 nm (12500 cm-1), hasta el inicio de la región del infrarrojo medio (MIR), 2500 nm (4000 cm-1). Dicha región recibe el nombre de infrarrojo cercano (NIR). La espectroscopia NIR se caracteriza por ser una técnica rápida, económica y no destructiva. Aunque en ocasiones puede ser aconsejable, no requiere el procesado de la muestra ni la adición de ningún tipo de sustancia [39–41]. La región del infrarrojo fue descubierta en el año 1800 por Fredrick William Herschel mediante un sencillo experimento, en el cual se generaba la difracción de la luz mediante un prisma [42]. Herschel midió la temperatura de las diferentes bandas del espectro visible, observando que esta iba en aumento a medida que se desplazaba de la región del azul hacia la banda del rojo. Al observar este incremento de temperatura, prosiguió con las mediciones. De esta forma, descubrió que la medición de la temperatura alcanzaba su máximo en una región superior a la banda del rojo, fuera del espectro visible. Herschel acababa de descubrir que la energía del sol no sólo se limitaba al espectro visible (lo que podemos ver) [43]. Esto no sólo supuso el descubrimiento de la región del infrarrojo, sino que además marcó el punto de partida para el descubrimiento del resto de regiones del espectro electromagnético [43]. No obstante, no fue hasta llegada la segunda mitad del siglo XX, cuando la espectroscopia de infrarrojo cercano experimentó un gran impulso, gracias especialmente a los trabajos desarrollados por Karl Norris, juntamente con las importantes contribuciones de Williams [44], McClure [45] y Shenk [43,46,47]. Actualmente, la espectroscopia de infrarrojo cercano se encuentra presente en Desarrollo de modelos mediante técnicas fotónicas 41 numerosos sectores, en los que se emplea para diversos usos. Por ejemplo, en la industria farmacéutica [48–50] y petroquímica [51,52], en el sector agrícola [53–55] y, también, en el sector sanitario [56–58], entre muchos otros. Asimismo, hoy en día existen en el mercado una amplia variedad de equipos NIR, tanto instrumentos más precisos de uso restringido en el laboratorio, como equipos portátiles o de uso onsite y on-line con capacidad para ser utilizados en ambientes más extremos [59], lo que facilita su implementación en múltiples ambientes. La absorción de radiación electromagnética dentro de este rango genera un cambio en el estado energético de la molécula, el cual se traduce en un cambio en el estado vibracional de los enlaces atómicos que constituyen dicha molécula [60]. De esta forma, se define una relación entre el estado energético y el estado vibracional. Para entender los fundamentos de la espectroscopia de infrarrojo cercano y, de esta forma, poder realizar una correcta interpretación de los espectros resultantes, es necesario comprender los elementos o conceptos básicos de la espectroscopia vibracional. 2.3.1 Conceptos de la vibración molecular en el infrarrojo cercano Se denomina vibración molecular al movimiento de los átomos que conforman la molécula, dentro de un rango definido por las particularidades de los átomos que constituyen los enlaces covalentes que dan forma a dicha molécula. En este tipo de enlaces se produce la compartición de uno o más electrones entre los dos átomos que conforman el enlace. Además, hay átomos que tienen la capacidad de atraer con más fuerza hacia su órbita a los electrones compartidos en el enlace covalente, los cuales reciben el nombre de átomos electronegativos. Por el contrario, los átomos que tienen menor capacidad de atracción de los electrones compartidos reciben el nombre de elementos electropositivos. Este fenómeno genera la formación de un potencial de carga en el enlace, dando lugar a un dipolo. De esta forma, se genera un ambiente más electronegativo alrededor del átomo más electronegativo, y un Introducción 42 ambiente más electropositivo en el entorno del átomo electropositivo. La intensidad o magnitud del potencial del dipolo recibe el nombre de momento dipolar, el cual se encuentra en continuo cambio debido a las vibraciones de los enlaces químicos. Cuando el dipolo se forma a nivel de enlace se habla de dipolo local, en cambio a escala molecular se habla de molécula polar (momento dipolar netos). Durante la vibración, los átomos de un enlace se aproximan y se alejan el uno al otro de manera cíclica. En la Figura 4 se ilustra este movimiento. Esto genera que la energía potencial cambie continuamente, haciéndose máxima cuando los átomos se encuentran en el punto de mayor proximidad debido a las fuerzas de repulsión, y también en el punto de mayor distanciamiento entre ambos como consecuencia de las fuerzas de atracción. En cambio, se alcanza un punto de energía próximo a cero cuando los átomos se encuentran a la distancia de equilibrio [61]. De esta forma, el movimiento de los átomos en la molécula está confinado dentro de un pozo de potencial descrito gráficamente en la Figura 5. Figura 4. Movimiento de un enlace covalente en una molécula diatómica heteronuclear [60]. Desarrollo de modelos mediante técnicas fotónicas 43 La frecuencia vibracional de las moléculas depende del estado energético de las mismas y, además, no cambia de manera continua, sino todo lo contrario. La variación se da de forma discontinua, saltando de una frecuencia vibracional discreta a otra (cuanto o quantum), sin pasar por las frecuencias intermedias, dando lugar a lo que se conoce como estados vibracionales. Estos estados vibracionales se definen como estados energéticos cuánticos [60,62]. La forma más precisa de describir el movimiento vibracional de un enlace es mediante el modelo de oscilador no armónico [63] ya que, como se observa en la Figura 5, los potenciales de energía no son simétricos a ambos lados del punto de equilibrio (punto de menor energía del enlace) ni la distancia energética entre estados vibracionales contiguos es siempre la misma (a mayor energía los estados vibracionales se encuentran más juntos). Esto se debe a la existencia de fuerzas que influyen en la vibración, como la repulsión coulómbica entre los núcleos de los átomos y la disociación del enlace, ambas contempladas en el modelo de oscilador no armónico [61]. Figura 5. Energía potencial en el modelo del oscilador no armónico. Modificación [61] Introducción 50 dos de ellas son espaciales y conforman el plano de la imagen. La tercera dimensión se genera por el propio apilamiento de las imágenes y es la que contiene la información espectral [93]. Para obtener el espectro de una región particular de la imagen (muestra analizada), lo que se hace es graficar la intensidad de los píxeles de la región seleccionada en cada una de las imágenes que conforma el hipercubo, o lo que es lo mismo, en cada una de las bandas espectrales. De esta forma, se obtiene un gráfico en dos dimensiones del espectro de reflectancia de la región seleccionada, donde el eje de ordenadas representa la intensidad de píxel y el de abscisas la longitud de onda. Se pueden distinguir dos tipos de cámaras espectrales en función del número de bandas en las que trabajen: • Cámaras multiespectrales: miden como máximo en 10 bandas del espectro. En este tipo de cámaras, por lo general, las bandas son anchas (varias longitudes de onda) y el rango de longitudes de onda puede ser discontinuo [93]. Figura 7. Ejemplo de un cubo de datos de una imagen hiperespectral. Cada píxel consta de un espectro de reflectancia completo en su posición [177]. Desarrollo de modelos mediante técnicas fotónicas 51 • Cámaras hiperespectrales: miden en más de 10 bandas del espectro. Pueden trabajar en cientos de bandas estrechas que cubren un rango continuo de longitudes de onda. También se distinguen varios tipos de cámaras espectrales dependiendo de la forma en la que se adquieren los datos [76,94] (Figura 8): • Whisk-broom o barrido de puntos: adquiere todas las bandas a la vez píxel por píxel moviendo el detector en el plano xy. El inconveniente más destacado es la lentitud en la adquisición de datos. • Push-broom o barrido de líneas: en lugar de un escaneo basado en píxeles, se adquiere una secuencia de píxeles que forman una línea. La adquisición de las bandas espectrales se realiza al unísono. El escaneo de la muestra se realiza por el desplazamiento de la cámara por encima de la muestra o viceversa a lo largo de una dimensión espacial (x en el ejemplo de la Figura 8). Este método se caracteriza por ser más simple y proporcionar una mayor relación señal/ruido. El principal inconveniente es que debe usarse un tiempo de exposición lo suficientemente corto para evitar el riesgo de inconsistencias a nivel de las bandas espectrales (saturación o subexposición). • Barrido de planos o escaneo de longitud de onda: Mantiene fijo el campo de visión de la imagen, es decir, no hay desplazamiento ni de la cámara ni de la muestra. Para construir el cubo espectral se adquiere una imagen monocromática de dos dimensiones espaciales (x, y) del campo de visión completo en una sola longitud de onda a la vez. Este proceso se repite sucesivamente para el resto de las longitudes de onda. Cabe destacar que este método no es adecuado para entornos en movimiento. • Full-Field o disparo único: este método adquiere todos los datos espaciales y espectrales a la vez. Es el más moderno de todos y se encuentra aún en desarrollo. Su principal desventaja es la baja resolución espacial. Introducción 52 En el presente estudio se utilizó una cámara hiperespectral VNIR (visible e infrarrojo cercano) de tipo push-broom capaz de medir 120 bandas dentro del rango de 400 a 1000 nm, con lo cual incluye toda la región del visible y la primera parte de la del infrarrojo cercano. La absorción de energía en la región del espectro visible causa cambios energéticos a nivel de electrones, a diferencia del infrarrojo cercano, en el cual los cambios son a nivel de estados vibracionales. El proceso es similar al explicado anteriormente para la espectroscopia vibracional. Cuando una molécula absorbe radiación en el espectro visible, pasa de un estado energético basal a uno de mayor energía, llamado estado de excitación. Esto sucede porque la energía absorbida genera que un electrón pase a un estado de valencia superior. Los diferentes estados energéticos son característicos de cada molécula, lo cual define el espectro de absorción. Es importante recordar que para que se produzca un cambio en el estado energético, la radiación incidente debe aportar una energía equivalente a la distancia energética entre los diferentes estados. Una vez la molécula se encuentra excitada, Figura 8. Modos de adquisición de datos hiperespectrales: ( A ) representa el modo whisk-broom o barrido de punto; en ( B ) representa el modo push-broom o de barrido de línea; ( C ) corresponde al modo de barrido de planos; (D) representa el modo disparo único [76]. Desarrollo de modelos mediante técnicas fotónicas 53 esta retorna a su estado energético basal mediante la emisión o transmisión de energía. Al trabajar con material vegetal, los espectros resultantes dependen en gran medida de la interacción de la radiación incidente con los pigmentos de la planta, aunque también influyen otros aspectos, como la estructura de la propia hoja. 2.5 Visión artificial junto con Deep learning (CV-DL) La visión artificial, también denominada visión por computador, consiste en adquirir, procesar y analizar, mediante ordenadores, imágenes del mundo real con la finalidad de que estos puedan interpretar dichas imágenes y ejecuten una respuesta autónomamente en base a dicha interpretación. Los datos que emplea la visión artificial son imágenes, ya sean fotografías, imágenes en vídeo, escáneres, etc. La visión artificial conjuga varios procesos concatenados, siendo las fases de análisis e interpretación de los datos donde entra en juego la inteligencia artificial. 2.5.1 Inteligencia artificial y Machine learning La Inteligencia artificial (IA) surgió en la década de 1950 y se puede definir como el esfuerzo de automatizar tareas intelectuales normalmente realizadas por humanos [95]. No obstante, en la década del 1940 ya existían las primeras técnicas basadas en redes neuronales (neural networks, NN), las cuales fueron abandonadas a finales de la década de 1960. Desde su aparición, la inteligencia artificial ha experimentado varias oleadas de interés y optimismo, seguidas de decepción y abandono [96]. Hasta finales de la década de 1980, la IA se basaba en reglas creadas por programadores (programas), mediante las cuales, el programador definía cual debía ser la respuesta del sistema para cada situación [97]. Es lo que se conoce como programación clásica o Symbolic AI. Se creía que con la creación de un número suficiente de reglas se podía simular el pensamiento humano. Este planteamiento era Introducción 54 adecuado para resolver problemas lógicos bien definidos, pero era insuficiente para afrontar problemas más complejos, como el reconocimiento de voz o la clasificación de imágenes. Esto favoreció la aparición, en la década de 1990, de un nuevo enfoque denominado machine learning [95]. El machine learning (ML) se basa en introducir datos, junto con la respuesta que se espera, de manera que sea el propio sistema el que defina como procesar la información (las reglas) para lograr el resultado deseado. Posteriormente, dichas reglas pueden ser aplicadas a nuevos datos. De esta forma el sistema es entrenado en lugar de programado [95,97]. La Figura 9 muestra gráficamente las diferencias principales entre la programación clásica y el machine learning. Por esta razón, es a partir de este punto cuando ya se habla de aprendizaje automático. Para lograr un correcto entrenamiento del sistema, este debe recibir mucha información en forma de ejemplos de entradas y de salidas, de manera que se encuentre una estructura estadística en estos ejemplos que finalmente permita que el sistema genere reglas para automatizar la tarea. Para poder crear modelos de machine learning, son necesarios tres elementos [95]: • Datos de entrada: son los datos de ejemplo que se van a emplear para entrenar el modelo, los cuales conforman la matriz X. Figura 9. Comparación conceptual entre la programación clásica y el machine learning [95]. Desarrollo de modelos mediante técnicas fotónicas 55 • Ejemplos de las salidas esperadas: la respuesta esperada a los datos de entrada. Corresponde a la matriz Y. • Una manera de medir si el modelo está trabajando bien La clave del machine learning es que el sistema “aprenda” a transformar o procesar los datos de entrada con el objetivo de obtener representaciones de los mismos (datos transformados) que ayuden a encontrar una relación con la salida esperada. Una representación es una forma diferente de ver los datos (representarlos o codificarlos) [95]. Por ejemplo, una imagen se puede representar en formato rojoverde-azul (RGB, por sus siglas en ingés) o en formato de matiz, saturación e intensidad (HSV, por sus siglas en inglés). Dependiendo de la tarea que se deba desarrollar, una representación puede ser más útil que otra. Los modelos de machine learning tienen que encontrar las representaciones de los datos más adecuadas para el caso de estudio. En el contexto del machine learning la palabra “aprender” (learning) describe el proceso automático de búsqueda de las representaciones más adecuadas. Esta búsqueda se realiza dentro de un conjunto de operaciones predeterminadas (proyecciones lineales, translaciones, operaciones no lineales, etc.) denominadas espacio de hipótesis [95]. A partir de este punto, han ido surgiendo nuevos métodos de aprendizaje automático, todos ellos basados en los conceptos desarrollados en el machine learning. Uno de los más importantes es el aprendizaje profundo o Deep learning. La Figura 10 ilustra la relación entre inteligencia artificial (IA), machine learning (ML) y deep learning (DL). Figura 10. Relación entre Inteligencia artificial (IA), Machine learning (ML) y Deep learning (DL) [96]. Introducción 56 2.5.2 Conceptos del aprendizaje profundo o Deep learning El deep learning es un subcampo específico dentro del machine learning, de forma que todo lo anteriormente explicado sobre el machine learning es totalmente aplicable al deep learning. El deep learning fue desarrollado en la década del 2010, gracias principalmente a las aportaciones de Geoffrey E. Hinton, Yoshua Bengio y Yann LeCunn [98], con la finalidad de incrementar el potencial de las representaciones de los datos originales. Por ello, se caracteriza por presentar una arquitectura de red neuronal computacional, la cual consiste en capas sucesivas e interconectadas de neuronas computacionales en las que se realizan representaciones de los datos de entrada. Tal y como se puede observar gráficamente en la Figura 11, cada capa se nutre de las transformaciones realizadas por la capa anterior, esto implica que a medida que nos adentramos en las sucesivas capas de la red neuronal, se alcanza un nivel de abstracción superior (mayor transformación de los datos de entrada). Los datos son introducidos dentro de la red neuronal a través de la capa de entrada. La capa de salida es la que reporta la respuesta. Las capas del centro reciben Figura 11. Ejemplo de red neuronal computacional [96]. Desarrollo de modelos mediante técnicas fotónicas 57 el nombre de capas ocultas y son las encargadas de procesar los datos de entrada. En la actualidad, no existe un consenso claro por lo que respecta al número de capas que una red neuronal ha de tener. Si bien es verdad que al incrementar el número de capas se aumenta el nivel de procesamiento de los datos, lo que es favorable para las tareas más complejas. Esto a su vez puede ser negativo debido a que aumenta el número de parámetros dificultando la correcta convergencia de la red. Los datos de entrada son transformados por las neuronas computacionales, las cuales se tratan de funciones no lineales que reciben el nombre de funciones de activación. La función de activación recibe unas entradas (xi), cada una de ellas es multiplicada por un peso específico (wi). A la suma de los productos resultantes (zj=∑xijwi) se le añade un sesgo o bias (b). Esto da como resultado la salida de la función, también denominada activación (yj) [97]. Esta es transmitida, como entrada, al siguiente grupo de neuronas a las que está conectada. La Figura 12 muestra un ejemplo de neurona computacional, también llamada Perceptrón. Figura 12. Ejemplo de neurona computacional [96]. Introducción 58 Durante la fase de entrenamiento, se denomina aprendizaje del modelo a la búsqueda de los valores para los parámetros, pesos y sesgo, que dan lugar a las representaciones más útiles. Por consiguiente, el valor de dichos parámetros representa lo que ha aprendido la neurona hasta ese momento. Una vez se tiene un modelo entrenado, si se analizan las neuronas por separado, se puede ver que cada neurona realiza una parte de la tarea global realizada por la red neuronal. Además, cada neurona aprende de manera autónoma a realizar esa tarea. Los tipos de función de activación más utilizados son la sigmoidal, Tanh y la ReLu. Incluso existe un tipo de función de activación que está diseñada específicamente para ser colocada en la capa de salida de la red neuronal, la softmax. • Sigmoidal: permite reducir valores extremos, los cuales se relacionan con valores atípicos (outliers), pero sin eliminarlos. Además, hace que la salida se encuentre entre 0 y 1. 𝑆(𝑥)= 1 1+𝑒−𝑥 (6) donde x es el valor de entrada. • Tangente hiperbólica o Tanh: es similar a una sigmoide, con la diferencia que esta función se encuentra comprendida entre 1 y -1. La ventaja de Tanh respecto a la sigmoide, es que puede trabajar más fácilmente con valores negativos. 𝑡𝑎𝑛ℎ(𝑥)=sinh(𝑥) cosh(𝑥) (7) donde x es el valor de entrada, 𝑠𝑖𝑛ℎ (𝑥) y 𝑐𝑜𝑠ℎ (𝑥) son el seno y el coseno hiperbólicos, respectivamente, de la entrada x. • Rectified Linear Unit o ReLu: la particularidad de esta función es que activa el nodo si la entrada supera cierto umbral. Este umbral se suele establecer en Desarrollo de modelos mediante técnicas fotónicas 59 0. De esta forma, si la señal es inferior a cero, no se activa, pero si es superior a cero genera una salida. Actualmente, es una función muy utilizada. 𝑅𝑒𝐿𝑢(𝑥)=max(0,𝑥)={0 𝑝𝑎𝑟𝑎 𝑥<0 𝑥 𝑝𝑎𝑟𝑎 𝑥≥0 (8) donde x es el valor de entrada • Softmax: Esta función está acotada entre 0 y 1, e indica la probabilidad con la que ha realizado la predicción. 𝑆𝑜𝑓𝑡𝑚𝑎𝑥(𝑦)𝑗=𝑒𝑦𝑗 ∑(𝑒𝑦𝑘) 𝐾 𝑘=1 (9) donde 𝑦𝑗 es una de las salidas de la capa de salida sobre la cual queremos calcular el porcentaje, 𝑦𝑘 son todas las salidas de la capa de salida y K es el número de clases. Es importante destacar que la función de activación f(z) no puede ser lineal porque de ser así se limitaría la capacidad de procesamiento de la red, debido a que, si se encadenan y se suman múltiples regresiones lineales, el resultado final es una regresión lineal, de manera que esto equivaldría a que nuestra red neuronal colapsara mostrando el comportamiento de una sola capa de neuronas. 2.5.3 Arquitectura de las redes neuronales computacionales A nivel de arquitectura de las redes neuronales, es conveniente hablar de los dos tipos arquitectura que han sido empleadas en el presente estudio. Se tratan de las redes neuronales densamente conectadas (Densely connected networks) y de las redes neuronales convolucionales (Convolutional neural networks o CNNs). Redes densamente conectadas (Densely connected networks) Las redes densamente conectadas presentan una estructura clásica en donde cada neurona de una capa se encuentra conectada con todas las neuronas de la Introducción 66 • Learning rate: es un valor que ayuda a ajustar la velocidad a la que el modelo se desplaza por la función de loss, o lo que es lo mismo, la magnitud del ajuste de los parámetros del modelo. Para ello, se multiplica el valor del gradiente por el valor de la learning rate, dando lugar a la magnitud de ajuste de los parámetros. Si la learning rate es grande, el proceso de aprendizaje se acelera, pero se corre el riesgo de que, al aproximarnos a un mínimo, el modelo salte al otro lado del mismo, entrando en un bucle de saltos alrededor del mínimo sin que este sea alcanzado o incluso provocando la divergencia del algoritmo. • Momentum: su función es intentar evitar que el entrenamiento del modelo quede atrapado en un mínimo local. Para ello, calcula el promedio ponderado de los pasos anteriores para obtener así cierta inercia que le permita salir y no quedarse atascado en pequeños mínimos locales. Mediante esta serie de argumentos se define cómo va a ser el entrenamiento, lo cual posteriormente tiene su repercusión en el éxito del mismo y, por tanto, del modelo. El aprendizaje de una red neuronal se puede definir como un proceso iterativo, del cual podemos distinguir tres fases [95,96]: 1. Forwardpropagation: se introducen los datos a través de la capa de entrada. Luego se comparan las predicciones del modelo con las salidas esperadas. En base a esto se calcula el error de predicción mediante la función de loss (Figura 16). La función de loss es uno de los parámetros requeridos para cuantificar lo cercano que está una determinada red neuronal de su ideal durante el proceso de entrenamiento. Mediante el proceso de entrenamiento se busca reducir ese error y aproximarlo lo más posible a cero (mínimo de la función de loss). Para lograrlo es necesario conocer donde se ha equivocado la red para poder reducir el error, el cual se promedia usando todas las muestras de un batch. Desarrollo de modelos mediante técnicas fotónicas 67 2. Backpropagation: consiste en propagar, a través de la red, el valor de la loss en dirección opuesta al recorrido realizado por las muestras. Es decir, se empieza por la capa de salida y se avanza hacia la capa de entrada. Hay que tener en cuenta que debido a que una capa trabaja con las salidas de la capa anterior, el error se debe ir asignando en base a la contribución relativa que haya aportado cada neurona a la salida original. De esta forma a cada neurona de la red se le asigna un valor de loss que describe su contribución relativa al error total. 3. Ajuste de los parámetros de la red: Una vez se conoce la contribución de cada neurona al error total, se realiza el ajuste de los parámetros de cada neurona en base a la loss asignada mediante la acción del algoritmo de optimización. En el caso de las capas convolucionales, este ajuste se da a nivel de filtro (todas las neuronas de un mismo filtro comparten los mismos parámetros). De esta forma, aquellos filtros que hayan contribuido más al error global de la red neuronal experimentarán un mayor ajuste de sus parámetros. El funcionamiento del optimizador se basa en calcular la derivada de la función de loss en el punto que nos encontramos, lo que nos da el gradiente de la función (Figura 16). A continuación, se realiza un ajuste de los parámetros en la dirección que nos permita ir bajando por la función de loss hasta alcanzar el mínimo local más cercano, es decir, mínimo error. Es preferible hablar de mínimo local en lugar de mínimo absoluto porque la función de loss es muy compleja y no se puede calcular en su totalidad, sino que únicamente podemos saber su pendiente en el punto en el que nos encontramos. Por lo tanto, nunca se sabe con total seguridad si se trata de un mínimo local o global. Este proceso se realiza de forma iterativa hasta lograr los mejores resultados posibles. La Figura 17 resume el proceso de entrenamiento anteriormente descrito. Introducción 68 Se debe evitar realizar un entrenamiento excesivo de la red neuronal. Ya que esto podría ocasionar que los parámetros se ajustaran excesivamente bien a las muestras de entrenamiento, llegando aprender aspectos muy específicos de las mismas, pero Figura 16. Proceso de entrenamiento representado sobre una función de loss ideal [96]. Figura 17. Esquema del entrenamiento de una red neuronal [95] Desarrollo de modelos mediante técnicas fotónicas 69 poco relevantes para la caracterización de la clase. Como consecuencia de ello, se reduciría la capacidad de clasificar correctamente nuevas muestras. Es lo que se denomina overfitting o sobreajuste [99], el cual se encuentra representado gráficamente en la Figura 18. La aparición del overfitting causa un incremento repentino en el error de la validación durante el entrenamiento. Existen una serie de técnicas llamadas regularizadores, las cuales ayudan a evitar el overfitting. Una de ellas es el conocido como dropout [100], el cual consisten en eliminar aleatoriamente (establecer a cero) una serie de características de la salida de una capa neuronal durante el entrenamiento. Por ejemplo, si una capa presenta un vector de salida [0.2, 0.5, 1.3, 0.8, 1.1] para una imagen determinada, al aplicar dropout varios de los valores del vector escogidos aleatoriamente se transforman en ceros, [0, 0.5, 1.3, 0, 1.1]. La tasa de dropout hace referencia a la fracción de valores que se transforman en ceros. Por lo general esta se establece entre 0.2 y 0.5 [95]. Esta asignación aleatoria de ceros se modifica al final de cada batch. Figura 18. Representación gráfica de la aparición de overfitting durante el entrenamiento de una red neuronal computacional [95]. Introducción 70 2.5.5 Transfer learning Al empezar a entrenar una red neuronal desde cero (scratch), los parámetros suelen tener un valor aleatorio, de manera que su optimización requiere de un largo y arduo proceso iterativo. Además, es necesario disponer de un gran número de datos. En muchos casos, no es posible cumplir ambos requisitos. Para estos casos existe un método llamado transfer learning [99,101], el cual nos permite descargar una red neuronal junto con sus parámetros ya entrenados. Luego, únicamente es necesario realizar pequeños ajustes de estos para adaptarlos a la nueva tarea que se quiera realizar. Además, este método permite mejorar los resultados del modelo [102]. Dentro del transfer learning existen dos modalidades: • Feature extraction: Únicamente se entrenan las últimas capas densas de la red neuronal, también denominadas clasificador. • Fine tuning: se entrena el clasificador junto con alguna de las capas predecesoras. Permite lograr un ajuste más fino del modelo. 2.5.6 Aumento de datos (data augmentation) Como se ha comentado, el número de imágenes es un factor limitante a la hora de entrenar una red neuronal. Como más compleja sea la tarea a realizar y más clases se deban caracterizar, mayor número de imágenes serán necesarias. En ocasiones, adquirir un gran número de imágenes es francamente complicado. Por ello, se suele recurrir a una técnica denominada data augmentation [99,103]. A través de este método es posible incrementar el número de imágenes de entrenamiento. Para lograrlo, esta técnica lo que hace es modificar aleatoriamente las imágenes originales, generando de esta forma, nuevas imágenes que podrían pasar por originales. El objetivo es que el modelo nunca vea exactamente las mismas imágenes en las diferentes epochs de entrenamiento [99], lo cual también ayuda a evitar la aparición del indeseado overfitting. Estas modificaciones suelen consistir en rotar, Desarrollo de modelos mediante técnicas fotónicas 71 desplazar, cambios de zoom, cortes aleatorios, etc. Pese a sus ventajas, se debe andar con cuidado con las modificaciones específicas que se apliquen al conjunto de datos, para no generar imágenes que nunca podrían encontrarse en la realidad. De lo contrario, se estaría empeorando la eficacia del modelo [99]. Otro punto importante, es que el data augmentation únicamente se debe aplicar sobre el conjunto de entrenamiento, nunca sobre el de test. 2.5.7 Arquitectura red neuronal convolucional VGG16 La arquitectura de la red neuronal convolucional VGG (Visual Geometry Group) fue creada por Karen Simonyan y Andrew Zisserman en el 2014 [104] y fue empleada en la competición de ImageNet Large-Scale Visual Recognition Challenge (ILSVRC) [105,106]. Los autores diseñaron dos arquitecturas VGG, una compuesta por 19 capas y otra por 16 capas. Esta última es la que se ha empleado en el presente estudio. La base convolucional de la red VGG16 está constituida por 16 capas, que están ordenadas en cinco bloques. Los bloques 1 y 2 contienen dos capas convolucionales cada uno con 64 y 128 filtros o kernels, respectivamente. Los otros tres bloques restantes (bloques 3, 4 y 5) están formados por tres capas convolucionales con 256, 512 y 512 filtros por bloque, respectivamente. Cada capa convolucional usa filtros con una ventana de conexión o campo receptivo de 3 × 3. El desplazamiento o paso de avance del filtro es de 1 × 1 píxel, y el relleno espacial de la entrada de la capa convolucional es tal que la resolución espacial se conserva después de la convolución [104]. Además, al final de cada uno de los cinco bloques convolucionales hay una capa max_pooling que trabaja sobre una ventana de 2x2 pixeles. A continuación de la base convolucional, la red VGG16 contiene un clasificador que está compuesto por tres capas completamente conectadas (Fully connected en inglés). La Figura 19 muestra un esquema de la arquitectura Vgg16. En el presente estudio se empleó una versión modificada de la red neuronal convolucional VGG16. La red VGG16 empleada conserva toda la arquitectura del Introducción 72 bloque convolucional de la VGG16 original a excepción del clasificador, el cual fue sustituido por otro creado específicamente para la situación experimental de interés. Los detalles aparecen descritos en el Capítulo 4. 2.6 Análisis de datos multivariantes Se habla de datos multivariantes cuando se estudian tres o más características (variables) por muestra. Un ejemplo de datos multivariantes son los obtenidos mediante técnicas espectroscópicas, en las cuales, una misma muestra se analiza a Figura 19. Arquitectura de la red neuronal convolucional VGG16. Creación propia. Desarrollo de modelos mediante técnicas fotónicas 73 diferentes longitudes de onda, siendo considerada cada una de ellas una variable [107]. Para poder trabajar los datos multivariantes, estos deben ser organizados formando matrices, donde las filas son las muestras (i=1…m) y las columnas son las medidas o variables de estudio (j=1…n). Los datos pueden agruparse en una sola matriz o en varias matrices. Por lo general, se suele trabajar con dos matrices. Por un lado, tenemos la matriz de datos (X), la cual contiene las variables independientes o predictoras. Esta matriz agrupa la información adquirida durante el desarrollo del ensayo. Por ejemplo, el caso de la espectroscopia serían los datos espectrales. Por otro lado, está la matriz de referencia (Y), la cual puede contener datos cuantitativos, cualitativos o definir las clases de interés. Las variables presentes en la matriz Y reciben el nombre de variables dependientes o respuesta. X= ( 𝑥11 𝑥12 𝑥13 ⋯ 𝑥1𝑛 𝑥21 𝑥22 𝑥23 ⋯ 𝑥2𝑛 𝑥31 𝑥32 𝑥33 ⋯ 𝑥3𝑛 ⋮ ⋮ ⋮ ⋮ 𝑥𝑚1 𝑥𝑚2 𝑥𝑚3 ⋯ 𝑥𝑚𝑛 ) 𝑂𝑟𝑑𝑒𝑛 𝑚·𝑛 (10) Una vez estructurados los datos en matrices se puede empezar a estudiar el comportamiento de las variables. Es en este punto donde entran en juego los métodos de análisis multivariante. Estos se emplean principalmente para la reducción de la dimensionalidad de los datos y la búsqueda de relaciones entre varios grupos de variables pertenecientes a una misma matriz o a varias matrices (matriz X y matriz Y). De esta forma, el análisis multivariante ayuda al estudio conjunto de los datos, facilitando la interpretación y comprensión de la información [107]. Dentro del análisis de datos multivariantes existe un amplio repertorio de técnicas y métodos. Los más relevantes, para datos espectrales, se muestran en la Figura 20. Algunos de los métodos de análisis multivariante más utilizados son los de reducción de variables, como el análisis de componentes principales (PCA). Además Introducción 74 de métodos en los que se buscan relaciones entre las matrices X e Y, como es el caso de la regresión de mínimos cuadrados parciales (PLS) junto con el análisis discriminante de mínimos cuadrados parciales (PLS-DA). Algunos de estos métodos de análisis multivariante son comúnmente empleados dentro del campo de la quimiometría 2.6.1 Métodos quimiométricos de análisis Massart (1998) definió la quimiometría como «una disciplina química que utiliza las matemáticas, la estadística y la lógica formal para a) diseñar o seleccionar procedimientos experimentales óptimos; b) proporcionar la máxima información química de relevancia mediante el análisis de datos químicos; c) obtener conocimientos sobre sistemas químicos» [108]. De esta forma, la quimiometría ayuda a extraer el máximo de información útil de los datos. Figura 20. Esquema donde se muestran los principales métodos de análisis multivariante aplicado a la espectroscopia NIR [64]. Desarrollo de modelos mediante técnicas fotónicas 75 El origen de la quimiometría se remonta a los trabajos realizados por Kowalski, Isenhour y Jurs en el año 1969 [109–113]. A partir de esas primeras publicaciones, otros grupos de investigación contribuyeron con sus trabajos al desarrollo de lo que hoy se conoce como quimiometría. Uno de esos grupos de investigación fue el liderado por Svante Wold, el cual, aparte de trabajar en algoritmos de clasificación como el Soft independent modelling by class analogy (SIMCA), fue el primero en referirse a este nuevo conjunto de herramientas con el nombre de quimiometría en el año 1974 [114]. La quimiometría incluye en primer lugar el tratamiento de los datos, lo que nos permite resaltar la señal y reducir el ruido. Y en segundo lugar la modelización y la calibración, a través de las cuales se busca una relación cuantitativa o cualitativa entre la señal analítica y alguna propiedad de la muestra. Pretratamiento de la señal Las técnicas quimiométricas se emplean frecuentemente para mejorar la señal de los espectros obtenidos mediante espectroscopia de infrarrojo cercano [73,115– 118], donde los espectros pueden verse significativamente influenciados por efectos no deseados derivados de la dispersión de la radiación, como el desplazamiento de la línea de base (efecto aditivo) y otros fenómenos agrupados bajo el termino de no linealidades (non-linearities) [73,119]. Debido a que estos fenómenos se encuentran estrechamente ligados a la presencia de partículas de diferentes tamaños, son muy comunes cuando se trabaja con muestras trituradas o en polvo [115]. Además, las características propias de los espectros NIR, como son la presencia de bandas anchas y solapadas o la baja intensidad de pico, hacen indispensable la utilización de técnicas de filtrado de señal, las cuales en el ámbito de la espectroscopia reciben el nombre de métodos de pretratamiento de espectros. De esta forma, las técnicas quimiométricas de tratamiento de señal tienen como objetivo resaltar la componente que depende de las propiedades de la muestra y eliminar o reducir los Introducción 82 [107]. El PLS-DA es un método de clasificación lineal que combina las propiedades del algoritmo PLS junto con el potencial de discriminación de las técnicas de clasificación [131]. El método PLS-DA consta de dos pasos: 1) búsqueda de la relación entre la matriz de datos X y la matriz de referencia Y mediante el algoritmo PLS; 2) Construcción de la regla de discriminación. PLS-DA emplea el algoritmo PLS para buscar variables latentes que presenten máxima covarianza con las variables Y [131]. Pero a diferencia del PLS, en un modelo PLS-DA la matriz de referencia Y contiene información cualitativa, es decir, informa de la clase a la que pertenece cada muestra de la matriz X. La información de la matriz Y se transforma en valores numéricos (dummy variables en inglés), los cuales suelen ser 0 y 1. En el caso de una clasificación binaria, el valor 1 se asigna a la clase de interés y el valor cero a la otra clase. No obstante, cuando se construye un modelo real no se suelen obtener valores enteros, sino que los valores predichos se distribuyen alrededor de 0 o de 1 [134]. Cuando se trabaja con dos clases, únicamente es necesaria una variable y (una sola columna en la matriz Y). Cuando hay más de dos clases, se debe crear una variable y en la matriz de referencia para cada una de ellas (una columna por clase) [131]. El procedimiento sería el mismo, 1 para la clase seleccionada y 0 para el resto de las clases. A continuación, y en base a la distribución de los datos en el nuevo espacio constituido por los factores PLS (VL), se define un discriminador o threshold para cada una de las variables y (clases), basado en el Teorema de Bayes [135]. El discriminador crea un umbral dentro del rango 0-1 por encima del cual la muestra es asignada a la clase correspondiente o, de lo contrario, es rechazada. En el proceso de cálculo (y optimización) del discriminador se realiza una estimación de la sensibilidad (proporción de positivos correctamente asignados) y la especificidad (proporción de negativos correctamente asignados) en base a los datos observados y asumiendo que la distribución de los mismos es representativa para la clase. Una vez hecho esto, se sitúa el discriminador en el punto de corte entre ambas curvas. De esta forma se intenta minimizar el número de falsos positivos y Desarrollo de modelos mediante técnicas fotónicas 83 falsos negativos en futuras predicciones. El cálculo del discriminador varía en función del número de factores PLS seleccionados. En este sentido, al igual que en el modelo PLS, en el modelo PLS-DA se debe escoger el número de variables latentes a través de un proceso de validación. Todo esto se muestra gráficamente en las Figura 21 y 22. De esta forma, el resultado del modelo PLS-DA son una serie de valores de predicción, uno para cada clase, los cuales son comparados con los diferentes discriminadores para realizar la asignación de la muestra a alguna de las clases definidas. Figura 21. Discriminador o threshold (línea discontinua roja) para la variedad Pentacebas en un modelo PLS-DA con tres clases. Introducción 84 Figura 22. Estimación del discriminador en el punto de corte entre la sensibilidad y la especificidad para cada clase. Objetivos Desarrollo de modelos mediante técnicas fotónicas 87 Objetivos Objetivo general El objetivo general es desarrollar un método que permita identificar y diferenciar variedades a nivel de planta de vivero. Además, se plantea la capacidad de evaluar el estado fisiológico de las mismas. En este sentido, es importante que la técnica desarrollada sea rápida y de bajo coste. Objetivos específicos Para lograr el objetivo general, la tesis doctoral queda estructurada en tres objetivos específicos: 1) Definir un protocolo de muestreo del material vegetal en el campo y en el vivero, además de definir el tratamiento que se les debe aplicar a las muestras de acuerdo con los resultados obtenidos, así como la determinación y puesta a punto del instrumento técnico. 2) Desarrollar modelos matemáticos con la utilización de software específicos que nos permitan: a. Discriminación varietal para un rápido fenotipado b. Detección de la presencia o ausencia de fitopatologías con antelación a la aparición de síntomas visuales. 3) Alcanzar un nivel 5 de madurez de la tecnología en la escala “Technological Readiness Level (TRL)”, además de estudiar la viabilidad para la implantación del instrumento en la cadena de producción de la empresa. Los objetivos de la tesis doctoral se acordaron en base a necesidades expuestas por Agromillora. Capítulo 1. Development of a Methodology to Analyze Leaves from Prunus dulcis Varieties Using Near-Infrared Spectroscopy Contents lists available at ScienceDirect Talanta journal homepage: www.elsevier.com/locate/talanta Development of a methodology to analyze leaves from Prunus dulcis varieties using near infrared spectroscopy Sergio Borraz-Martínez a,c,∗ , Ricard Boqué b , Joan Simó a,d , Mariàngela Mestre c , Anna Gras a a Universitat Politècnica de Catalunya, Department of Agri-Food Engineering and Biotechnology, Esteve Terrades 8, 08860, Castelldefels, Spain b Universitat Rovira i Virgili, Department of Analytical Chemistry and Organic Chemistry, Campus Sescelades, 43007, Tarragona, Spain c Agromillora Iberia S.L.U, Center of Initial Materials, Ctra. BV-2247 km. 3, 08770, Sant Sadurní d’Anoia, Spain d Fundació Miquel Agustí, Esteve Terrades 8, 08860, Castelldefels, Spain ARTICLE INFO Keywords: Optimization Almond trees Leaf analysis Varietal purity NIR PLS-DA ABSTRACT Near-infrared spectroscopy (NIRS) can be a faster and more economical alternative to traditional methods for screening varietal mixtures of nursery plants during the propagation process to ensure varietal purity and to avoid errors in the dispatch batches. The global objective of this work was to develop and optimize a NIR spectral collection method for construction of robust multivariate discrimination models. Three different varieties of Prunus dulcis (Avijor,Guara, and Pentacebas) of agricultural interest were used for this study. Sources of variation were investigated, including the position of the leaves on the trees, differences among trees of the same variety, and differences at the varietal level. Three types of processed samples were investigated. Fresh leaves, dried leaves, and dried leaves in powder form were included in each analysis. A study of spectral pre-treatment methods was also performed, and multivariate methods were applied to analyze the influence of different factors on classification. These included principal component analysis (PCA), partial least squares discriminant analysis (PLS-DA), and ANOVA simultaneous component analysis (ASCA). The results indicated that variety was the most important factor for classification. The spectral pre-treatment that provided the best results was a combination of standard normal variate (SNV), Savitzky-Golay first derivative, and mean-centering methods. With regard to the type of processed sample, the highest percentages of correct classifications were obtained with fresh and dried powdered leaves at both the training set and test set validation levels. This study represents the first step towards the consolidation of NIRS as a method to identify Prunus dulcis varieties. 1. Introduction Rapid discrimination between vegetal varieties is a key requirement for all nursery plant production. The huge diversity of vegetal materials necessitates the incorporation of new control systems along the nursery plant production chain to avoid mixing varieties and to ensure varietal purity in the dispatch batches. Nowadays, the most extensively used methods for varietal identification are based on DNA analysis. These techniques include DNA amplification by the polymerase chain reaction (PCR) [1] followed by analysis of genetic variations, such as single nucleotide polymorphisms (SNPs) [2]. However, these biomolecular techniques are very expensive for routine analysis of a large number of samples. In this context, the use of spectroscopic analysis combined with chemometrics has recently increased. This combination comprises a rapid, accurate, and nondestructive methodology for the classification and authentication of agricultural products [3]. Near-infrared (NIR) spectroscopy has proved to be a powerful analytical tool and has been widely used in various sectors, including the petrochemical [4] and pharmaceutical industries [5]. It has also become a well-established technique for the quantitative and qualitative analysis of agricultural products [6]. Several recent studies have employed spectroscopic techniques for species discrimination [7,8], or differentiation of varietals within a species, such as tomato [9], rice [10] and lettuce [11]. For these reasons, NIRS can be considered a potential candidate for the differentiation of Prunus dulcis varieties. Despite recent studies, there is a lack of knowledge regarding the best methodology for accurate sampling of leaves. Most of the published works on species discrimination do not consider factors derived from the nature of the samples, which are potential sources of variance. For example, mature trees have a heterogeneous canopy composed of leaves in different phenological stages. It is thus important to take the https://doi.org/10.1016/j.talanta.2019.05.105 Received 22 March 2019; Received in revised form 21 May 2019; Accepted 27 May 2019 ∗ Corresponding author. E-mail address: [email protected] (S. Borraz-Martínez). Talanta 204 (2019) 320–328 Available online 05 June 2019 0039-9140/ © 2019 Elsevier B.V. All rights reserved. T 91 accuracy obtained with this spectral pre-treatment was 97.5% at both the cross-validation and test set validation levels. No relevant differences between the other two spectral pre-treatments were observed, so de-trending did not appear to have a significant effect. It is important to note that in the case of fresh leaves, similar results were obtained with the three different spectral pre-treatments. 3.3.2. Sample processing study Each sample processing method had its advantages and disadvantages. Fresh leaves did not require any processing, so measurement was faster and easier than it was with the other types of samples. However, the water content of the leaves was a disadvantage, because it generated wide bands in the NIR spectra. This could make discrimination between varieties more difficult. Samples can be dehydrated to circumvent the effects of water, but this process is timeconsuming (48 h), so it is not the best option if rapid identification is required. To evaluate which of the processed samples was the most suitable for varietal classification, the advantages and disadvantages of each were considered together with the PLS-DA classification results obtained with SNV spectral pre-treatment and application of the SG first derivative and mean centering (Table 4). The results obtained with the three types of sample processing at the calibration level could be considered quite good, although those obtained with fresh leaves were less stellar. The dried powdered leaves provided a higher percentage of correct classifications. For the test set validation, high percentages of correct classifications were obtained with all varieties and processed sample types. The results provided by the dried leaves were not as good as those obtained with the other two processed sample types, although the Pentacebas variety was correctly classified in 100% of the test set validations. Fresh leaves provided almost perfect classification, and nearly 100% correct classification was attained with dried powdered leaves. Taking only the PLS-DA results into account, the best sample processing method was drying and powdering the leaves. Considering the methodological aspects, using fresh leaves was the fastest and easiest option. The biggest drawback of fresh leaves was their water content, but this did not seem to hinder discrimination between the varieties studied. In the ASCA-ANOVA model performed in assay two (Table 3), the strongest effect on dried leaves was contributed by the leaf age factor. The age factor accounted for more variability than even the tree variety factor, which could be problematic. Fresh leaves exhibited more favorable behavior in the ASCA-ANOVA model. Results of the ASCAANOVA model with dried powdered leaves were similar to those obtained with fresh leaves, but the residual was higher. 4. Conclusions and perspectives In this study, we defined a methodology for construction of a classification model that could discriminate between Prunus dulcis varieties using NIRS. We also identified the most important sampling and analysis aspects. In assay one, differences were seen in the PCA whether or not the midvein was included. The central leaf region provided more useful information for discriminating between almond tree varieties, because it contained both the primary vein and the laminar tissues. We also attempted to determine which surface of the leaves, adaxial or abaxial, was the most suitable for analysis. Despite the spectral differences observed, the comparison made using the PLSDA model indicated this was not an important aspect. In assay two, no notable differences were detected between trees of the same variety, which indicated that trees within each variety were quite homogeneous. Differences were observed at the PCA level between young and adult leaves, which indicated age was important to consider during the sampling process. The best results from the PLS-DA models in assay three were obtained with dried powdered leaves when SNV was used for spectral pretreatment with application of the SG first derivative (15-point window, second order) and mean centering. However, fresh leaves appeared to be the easiest and most suitable samples for laboratory or industrial analysis. These results indicated that both fresh leaves and dried powdered leaves could be useful for discriminating between Prunus dulcis varieties using NIR spectroscopy. All the information gathered in the present study will be used to build a classification model that includes more Prunus dulcis varieties. The potential of NIR spectroscopy for the classification of almond tree varieties and its implementation as a quality control tool in the nursery plant industry will be studied. Funding This work was supported by Generalitat de Catalunya through a grant from Program of Industrial Doctorates (DI-COF 2017) and by The Table 4 PLS-DA model results of the spectra pre-treatment and study of the types of pre-processed samples. Real class Data set Assigned class SNV +Mean center SNV +1st derivative +Mean center SNV + De-trending + Mean center Dried-powdered leaves Avijor Cross-validation 87.4% 99.2% 86.6% Test set validation 97.5% 100% 97.5% Guara Cross-validation 89.9% 99.2% 89.1% Test set validation 96.6% 100% 96.6% Pentacebas Cross-validation 97.5% 100% 97.5% Test set validation 99.2% 100% 99.2% Dried leaves Avijor Cross-validation 97.5% 99.2% 95.0% Test set validation 95.0% 98.3% 93.3% Guara Cross-validation 95.0% 100% 93.3% Test set validation 92.5% 97.5% 91.7% Pentacebas Cross-validation 97.5% 99.2% 93.3% Test set validation 97.5% 100% 98.3% Fresh leaves Avijor Cross-validation 100% 97.5% 100% Test set validation 99.2% 100% 99.2% Guara Cross-validation 99.2% 97.5% 99.2% Test set validation 98.3% 99.2% 98.3% Pentacebas Cross-validation 99.2% 100% 99.2% Test set validation 99.2% 99.2% 99.2% S. Borraz-Martínez, et al. Talanta 204 (2019) 320–328 327 98 Spanish Ministry of Economy and Competitiveness (project AGL 2015- 70106-R). Acknowledgment The authors thank Thermo Scientific for temporary assignment of the NIR equipment. References [1] K. Mullis, F. Faloona, S. Scharf, R. Saiki, G. Horn, H. Erlich, Specific enzymatic amplification of DNA in vitro: The polymerase chain reaction, Cold Spring Harbor Symp. Quant. Biol. 51 (1986) 263–273, https://doi.org/10.1101/SQB.1986.051.01. 032. [2] P.K. Gupta, J.K. Roy, M. Prasad, Single nucleotide polymorphism a new paradigm for molecular marker technology and DNA polymorphism detection with emphasis on their use in plant.pdf, Curr. Sci. 80 (2001) 524–535, https://doi.org/10.2307/ 24104242. [3] M. Makky, P. Soni, In situ quality assessment of intact oil palm fresh fruit bunches using rapid portable non-contact and non-destructive approach, J. Food Eng. 120 (2014) 248–259, https://doi.org/10.1016/J.JFOODENG.2013.08.011. [4] M.V. Reboucas, J.B. dos Santos, D. Domingos, A.R.C.G. Massa, Near-infrared spectroscopic prediction of chemical composition of a series of petrochemical process streams for aromatics production, Vib. Spectrosc. 52 (2010) 97–102, https://doi.org/10.1016/J.VIBSPEC.2009.09.006. [5] M. Verstraeten, D. Van Hauwermeiren, M. Hellings, E. Hermans, J. Geens, C. Vervaet, I. Nopens, T. De Beer, Model-based NIR spectroscopy implementation for in-line assay monitoring during a pharmaceutical suspension manufacturing process, Int. J. Pharm. 546 (2018) 247–254, https://doi.org/10.1016/j.ijpharm. 2018.05.043. [6] Z. Seregély, T. Deák, G.D. Bisztray, Distinguishing melon genotypes using NIR spectroscopy, Chemometr. Intell. Lab. Syst. 72 (2004) 195–203, https://doi.org/10. 1016/j.chemolab.2004.01.013. [7] Q. Fan, Y. Wang, P. Sun, S. Liu, Y. Li, Discrimination of Ephedra plants with diffuse reflectance FT-NIRS and multivariate analysis, Talanta (2010), https://doi.org/10. 1016/j.talanta.2009.09.018. [8] F.M. Durgante, N. Higuchi, A. Almeida, A. Vicentini, Species spectral signature: Discriminating closely related plant species in the amazon with near-infrared leafspectroscopy, For. Ecol. Manag. 291 (2013) 240–248, https://doi.org/10.1016/j. foreco.2012.10.045. [9] Y.N. Shao, C.Q. Xie, L.J. Jiang, J.H. Shi, J.J. Zhu, Y. He, Discrimination of tomatoes bred by spaceflight mutagenesis using visible/near infrared spectroscopy and chemometrics, Spectrochim. Acta Part A Mol. Biomol. Spectrosc. (2015), https://doi. org/10.1016/j.saa.2015.01.018. [10] L. Zhang, S.S. Wang, Y.F. Wang, J.R. Pan, C. Zhu, Discrimination of transgenic rice based on near infrared reflectance spectroscopy and partial least squares regression discriminant analysis, Rice Sci. (2015), https://doi.org/10.1016/j.rsci.2015.09. 004. [11] L. de Oliveira Moura, D. de Carvalho Lopes, A.J. Steidle Neto, L. de Castro Louback Ferraz, L. de Almeida Carlos, L.M. Martins, Evaluation of techniques for automatic classification of lettuce based on spectral reflectance, Food Anal. Methods 9 (2016) 1799–1806, https://doi.org/10.1007/s12161-015-0366-5. [12] G.D. Batten, Plant analysis using near infrared reflectance spectroscopy: The potential and the limitations, Aust. J. Exp. Agric. 38 (1998) 697–706, https://doi. org/10.1071/EA97146. [13] P. Skolik, M.R. McAinsh, F.L. Martin, Biospectroscopy for plant and crop science, in: C.S. João Lopes (Ed.), Compr. Anal. Chem. Elsevier, 2018, pp. 15–49, , https://doi. org/10.1016/BS.COAC.2018.03.001. [14] A. Candolfi, R. De Maesschalck, D. Jouan-Rimbaud, P.A. Hailey, D.L. Massart, The influence of data pre-processing in the pattern recognition of excipients near-in- frared spectra, J. Pharm. Biomed. Anal. 21 (1999) 115–132, https://doi.org/10. 1080/13554790490495140. [15] L. Xu, Y.P. Zhou, L.J. Tang, H.L. Wu, J.H. Jiang, G.L. Shen, R.Q. Yu, Ensemble preprocessing of near-infrared (NIR) spectra for multivariate calibration, Anal. Chim. Acta 616 (2008) 138–143, https://doi.org/10.1016/j.aca.2008.04.031. [16] Å. Rinnan, F. van den Berg, S.B. Engelsen, Review of the most common pre-pro- cessing techniques for near-infrared spectra, TrAC Trends Anal. Chem. (Reference Ed.) 28 (2009) 1201–1222, https://doi.org/10.1016/j.trac.2009.07.007. [17] R.J. Barnes, M.S. Dhanoa, S.J. Lister, Standard normal variate transformation and de-trending of near-infrared diffuse reflectance spectra, Appl. Spectrosc. 43 (1989) 772–777, https://doi.org/10.1366/0003702894202201. [18] A. Savitzky, M.J.E. Golay, Smoothing and differentiation of data by simplified least squares procedures, Anal. Chem. 36 (1964) 1627–1639, https://doi.org/10.1021/ ac60214a047. [19] R.S.K. Barry, M. Wise, Neal B. Gallager, Rasmus Bro, Jeremy M. Shaver, Willem Windig, Chemometrics Tutorial for PLS _ Toolbox and Solo, (2006), https://doi.org/ 10.1016/j.cplett.2004.08.130. [20] P. Wang, Z. Yu, Species authentication and geographical origin discrimination of herbal medicines by near infrared spectroscopy: A review, J. Pharm. Anal. 5 (2015) 277–284, https://doi.org/10.1016/j.jpha.2015.04.001. [21] R.G. Brereton, G.R. Lloyd, Partial least squares discriminant analysis: Taking the magic away, J. Chemom. 28 (2014) 213–225, https://doi.org/10.1002/cem.2609. [22] D. Ballabio, V. Consonni, Classification tools in chemistry. Part 1: Linear models, PLS-DA, Anal. Methods. 5 (2013) 3790, https://doi.org/10.1039/c3ay40582f. [23] L. St»hle, S. Wold, Analysis of variance (ANOVA), Chemometr. Intell. Lab. Syst. 6 (1989) 259–272, https://doi.org/10.1016/0169-7439(89)80095-4. [24] L. St»hle, S. Wold, Multivariate analysis of variance (MANOVA), Chemometr. Intell. Lab. Syst. 9 (1990) 127–141, https://doi.org/10.1016/0169-7439(90)80094-M. [25] G. Zwanenburg, H.C.J. Hoefsloot, J.A. Westerhuis, J.J. Jansen, A.K. Smilde, ANOVA–principal component analysis and ANOVA–simultaneous component analysis: A comparison, J. Chemom. 25 (2011) 561–567, https://doi.org/10.1002/cem. 1400. [26] A.K. Smilde, J.J. Jansen, H.C.J. Hoefsloot, R.J.A.N. Lamers, J. van der Greef, M.E. Timmerman, ANOVA-simultaneous component analysis (ASCA): A new tool for analyzing designed metabolomics data, Bioinformatics 21 (2005) 3043–3048, https://doi.org/10.1093/bioinformatics/bti476. [27] J.J. Jansen, H.C.J. Hoefsloot, J. Van Der Greef, M.E. Timmerman, J.A. Westerhuis, A.K. Smilde, ASCA: Analysis of multivariate data obtained from an experimental design, J. Chemom. 19 (2005) 469–481, https://doi.org/10.1002/cem.952. [28] O.E. de Noord, E.H. Theobald, Multilevel component analysis and multilevel PLS of chemical process data, J. Chemom. 19 (2005) 301–307, https://doi.org/10.1002/ cem.933. [29] N. Suzuki, R.M. Rivero, V. Shulaev, E. Blumwald, R. Mittler, Abiotic and biotic stress combinations, New Phytol. 203 (2014) 32–43, https://doi.org/10.1111/nph. 12797. [30] J.C.M.S. Moura, C.A.V. Bonine, J. de Oliveira Fernandes Viana, M.C. Dornelas, P. Mazzafera, Abiotic and biotic stresses and changes in the lignin content and composition in plants, J. Integr. Plant Biol. 52 (2010) 360–376, https://doi.org/10. 1111/j.1744-7909.2010.00892.x. S. Borraz-Martínez, et al. Talanta 204 (2019) 320–328 328 99 Capítulo 2. Multivariate Classification of Prunus dulcis Varieties Using Leaves of Nursery Plants and Near- Infrared Spectroscopy 1 Scientific RepoRtS | (2019) 9:19810 | https://doi.org/10.1038/s41598-019-56274-5 www.nature.com/scientificreports Multivariate Classification of Prunus dulcis Varieties using Leaves of Nursery Plants and Near-Infrared Spectroscopy Sergio Borraz-Martínez 1,2*, Joan Simó 4, Anna Gras 1, Mariàngela Mestre2 & Ricard Boqué 3 The emergence of new almond tree (Prunus dulcis) varieties with agricultural interest is forcing the nursery plant industry to establish quality systems to keep varietal purity in the production stage. The aim of this study is to assess the capability of near-infrared spectroscopy (NIRS) to classify different Prunus dulcis varieties as an alternative to more expensive methods. Fresh and dried-powdered leaves of six different varieties of almond trees of commercial interest (Avijor, Guara, Isabelona, Marta, Pentacebas and Soleta) were used. The most important variables to discriminate between these varieties were studied through of three scientifically accepted indicators (Variable importance in projection¸ selectivity ratio and vector of the regression coefficients). The results showed that the 7000 to 4000 cm−1 range contains the most useful variables, which allowed to decrease the complexity of the data set. Concerning to the classification models, a high percentage of correct classifications (90–100%) was obtained, where dried-powdered leaves showed better results than fresh leaves. However, the classification rate of both kinds of leaves evidences the capacity of the near-infrared spectroscopy to discriminate Prunus dulcis varieties. We demonstrate with these results the capability of the NIRS technology as a quality control tool in nursery plant industry. The almond market is in expansion. The world production in the 2017/2018 season reached the record of 1.3 million tons, 6% above the registered in the previous season, according to the latest estimates of the United States Department of Agriculture (USDA)1. The Food and Agriculture Organization Corporate Statistical Database (FAOSTAT)2 shows that, in Spain, in the period 2015–2017, the almond tree harvested area increased by 15%, which was reflected in an increase in production of 21%. These data demonstrate the importance of almond tree in world agriculture. For this reason, new varieties of almond trees have been increasing3,4. Varietal control in the production stage is a great challenge. The appearance of varietal mixtures within a batch, which should be homogeneous, is an important trouble, not only because the customer receives unwanted vegetal material, but also because nursery plant companies may face expensive fines and the deterioration of their corporative image. The current method used for the identification of plants consists of performing molecular studies of the vegetal material in order to obtain molecular profiles and identifying the variety by using microsatellites and single nucleotide polymorphisms (SNPs)5. These biomolecular techniques are reliable. However, they are expensive and time consuming, and therefore cannot be applied routinely and with a high sample throughput. For this reason, the most common varietal control system consists of ensuring a correct and detailed traceability from the origin of the plant to its delivery to the customer, which is not always reliable. In this context, near-infrared spectroscopy (NIRS), combined with chemometrics techniques, is potentially a rapid, accurate, and non-destructive alternative. 1Dept. of Agri-Food Engineering and Biotechnology, Universitat Politècnica de Catalunya, Campus Baix Llobregat, Esteve Terrades 8, 08860, Castelldefels, Spain. 2Center of Initial Materials, Agromillora Iberia S.L.U, Ctra. BV-2247 km. 3, 08770, Sant Sadurní d’Anoia, Spain. 3Universitat Rovira i Virgili, Dept. of Analytical Chemistry and Organic Chemistry, Campus Sescelades, 43007, Tarragona, Spain. 4Fundació Miquel Agustí, Campus Baix Llobregat, Esteve Terrades 8, 08860, Castelldefels, Spain. *email: [email protected] open 103 2 Scientific RepoRtS | (2019) 9:19810 | https://doi.org/10.1038/s41598-019-56274-5 www.nature.com/scientificreports www.nature.com/scientificreports/ In the last years, NIRS has gained importance in the agriculture sector as an interesting tool for monitoring and quality assessment of agricultural products6–8. Various studies have been published concerning the geographic origin9–11 and species discrimination in grapevine12, tea13, tomato14 and coffee15. Moreover, several studies have shown the existence of an empirical relationship between leaf spectral properties and leaf physiological conditions16,17. In the present study, six varieties of Prunus dulcis of agricultural interest were chosen: Avijor, Guara, Isabelona, Marta, Pentacebas and Soleta. All of them are genetically close because they come from crosses of traditional varieties, and some of them even share parents. In fact, this is the case of Avijor and Marta, both coming from the cross between “Ferragnès x Tuono”, and Isabelona and Soleta come from the cross between “Blanquerna x Bella d’Aurons”. Due to their genetic proximity, the morphology of these six varieties is difficult to distinguish. Despite the present study focuses on specific varieties of Prunus dulcis, as the leaves’ composition is similar in all the angiosperm species18, the knowledge achieved in this work could be applied to discriminate other plant species. The present study is the continuation of a previous research, where a sampling methodology was developed and optimized to analyze leaves from Prunus dulcis varieties using near infrared spectroscopy19. In the cited study, several sources of variability affecting the measurements were investigated, such as the regions of the leaves analyzed and the age of the leaves, and how these factors affect to the spectral signature of the varieties. Moreover, the most suitable preprocessing of the leaves and the best spectral pre-treatment were determined. In the present study, the information gathered from the previous research was used to assess the potential of NIRS to classify several varieties of almond trees (Prunus dulcis) that are genetically close and morphologically not distinguishable. The specific objectives are to: 1) develop a classification model capable of discriminating between six varieties of Prunus dulcis; 2) investigate the most important variables for the discrimination of the varieties; and 3) compare the classification results obtained with dried-ground leaves and fresh leaves. Material and Methods Description of the sampling field. The studied almond trees belong to the mother-plant field of the Centre of Initial Materials of Agromillora Iberia S.L.U., which is located in Sant Sadurní d’Anoia (Catalonia, Spain). The sanitary quality of the sampled trees was verified by means of molecular analysis, which Agromillora S.L.U. perform periodically as a quality control. Moreover, the trees were certified by the company. The same mother-plant field was used in a previously study19. Sampling protocol. Six Prunus dulcis varieties of agricultural interest were used. One hundred leaves were collected from ten trees for each variety. In total, six hundred leaves were collected from which three hundred fresh leaves were analyzed without any prior treatment, and the rest was dried and ground. The number of samples per variety was identical. Table1 details the samples used in this study. The leaf samples collected were introduced in plastic bags with an identification code and stored at 4 °C until they were analyzed. Sample pre-processing. To obtain dried-powdered leaves, fresh leaves were heated in an oven at 65 °C for 48 h. Once dried, a grinder was used to obtain a homogeneous powder. Further, the powder was stored in a desiccator with silica gel to avoid moisture19. Acquisition of NIR spectra. The NIR spectra acquisition method shown below was developed in a previous study19. An Antaris II FT-NIR analyzer (Thermo Scientific, USA), equipped with an integrating sphere module was used to scan the samples, which were measured in the spectral range of 12000–3800 cm−1 (833–2630 nm). The instrument configuration used consisted in the average of 32 scans by spectrum with a resolution of 4 cm−1. Each sample was analyzed in triplicate and the average of the replicates was used in the subsequent discrimination models. Every 20 minutes a background spectrum was collected. The powdered leaf samples were measured in a standard sample cup available with the instrument and fresh leaves were placed directly over the sphere. In both cases, samples were covered to prevent interference from environmental light. The reflectance spectra were mathematically transformed to absorbance by means of the log(1/R), where R is the reflectance. The room temperature was maintained at ~25 °C, and the humidity remained constant throughout the spectral acquisition process. Varieties Parents Breeder No. of fresh leaves No. of dried-ground leaves Harvesting time Avijor Ferragnès x Tuono INRA 50 50 October 2018 Guara Unknown CITA 50 50 October 2018 Isabelona Blanquerna x Bella d’Aurons CITA 50 50 October 2018 Marta Ferragnès x Tuono CEBAS-CSIC 50 50 October 2018 Pentacebas S5133 x Lauran CEBAS-CSIC 50 50 October 2018 Soleta Blanquerna x Bella d’Aurons CITA 50 50 October 2018 Total 300 300 Table 1. Description of the different varieties of Prunus dulcis studied. (INRA = Institut National de la Recherche Agronomique (France); CITA = Centro de Investigación y Tecnología Agroalimentaria de Aragón (Spain); CEBAS-CSIC = Centro de Edafología y Biología Aplicada del Segura (Spain)). 104 3 Scientific RepoRtS | (2019) 9:19810 | https://doi.org/10.1038/s41598-019-56274-5 www.nature.com/scientificreports www.nature.com/scientificreports/ Data preparation. When applying supervised multivariate classification methods, it is important to validate mathematical models by using an independent test data set. We applied two difference strategies to split the original dataset into calibration and test set: random split and the Kennard–Stone algorithm20. Similar results were obtained, so finally we decided to use the Kennard-Stone algorithm, which was applied to each class separately to split the data set into calibration set (70% of the leaves) and a test set (30% of the leaves). Spectral data pre-treatment. To enhance the spectral features and reduce systematic noise, such as baseline variation, light scattering, and path length differences, a mathematical pre-processing of the original spectra was necessary. The spectral pretreatment was optimized in a previous study19 and consisted of a combination of standard normal variate (SNV) with Savitzky–Golay (SG) first (1st) derivative filter and mean centering. SNV is a normalization procedure for spectral light scattering correction. It is used to correct additive and multiplicative effects in spectra caused by particle size variation. SNV calculates the standard deviation of all the variables in a given sample spectrum. The entire data set is then normalized by this value, which yields a unit standard deviation (s = 1) for the sample spectrum19,21. SG first derivative was applied to remove the baseline drift and enhance small spectral differences. The SG derivative method includes a smoothing step, the SG algorithm, which corrects the additional noise caused by the application of the derivative. The SG algorithm requires the selection of the order of the polynomial, order of the derivative, and filter width, which corresponds to the size of the window19,22. Herein, a 15-point window and second order polynomial were selected. Finally, mean centering was applied, which consists of calculating the mean value of each column and subtracting it from each individual value in the column. After mean centering, the mean value of each column equals zero, and each row of mean-centered data reflects only how it differs from the average sample in the original data matrix19,23. The PLS_Toolbox (Eigenvector Research Incorporated, Manson, USA) with MATLAB R2017b (MathWorks, Natick, USA) were used to perform the spectral pre-treatments. Partial Least-Squares discriminant analysis (PLS-DA). PLS-DA24 is based on the PLS regression algorithm and seek to find the linear combinations of the original variables (latent variables (LVs)) that have maximum covariance with the Y-variables (classes)24. Unlike PLS regression, in PLS-DA the Y-block is coded with dummy variables. Each sample is codified with one (1) if the sample belongs to a given class, and zero (0) if the sample does not belong to a given class. The result of a PLS-DA model is a series of prediction values for the different classes, that is, values around one for the class of interest and values around zero for the rest of classes. Finally, a threshold is calculated and optimized that optimally discriminates the different classes. Whit this PLS-DA model, validated with the test set of samples, it is then possible to predict the class of an unknown sample. In our case, six classes of leaves, one for each variety, were used, and therefore, the Y-block contained six columns. A Venetian blinds cross-validation, with a data split of 10 and one sample per blind (thickness), was used to find the optimal number of factors (LVs) for the PLS-DA model19. The number of factors that showed the lowest classification error was selected as optimal. After the internal validation (optimization), the prediction ability of the model was assessed using samples that were not included in the calibration (30% of the total data set). The results are shown in Tables2 and 3 (test-set validation). To study the model results three different statistical parameters were calculated: sensitivity, specificity and accuracy. The sensitivity measures the proportion of actual positives that are correctly identified as such, the specificity measures the proportion of actual negatives that are correctly identified as such, and the accuracy measures the proportion of correctly classified samples, that is, the sum of true positives and true negatives divided by the total number of samples. Study of the important variables. The prediction accuracy of the full-spectrum PLS-DA model is negatively affected by the water absorption and other unrelated or collinear spectral variables. By selecting the optimal wavelengths, it is possible to reduce the complexity of the multivariate calibration model, by reducing the computational requirements and avoiding the inclusion of noisy variables. Spectral variable selection is then essential to generate models with better prediction accuracies25. However, it is crucial to use different variable selection methods in order to ensure that no important variables are eliminated. The variable importance in projection (VIP) score, selectivity ratio and vector of regression coefficients were used to study the most important variables required to discriminate between the classes. The VIP score is a parameter used for calculating the cumulative values of the influence of individual X-variables in the model26. In other words, VIP scores estimate the importance of each variable in the projection used in a PLS model27. Scores close to or greater than 1 are considered relevant. The selectivity ratio provides a simple numerical assessment of the importance of each variable in a regression model28. By using the y-vector as a target, it is possible to transform the PLS components to obtain a single predictive target-projected component analogously to the predictive component in the orthogonal partial least squares discriminant analysis (OPLS-DA). By calculating the ratio between the explained and residual variance of the spectral variables on the target-projected component, a selectivity ratio plot is obtained and can be used for variable selection29. The larger the selectivity ratio, the more useful a variable for prediction. Variables with lower selectivity ratios may be excluded without degrading the performance of the model28. The vector of the regression coefficients is an informative tool to select variables in multivariate calibration. The regression vector obtained from a multivariate regression can be defined as the expected change in the response per unit change in the variable if all the variables and responses are linearly related30,31. Variables with low regression coefficients do not contribute significantly to the prediction and can be removed. 105 4 Scientific RepoRtS | (2019) 9:19810 | https://doi.org/10.1038/s41598-019-56274-5 www.nature.com/scientificreports www.nature.com/scientificreports/ Results and Discussion Spectra investigation. Figure1 shows the mean raw spectra of the fresh and dried-powdered leaves. It can be observed that the shape of the spectra from both types of samples differs. This is due to the water content, which generates broad bands in the NIR spectra. However, both types of spectra present a low information zone that corresponds to the region between 7500 and 10000 cm−1. In contrast, the remaining region, from 4000 to 7500 cm−1, seems to be more informative, and the importance of this region will be evaluated below. It is noted that both regions were also observed in others studies performed on tea and bamboo leaves13,32. By using NIR tables, it was possible to identify the main chemical groups behind the different bands. These bands in the NIR region correspond to the overtones and combination bands. Regarding fresh leaves, two main broad bands were observed at 5000 and 7000 cm−1, corresponding to O-H vibrations and more specifically the combination O-H stretching and first overtone O-H stretching, respectively. Water is the main responsible of these bands as observed in a study developed on grapevine leaves33, although the O-H bond is also found in carbohydrates. Another important peak is observed between 4000 and 4500 cm−1. This absorption is attributed to the combination C-H stretching. The C-H bond is present in monosaccharides and, together with oxygen, conforms the aldehyde group, which is also present in carbohydrates. Concerning the dried-powdered leaves, the range between 4000 to 7500 cm−1 includes the main bands, which correspond to the combination of C-H (7692–7042 cm−1), N-H (5000–4545 cm−1), and O-H stretching (5000– 4545 cm−1) and the first overtone of C-H (6061–5556 cm−1), N-H and O-H (7143–6250 cm−1) stretching. All the bonds mentioned before are commonly found in carbohydrates and proteins. In addition, a small band can be observed between 8000 and 9000 cm−1 approximately. This band correspond to the second overtone of the C-H stretching (9091–8163 cm−1). Classification model using the whole spectra. Table2 presents the results of the classification models for fresh and dried-powdered leaves. Concerning the dried-powdered leaf results, the classification accuracy in the cross-validation and test set validation was greater than 95% for all the varieties. In most cases, the test set validation showed a higher classification accuracy than that of cross-validation, except for Avijor class, due to the erroneous assignation of two Guara samples. This is not a common situation, as in general, better accuracy is reached for cross-validation than for test-set validation. However, sometimes this can happen when the test set does not contain a high number of samples. Avijor was presented the highest results for the cross-validation test, with a classification accuracy of 99.0%. In case of the test set validation, the best classification rate was obtained for the Marta class, with a classification accuracy of 100%. The lowest classification rate was obtained for Guara, which was the only variety showing an accuracy below 97%. Three Guara samples were misclassified in the test set validation, two samples were classified in the Avijor class, and one sample was assigned to the Isabelona class. Errors in the assignation of Guara samples were also reported in the cross-validation. Consequently, the Guara class showed a low sensitivity in both data sets. Isabelona and Marta showed the same sensitivity in both, cross-validation and test set validation. In addition, a correct assignation of all the samples of the validation data set was achieved for both varieties. Marta showed a higher specificity than that of Pentacebas because one Guara sample and one Pentacebas sample were misclassified in the Isabelona class. Thus, Marta presented better classification accuracy than that of Isabelona (100% and 97.8% accuracy, respectively). Soleta and Pentacebas showed the same sensitivity in the test set validation. The specificity was higher for Soleta than that of Pentacebas because one Soleta sample was erroneously assigned to Pentacebas, which was also reflected in a higher classification accuracy for Soleta. Concerning the fresh leaf results, except for Isabelona, the rest of the varieties showed a classification accuracy higher than 90% in both cross-validation and test set validation. Specifically, an accuracy between 89.5–98.6% and between 92.2–100% was obtained fir the cross-validation and test set validation, respectively. The best classification results were obtained for Marta variety, with 98.6% and 100% of accuracy for the cross-validation and test set validation, respectively. Pentacebas and Avijor reached an accuracy of 100% in the test set validation. Marta, Pentacebas and Avijor presented a relatively low sensitivity in the cross-validation, but the samples were correctly predicted in test set validation. The lowest classification accuracy was obtained for Isabelona and Guara. Isabelona had a 89.5% accuracy in the cross-validation and 92.2% in the test set validation. Guara was the only variety showing a lower accuracy in the test set validation than that in the cross-validation. Four samples of Guara were assigned to Isabelona, and one sample of Isabelona was predicted as Guara. Similarly, in the dried-powdered leaf model, the Guara class was not correctly modelled. Soleta showed a high sensitivity in test set validation as only one sample of Guara was misclassified. However, due to the erroneous assignment of two Guara samples and one Isabelona sample, the classification accuracy of Soleta class was reduced. The highest specificity was obtained for Marta, Pentacebas, and Avijor. For both models the prediction accuracy was high despite the genetic proximity of the varieties. However, the dried-powdered leaf model presented a higher accuracy in both the cross-validation and test set validation than that of the fresh leaf model. The homogeneity, and especially, the absence of water in the dried-powdered leaves seem to explain these results. The vibration of the water molecules generates broad bands in the near-infrared range that can hide other features, as it can be seen in the Fig.1 and in other studies34. However, in of fresh leaf model, three varieties reached a 100% classification accuracy in the test set validation, in contrast, this was only achieved for one variety in the dried-powdered model. Guara was the worst classified variety in both models. In contrast, Marta showed a high classification accuracy in both models. The full-spectrum PLS-DA model results were used as a reference to check that the variable selection process was correctly performed. Study of the most important variables. The VIP score, selectivity ratio, and vector of the regression coefficients were used to study the most important variables to discriminate between the classes. The results of these indicators are shown in Fig.2. 106 5 Scientific RepoRtS | (2019) 9:19810 | https://doi.org/10.1038/s41598-019-56274-5 www.nature.com/scientificreports www.nature.com/scientificreports/ Regarding the dried-powdered leaf model, the VIP score (Fig.2a) showed important variables located in the range from 4000 to 6000 cm−1. Similar results were obtained with the regression vector (Fig.2b). However, around 6600 cm−1, other important variables appeared in the selectivity ratio plot (Fig.2c). In the range from 10000 to 7000 cm−1, no important variable was detected. Therefore, it was decided to cut the spectra from 6700 cm−1 in order to include only relevant variables. Concerning the fresh leaf model, the VIP score and regression vector (Fig.2d,e) showed important variables in the range between 6000 and 4000 cm−1. A small gap was detected between 7000 and 6000 cm−1, and the variables inside this range did not help the discriminate study. However, around 7000 cm−1, important variables can be found. The same results were obtained for the selectivity ratio indicator (Fig.2f), except for the appearance of a band between 7000 and 6000 cm−1. The rest of variables were not useful to discriminate the almond tree varieties. Considering this, the fresh leaf spectra were cut from 7500 cm−1. In both cases, fresh and dried-powdered leaves, the variables selected contain the bands related to C-H, O-H and N-H bonds, which can mainly be associated to proteins and carbohydrates, and water too in the fresh leaf. The amount of these bonds and their configuration inside the molecules affect the shape of the spectrum and, therefore, have an influence in the spectral fingerprint of the varieties. However, the region removed corresponded to wavenumbers with no important bands in the raw spectra (Fig.1). Real class Data set Sensitivity Specificity Accuracy Dried-powdered leaves Avijor Cross-validation 0.971 0.994 99.0% Test set Validation 1.000 0.973 97.8% Guara Cross-validation 0.829 0.983 95.7% Test set Validation 0.800 1.000 96.7% Isabelona Cross-validation 0.971 0.960 96.2% Test set Validation 1.000 0.973 97.8% Marta Cross-validation 0.971 0.983 98.1% Test set Validation 1.000 1.000 100% Pentacebas Cross-validation 0.886 0.989 97.1% Test set Validation 0.933 0.987 97.8% Soleta Cross-validation 0.886 0.994 97.6% Test set Validation 0.933 1.000 98.9% Fresh leaves Avijor Cross-validation 0.857 0.977 95.7% Test set Validation 1.000 1.000 100% Guara Cross-validation 0.857 0.943 92.9% Test set Validation 0.600 0.987 92.2% Isabelona Cross-validation 0.657 0.943 89.5% Test set Validation 0.867 0.933 92.2% Marta Cross-validation 0.943 0.994 98.6% Test set Validation 1.000 1.000 100% Pentacebas Cross-validation 0.914 0.983 97.1% Test set Validation 1.000 1.000 100% Soleta Cross-validation 0.743 0.954 91.9% Test set Validation 0.933 0.960 95.6% Table 2. PLS-DA results of the classification of six varieties of Prunus dulcis using the entire spectra. Figure 1. NIR mean raw spectra of fresh (green dashed line) and dried-powdered (blue solid line) leaves. 107 115 Diferenciación varietal y control del estado fisiológico mediante cámara hiperespectral En este capítulo se muestran los resultados obtenidos a partir del trabajo realizado con una cámara hiperespectral, en colaboración con los compañeros de Agromillora Sur (Chile). La cámara hiperespectral empleada fue adquirida por Agromillora Sur con el objetivo de desarrollar una serie de proyectos. El interés mutuo por esta técnica dio lugar a una estrecha colaboración que culmino con una estancia en Chile, durante la cual se realizaron la mayor parte de los ensayos que se muestran en este capítulo. 1. Introducción La necesidad de aumentar la eficiencia y la productividad de los cultivos está generando que surja un gran interés, en el sector agrícola, por la aplicación de nuevas tecnologías que permitan monitorizar y extraer información que ayude en la gestión de los cultivos. En este sentido, una de las nuevas corrientes que más está creciendo es la agricultura de precisión, dentro de la cual se emplean herramientas tan diversas como vehículos aéreos no tripulados [1,2], satélites [3,4], diversos tipos de sensores [5,6] y cámaras espectrales [7,8], entre otros. Además de la utilización de la inteligencia artificial para el análisis de los datos [9,10]. En este contexto, se planteó la utilización de una cámara espectral para afrontar los objetivos del presente estudio. Con dicha finalidad, se diseñaron y se llevaron a cabo una serie de ensayos dirigidos al estudio de la discriminación varietal y el estado fisiológico de plantas de vivero. Al desarrollarse esta investigación en las instalaciones de Agromillora Sur, no se pudo disponer de las variedades de almendro de interés. Por ello, estas fueron reemplazadas por tres variedades de portainjerto de cerezo, como son Colt, Gisela 6 (G6) y Maxma 14 (M14). Los tres portainjertos escogidos son suficientemente similares como para ser confundidos por ojos poco entrenados, 116 aunque no presentan la misma proximidad genética encontrada en las variedades de almendro. No obstante, fueron consideradas como buenos especímenes de ensayo dada su importancia para Agromillora Sur. 2. Material y Métodos 2.1 Ensayos realizados 1. Estudio de diferenciación varietal: Para este estudio se emplearon 48 portainjertos de cerezo por cada una de las tres variedades estudiadas, Colt, Gisela 6 y Maxma 14. En total se analizaron 144 plantas. Todas ellas presentaban un tamaño comprendido entre los 6 y los 10 cm de altura (Figura 1). 2. Estudio sobre la detección de deficiencias nutricionales: Para este estudio se separaron de la línea de producción 26 plantas de la variedad Colt, las cuales fueron privadas de la fertiirrigación habitual durante un período de 4 semanas. Durante este período, únicamente se fueron regando con agua, siguiendo el ciclo normal de riego de la línea de producción. De esta forma, se indujo la aparición de deficiencias nutricionales en estas 26 plantas. A la hora del análisis, los Figura 1. Imagen de portainjertos de cerezo de las variedades Colt, Maxma 14 (M14) y Gisela 6 (G6). 117 espectros obtenidos de las plantas con deficiencias nutricionales fueron comparados con los espectros de 26 plantas de Colt que sí habían seguido el ciclo normar de fertiirrigación, las cuales se consideraron como plantas control. Todas ellas presentaban un tamaño comprendido entre los 10 y los 15 cm de altura. La Figura 2, muestra una imagen de las plantas empleadas en el ensayo de detección de deficiencias nutricionales. 3. Detección de la presencia de Pseudomonas syringae: Para estudiar la detección precoz de Pseudomonas, se procedió a la inoculación de Pseudomonas syringae se realizó a través de un método denominado infiltración. Este método consistió en inocular la bacteria mediante el uso de una jeringuilla sin aguja. Para ello la jeringuilla se llenó previamente con 1 ml de cultivo bacteriano líquido con una concentración de 106 Unidades Formadoras de Colonias (UFC). A continuación, se colocó la punta de la jeringuilla en contacto con la cara adaxial del limbo de la hoja y se ejerció presión del líquido sobre la misma mediante el embolo de la jeringuilla. Este proceso se repitió sobre varios puntos de una misma hoja en tres hojas distintas por planta. La infiltración se realizó con el máximo cuidado posible para evitar generar daños en el tejido foliar. Una vez realizada la inoculación, las Figura 2. Portainjertos de la variedad Colt empleados en el ensayo de detección de deficiencias nutricionales. 118 plantas fueron analizadas cada 2 días, realizándose un total de 11 mediciones. Para este estudio se emplearon 50 plantas de la variedad de portainjerto de cerezo Colt, 25 plantas fueron inoculadas y las otras 25 plantas restantes fueron empleadas como control. Las plantas control fueron sometidas al mismo proceso de infiltración, con la diferencia de que se empleó como solución de inoculación agua esterilizada en autoclave. Por último, resaltar que el presente ensayo de detección de Pseudomonas syringae se enfocó como un estudio preliminar. Dicho estudio fue realizado por mis compañeros de Agromillora Sur, junto con mi participación en el diseño experimental, asesoramiento en la adquisición de datos y en el análisis de los mismos. 2.2 Cámara Hiperespectral y adquisición de datos Para la realización del estudio se empleó una cámara hiperespectral de tipo pushbroom OCI Hyperspectral Camera (BaySpec, San José, CA, EUA). Las muestras fueron analizadas en un rango espectral comprendido entre los 400 y los 1000 nm (25000- 10000 cm-1), el cual incluye toda la región del visible (400-780 nm) y una parte del infrarrojo cercano (780-1000 nm). La cámara hiperespectral se situó en un soporte regulable en altura y las muestras se desplazaron manualmente por debajo de la cámara, de esta forma, se obtuvieron imágenes apicales de los portainjertos. Al soporte se le añadieron tres luces halógenas para estandarizar la fuente de luz. Se escogieron las luces halógenas porque tienen un espectro de emisión estable a lo largo de todo el espectro de estudio. La cámara hiperespectral fue operada a través de un ordenador al cual estaba conectada mediante dos puertos USB 3.0. La adquisición de datos se realizó en una sala bajo condiciones de luz controladas. 2.3 Tratamiento de los datos Previamente a la construcción de los modelos, los datos espectrales fueron pretratados matemáticamente aplicando un autoescalado. A continuación, los datos 119 se separaron aleatoriamente en dos subconjuntos. El conjunto de entrenamiento, compuesto por el 70 % de las muestras, fue utilizado para la calibración el modelo. Por otro lado, el conjunto de test, constituido por el 30 % de las muestras, se empleó para validar el modelo. Ambos grupos presentaban una distribución proporcional de las clases para evitar una representación no balanceada. 3. Resultados y Discusión 3.1 Resultados del estudio sobre la diferenciación varietal Los resultados del estudio de las huellas espectrales de las tres variedades de portainjerto de cerezo, Maxma 14 (M14), Gisela 6 (G6) y Colt, se muestran en el gráfico de la Figura 3. Figura 3. Espectros de reflectancia promedios de las variedades de portainjerto de cerezo Colt (naranja), Gisela 6 (G6) (gris) y Maxma 14 (M14) (azul). Se incluye un intervalo de confianza del 95% de la media (Estudio de la distribución normal realizado). 120 Se observaron diferencias significativas en dos regiones del espectro. Estas corresponden a las regiones comprendidas entre 414 a 430 nm (primera parte de la región del azul), y la región de 797 nm a 958 nm (infrarrojo cercano). También hay una amplia extensión donde no hay diferencias significativas entre los espectros promedio de las tres variedades, la cual corresponde a la región entre los 506 y 725 nm. Esta región se amplía si consideramos los solapamientos entre las variedades Colt y M14 en la región del azul, y entre M14 y G6 en la región del borde rojo (red edge, 680-730 nm). Toda esta región de solapamiento coincide con las longitudes de onda en las que se produce absorción de radiación electromagnética por parte de los fotosistemas de las plantas, como son la banda del azul (440-500 nm) y, especialmente, en la banda del rojo (600-700 nm). Esto es debido a que la absorción de luz por parte de los fotosistemas es un proceso esencial en la fisiología vegetal, lo que favorece a que sea un carácter muy conservado [11]. Por lo que respecta al infrarrojo cercano, se trata de una longitud de onda que no aporta suficiente energía para la fotosíntesis, pero al mismo tiempo, causa un perjudicial incremento de la temperatura en los fotosistemas debido a la gran absorbancia de esta radiación por parte de las moléculas de agua [12] (incremento del estado energético vibracional). Por esta razón, los organismos vegetales presentan una alta capacidad de reflexión de la radiación infrarroja como mecanismo de protección, lo que explica la gran reflectancia espectral observada en esta región. Las diferencias entre los espectros promedio de las tres variedades se asocian a la diferente capacidad de cada una de ellas para reflejar la radiación del infrarrojo cercano. Como se puede observar en la Figura 3, la región comprendida entre los 414 y los 430 nm se localiza en un extremo del rango de detección de la cámara, además está constituida por tan solo cuatro variables (mediciones). Ambos aspectos podrían afectar a su eficacia como región de interés para la diferenciación de las variedades de portainjerto. 121 Se construyó un modelo de clasificación Partial least square discriminant analysis (PLS-DA) con la finalidad de evaluar y validar las diferencias observadas entre los espectros promedio de las tres variedades. Los resultados del modelo PLS-DA se muestran en la Tabla 1. Se obtuvo una exactitud en la clasificación entre 97.7 y 100 % dependiendo de la clase. La variedad mejor identificada fue Gisela 6, siendo la única que alcanzó un 100 % de exactitud en la validación del test. Dicho resultado se vio favorecido por una menor variabilidad de las muestras que componían la clase Gisela 6 respecto a las otras dos clases. Este aspecto es observable a través de los intervalos de confianza mostrados en la Figura 3. Por otro lado, se puede extraer del análisis de la sensibilidad y la especificidad, que la tasa de error en las clases Colt y Maxma 14 se debe al error en la asignación de alguna muestra de la clase Colt en a clase Maxma 14. De esta forma, los resultados de modelo PLS-DA corroboran lo observado gráficamente en la Figura 3. Tabla 1. Resultados del modelo PLS-DA para la diferenciación de tres variedades de portainjertos de cerezo. Variedades Conjunto de datos Sensibilidad Especificidad Exactitud Colt Cross-validation 0.941 0.955 95.0 % Test set Validation 0.929 1.000 97.7 % Gisela 6 Cross-validation 1.000 0.971 98.0 % Test set Validation 1.000 1.000 100 % Maxma 14 Cross-validation 0.853 0.970 93.1 % Test set Validation 1.000 0.966 97.7 % 122 3.2 Resultados del estudio de deficiencia nutricional La Figura 4 muestra los espectros promedio de dos conjuntos de portainjertos de cerezo de la variedad Colt, uno de ellos compuestos por plantas con deficiencia nutricional y el otro compuesto por plantas sin deficiencia nutricional, al cual se le denominó control. Se observó una región espectral, comprendida entre los 500 y los 720 nm, en la cual existen diferencias significativas entre los espectros promedio de las plantas control y las plantas con deficiencia nutricional. Esta región incluye las bandas del azul, el verde y el rojo, además de la zona de transición entre esta última y el NIR, llamada borde rojo (red edge). En la región espectral descrita son claves los pigmentos que intervienen en la fotosíntesis, especialmente la clorofila. Por lo tanto, Figura 4. Espectros de reflectancia promedio de plantas de Colt control (verde) y plantas de Colt con deficiencia nutricional (roja). Se incluye un intervalo de confianza del 95% de la media (Estudio de la distribución normal realizado). 123 los resultados indican que la deficiencia nutricional afectó a la producción de clorofila, reduciéndose la concentración de esta en las hojas. Por otro lado, se construyó un modelo PLS-DA con el fin de evaluar mejor la posibilidad de diferenciar ambos grupos. Los resultados de dicho modelo se muestran en la Tabla 2. Tabla 2. Resultado del modelo PLS-DA para el estudio de deficiencias nutricionales Tal como se observa en la Tabla 2, se logró diferenciar perfectamente ambos grupos de plantas, alcanzándose una exactitud en la clasificación del 100%. Esto indica, que es posible identificar la presencia de deficiencias nutricionales a partir de la huella espectral, pudiendo ser clasificadas las plantas según la presencia o ausencia de dichas deficiencias. 3.3 Resultados del estudio de detección de Pseudomonas syringae Las plantas infectadas con Pseudomonas syringae y las del grupo control fueron monitorizadas durante 22 días. La Figura 5 muestra los resultados de tres de las once mediciones realizadas a lo largo del período de monitorización. Se puede observar como el espectro promedio del grupo control se mantuvo sin grandes cambios en las sucesivas mediciones. En cambio, la huella espectral promedio del conjunto de plantas inoculadas con Pseudomonas syringae, sí que experimentó una variación. Clases Conjunto de datos Sensibilidad especificidad Exactitud Control Cross-validation 1.000 1.000 100 % Test set Validation 1.000 1.000 100 % Deficiencia Cross-validation 1.000 1.000 100 % Test set Validation 1.000 1.000 100 % SPECIAL ISSUE - RESEARCH ARTICLE Varietal quality control in the nursery plant industry using computer vision and deep learning techniques Sergio Borraz-Martínez 1,2 | Francesc Tarrés 5 | Ricard Boqué 3 | Mariàngela Mestre 2 | Joan Simó 1,4 | Anna Gras 1 1 Department of Agri-Food Engineering and Biotechnology, Universitat Politècnica de Catalunya, Campus Baix Llobregat, Esteve Terrades 8, Castelldefels, 08860, Spain 2 Center of Initial Materials, Agromillora Iberia S.L.U, Ctra. BV-2247 km. 3, Sant Sadurní d'Anoia, 08770, Spain 3 Department of Analytical Chemistry and Organic Chemistry, Universitat Rovira i Virgili, Campus Sescelades, Tarragona, 43007, Spain 4 Fundació Miquel Agustí, Campus Baix Llobregat, Esteve Terrades 8, Castelldefels, 08860, Spain 5 Signal Theory and Communications Department, UPC Barcelona Tech, Barcelona, Spain Correspondence Sergio Borraz-Martínez, Department of Agri-Food Engineering and Biotechnology, Universitat Politècnica de Catalunya, Campus Baix Llobregat, Esteve Terrades 8, Castelldefels 08860, Spain. Email: [email protected]; [email protected] Funding information Spanish Ministry of Economy and Competitiveness, Grant/Award Numbers: AGL2015-70106-R, AEI/FEDER, UE, AEI/FEDER, UE, AGL2015-70106-R; Industrial Doctorates Plan of the Secretariat of Universities and Research of the Department of Economy and Knowledge of the Generalitat of Catalonia, Grant/Award Number: DI-COF 2017 Abstract Computer vision coupled to deep learning is a promising technique with multiple applications in the industry. In this work, the potential of this technique has been assessed in the classification of two varieties of almond trees (Prunus dulcis), Soleta and Pentacebas. For that, a convolutional neural network named VGG16 was used. The most appropriate configuration for model training was studied, which included the comparison between two different filling modes (reflect and nearest) in the data augmentation step, the evaluation of the batch size and the analysis of the image sizes. The robustness of the model was also checked, and information was obtained about how the model extracts the information from the images. The results showed that the reflect fill mode was more effective than the nearest one. The best results were obtained using batches with 30 and 40 images, with an image size of (224 ×224) pixels. The verification of the robustness proved the capability of the technique as a promising tool for plant varietal identification. KEYWORDS computer vision, convolutional neural network, deep learning, nursery plant, varietal mixture [Correction added on 30 January 2021, after first online publication: Peer review history statement has been added.] Received: 28 July 2020 Revised: 28 October 2020 Accepted: 1 November 2020 DOI: 10.1002/cem.3320 Journal of Chemometrics. 2021;e3320. wileyonlinelibrary.com/journal/cem © 2020 John Wiley & Sons, Ltd. 1of11 https://doi.org/10.1002/cem.3320 131 1|INTRODUCTION Computer vision coupled to deep learning (CV-DL) techniques are getting more popularity in different areas such as pedestrian detection and tracking, 1 human health, 2 and structural health monitoring in civil structures, 3 especially for their great capability of object recognition. This capability has been shown in the successive Large Scale Visual Recognition Challenge (LSVRC) competitions. 4 Many studies have been developed to solve different problems and overcome challenges in agro-food quality control, 5,6 precision agriculture, 7,8 control of fruits and vegetables, 9,10 plant disease detection, 11,12 and plant phenotyping. 13,14 We have applied CV-DL to solve the problem of varietal discrimination in the nursery plant industry. During the production process of the plants, varietal mixtures can appear in the batches due to traceability errors. When this happens and the product is commercialized, customers complain, the company must pay a fine, and its corporative image is damaged. Nowadays, the varietal identification is usually performed by means molecular methods based on DNA analysis, specifically DNA amplification by the polymerase chain reaction (PCR) 15 together with analysis of genetic variations, such as single nucleotide polymorphism (SNP). 16 Despite these molecular techniques have an excellent accuracy, they are very expensive for routine analysis of a large number of samples. Other studies have focused on the implementation of near-infrared (NIR) spectroscopy as a tool for varietal control. 17,18 In the literature, there are studies related to plant identification using CV. 19–22 In our case, the challenge is to discriminate between two almond trees (Prunus dulcis) varieties, Soleta and Pentacebas, which are morphologically very similar, genetically close, and almost indistinguishable for the human eye. Figure 1 shows images of both varieties. In other CV systems, the final classification relies on the features designed by the engineer. The programmer has to choose the features of the image that will be more representative to classify the leaves of the plant. The final quality of the system depends on this previous knowledge of the best features. But the designer does not know if the features applied are the best or another selection, or combination would produce better results. In this work, it was wanted to obtain a classification system without using any prior knowledge about the best-suited features. With DL, the programmer inputs data as well as the outputs expected from the data, and the system automatically searches the best features. 23 Therefore, CV-DL is more suitable to face complex problems, as the case of study. For that, a database with images from the two varieties of interest was created, and a convolutional neural network (CNN) was used to build a classification model. The specific objectives of the study are (1) to study the training configuration of the neural network; (2) to explore what features of the plant is the model using in the modeling/ training step; and (3) to check the robustness of the technique. 2|MATERIAL AND METHODS 2.1 |Image acquisition The red–green–blue (RGB) images used were acquired using a photo studio box and a Nikon D5300 camera. Two LED lamps (Color temperature 5500 K, color rendering index of 93%, and 13 000 lumens) were placed at the bottom of the box to achieve the correct illumination of the plant. The position of the light source was optimized in order to highlight FIGURE 1 Images of almond tree plants. (A) Pentacebas variety; (B) Soleta variety 2of11 BORRAZ-MARTÍNEZ ET AL. 132 the features of the leaves: the venation and the borders. To avoid pictures with too much light intensity or reflectance effects, a textile diffuser was placed between the light source and the canopy of the plant. The images were collected from the top of the plants, thus obtaining an apical view. Before image acquisition, the setup of the camera was adjusted (diaphragm opening = f/29, shutter spit = 1/30, and International Organization for Standardization [ISO] sensitivity = 200). This parameter set was selected to produce a well-balanced histogram. In total, 824 images (one image per plant) were taken from two P.dulcis varieties, 412 images of Soleta, and 412 of Pentacebas. Table 1 shows more details about the number of images used in the study. 2.2 |Image preparation The rectangular raw images obtained from the camera (image size of 6000 ×4000 pixels) were cropped to an image size range between 4000 ×4000 and 2500 ×2500 pixels to obtain squared images, which constituted the dataset used in this work. The model was adjusted to be fed with images of 224 ×224 pixels, so just before introducing them into the model, their resolution was reduced automatically to 224 ×224 pixels. Moreover, the pixel component levels were normalized (1.0/255) in order to adjust their values between 0 and 1. These two last modifications are indispensable to decrease the computation time. The whole dataset was randomly split into a training set (75% of images), a validation set (15% of images), and a test set (10% of images). Table 1 shows more details about the number of samples of the three datasets. 2.3 |Convolutional neural network A CNN is a type of network architecture commonly used in image analysis. It is characterized by having a reduced number of tunable parameters, because each neuron of the convolutional layer represents a small kernel that is applied to the previous layer using a convolution operator. Therefore, not all neurons in one layer are connected to all neurons in the previous layer. The neurons of the CNN form three dimensional layers, with height, width, and depth, also named channels. 24 Next to the convolutional layers, there are pooling layers that reduce the resolution of the output features in higher-level layers. In this way, higher layers have a global view of the image contents while lower layers are specialized in detecting local features. The Vgg16 CNN 25 was used to perform the study. Vgg16 was developed by the Geometry Group at the University of Oxford to obtain state of the art results in the ILSVRC-2014 competition. 4,26 The convolutional base of the CNN is constituted by 16 layers, which are ordered in five blocks. Moreover, after the convolutional base, the Vgg16 contains a classifier that is composed by three fully connected layers. Blocks 1 and 2 have two convolutional layers each one and 64 and 128 filters, respectively. Blocks 3–5 contain three convolutional layers and 256, 512, and 512 filters, respectively. Every convolutional layer use filters with a receptive field of 3 ×3. The convolution stride is 1 ×1 pixel, and the spatial padding of the convolutional layer input is such that the spatial resolution is preserved after convolution. 25 In addition, one max-pooling layer performed over a 2 ×2 pixel window is located at the end of each block. The classifier is composed of three fully connected layers. Figure 2 shows a scheme of the Vgg16 architecture. The convolutional base of the Vgg16 neural network was downloaded pretrained (with the parameters adjusted) with ImageNet dataset 27 from TensorFlow. 28 ImageNet is formed by 1.4 million labeled images and 1000 different classes, and it is commonly used to pretrain CNNs in CV. Then, a new classifier was added, constituted by one flatten layer followed by two dense layers. The CNNs learn local features of the input image. For this reason, the purpose of these fully connected layers is to collect the local information and combine it through nonlinear filtering, which is learned TABLE 1 Details of the number of samples in the datasets used Percentage % Pentacebas Soleta Overall dataset Training set 75 309 309 618 Validation set 15 62 62 124 Test set 10 41 41 82 Total 412 412 824 BORRAZ-MARTÍNEZ ET AL.3of11 133 from the training set. Usually, a minimum of two fully connected layers is used. The flatten layer allows transforming the 3-D tensor of the CNN to a 1-D tensor, which is required by the dense layer. The first dense layer included 256 neurons with rectified linear unit (ReLU) activation. This layer is necessary because it integrates all the local features learned by the last CNN layer, taking into account nonlinear combinations. Otherwise, without this inner layer, outputs would be a form of regression of the convolutional layers. Finally, the second dense layer contained one neuron with sigmoid activation. The output of the sigmoid will be an estimation of the confidence of having an input image of one or the other class. During the training process, only the classifier and the convolutional layers of Block 5 were trained. The rest of parameters retained the values acquired from the training with the ImageNet dataset. We decided to train the Block 5 because this way, it is possible to improve the accuracy of the classification model. This method, which involves training the last CNN layer, is known as Fine-tuning. 2.4 |Data augmentation study To avoid overfitting, a data augmentation technique was used. The overfitting occurs when the model fits very specific features of the training images that are not representative of the whole class. Thus, the accuracy in the classification of new images is reduced. Data augmentation consists of obtaining multiple images from the original one. This is achieved by modifying the original image. The common modifications are rotation, shear, horizontal flip, zoom, and shift of the image. The goal is to increase the diversity of the training set, which helps to improve the robustness of the model and its prediction accuracy. When using data augmentation, it is important to check the modified images. Misuse of data augmentation can lead to a reduction in the effectiveness of the model. An important aspect of data augmentation is what to do with pixels that FIGURE 2 Vgg16 neural network architecture 4of11 BORRAZ-MARTÍNEZ ET AL. 134 are empty due to image rotation or shifting. This can be dealt with using the argument fill_mode. This argument defines the method for filling empty pixels. There are several strategies, the most common being nearest and reflect. The command nearest fills the pixels with the values of the contiguous pixels. In contrast, reflect generates a specular image. Both methods were compared to investigate which one generates less differences with the original images and thus leads to better results in the test. Data augmentation was only applied to the training set because in the validation and test sets, it is preferable to use original images. In addition to the fill mode, other image modifications were applied: shear in a range of 0.2, zoom in a range of 0.4, horizontal flip, random rotation in a range of 180, and width and height shift in a range of 0.2. 2.5 |Batch size and optimizer Batch size is an important aspect to consider before starting to train a DL model. A batch is a set of input images that are passed through the network with fixed weights. The loss function is computed, and gradient backpropagation is applied to modify the weights for each batch. The steps per epoch (weight updates) come from the division of the number of images of the training/validation set by the batch size assigned. The validation step consists of the division of the number of images contained in the validation set by the batch size. Both concepts show the number of iterations by epoch. If the batch size is small, the number of iterations will be high, but each learning step will be performed with few images, which means little information. In contrast, if the batch size is large, the number of iterations will be low, but each learning step of the model will be robust because it will be based on many images. We studied different batch sizes to evaluate what ratio between number of images per batch and number of iterations per epoch was the most suitable. The batch sizes used were 20 (30 steps per epoch/6 validation steps), 30 (20 steps per epoch/4 validation steps), and 40 (15 steps per epoch/3 validation steps) samples per batch. The number of epochs was defined based on the convergence between training and validation accuracies. Moreover, the progression of the classification error (loss value) along of the training process was taken into account. The models were trained in a range between 80 and 90 epochs, because overfitting was observed above 100 epochs. 2.6 |Comparison between image sizes The Vgg16 CNN can be fed with two image sizes, 150 ×150 or 224 ×224 pixels. The advantage of using 224 ×224 pixel images is their higher resolution. This allows keeping more fine features, which can provide useful information for the identification and the discrimination of the classes. However, this strategy has two main disadvantages; first, the number of operations to adjust the parameters of the convolutional base of the Vgg16 neural network increases; second, the number of parameters of the classifier also increases, which translates in longer computing times. In this study, 224 ×224 pixel images were used because we decided to prioritize resolution instead of time. However, we compared the performance when using images of 224 ×224 and 150 ×150 pixels. The dataset images, with a size range between 4000 ×4000 and 2500 ×2500 pixels, were automatically reduced to images with a resolution of 150 ×150 pixels through adjusting the setup of the model. To perform the comparison, we applied the training setup resulting from the study of the previous sections. 2.7 |Model robustness assessment The robustness of the model trained with the configuration mentioned above was studied. To perform this analysis, five models were built using different random splits of the images into training, validation, and test sets. The variability in the test accuracy obtained helped us to assess the robustness of the DL technique to classify the Prunus varieties. 2.8 |Visualization of the intermediate activations It is interesting to know how the model performs the analysis of the images in order to understand how it works. To try to answer this question, an input (image) was introduced, and the output was observed in different convolutional BORRAZ-MARTÍNEZ ET AL.5of11 135 layers. The output is the activation of the layer, which provides information about how the input is decomposed into the different filters learned by the network. 23 By doing this, feature maps were created, which are composed of channels or filters. Each channel performs a specific analysis of the input, although all the filters in a layer perform a similar decomposition of the input image. This characteristic allows us to have an overview of the features extracted by each layer of the neural network. Finally, to plot the feature maps, a 2-D image was created with an independent plot of the contents of every channel of a layer of the CNN. 3|RESULTS AND DISCUSSION 3.1 |Data augmentation study The images were analyzed by using the nearest and reflect fill modes. Several modified images were obtained using both methods. Figure 3 shows three examples from each method. It is important to remark that the images shown in Figure 3 are an example of the images that are feeding the neural network. Regarding the nearest fill mode, despite the modified images showed an appearance very similar to the original ones, several anomalies or deformations were detected, which are highlighted with a circle in Figure 3. These distortions arose because some of the empty pixels were filled using the value of the leaf pixels, which resulted in an elongation of the original leaves. The presence of this deformed leaves in the training images represents a significant alteration of the original images. Concerning the reflect fill mode, the modified images showed an alteration too, which is highlighted with a square in Figure 3. The reflect fill mode generated a deformation of the original images too but with the difference that created a specular image of the original one. Table 2 shows the results of the DL models. Using the nearest fill mode, an accuracy average of 95.1% in the test set was obtained, whereas the reflect fill mode provided an average accuracy of 96.7%. When the results obtained using the different batch sizes, in all cases, better results were obtained with the reflect fill mode. This result confirms that image deformations caused by the nearest fill mode negatively affected the accuracy of the model. To understand better this result, it is important to remark that data augmentation is only used during the training of the model. Therefore, the FIGURE 3 Study of the image modifications performed by nearest and reflect fill modes 6of11 BORRAZ-MARTÍNEZ ET AL. 136 model will learn any alteration generated by data augmentation, even if the features are false. In addition, these deformations will not be present in the validation and test sets because data augmentation was not applied there. Thus, the nearest fill mode increased the gap between the training set and the test set. 3.2 |Batch size and optimizer study Three different batch sizes, 20, 30, and 40, were studied. As it can be seen in Table 2, the best result of this comparison was achieved using the reflect fill mode together with a batch size of 30 and 40, reaching a 97.5% accuracy in the test set. In contrast, the worst result was obtained by applying the nearest fill mode together with a batch size of 20. Although a batch size of 20 allows a greater number of iterations, each learning step is performed based on a smaller number of images, and this affects the test accuracy. It seems more adequate to use a batch size of 30 or 40 images. Both provided the same result using the reflect fill mode, but the batch size of 30 achieved a better accuracy using the nearest fill mode. 3.3 |Comparison of image sizes Table 3 shows the results of the comparison between the different image sizes. With 150 ×150 pixel images, an accuracy of 95.1% was obtained in the test set, which is the same accuracy obtained using 224 ×224 pixel images, but with a batch size of 20. This indicates that using images of 150 ×150 pixels, it is possible to obtain results comparable with those obtained using images of 224 ×224 pixels. However, a better comparison is performed with the results obtained using a batch size of 30. In this case, the model trained with 224 ×224 pixel images provided a better result but took an average of 16.4% more computing time than the model trained with 150 ×150 pixel images. When using 224 ×224 pixel images, the Vgg16 had 13.5 million trainable parameters, while using 150 ×150 pixel images the network had 9.1 million of trainable parameters, that is, a 32.6% less parameters. The increase in parameters is higher than the increase in training time. The differences in accuracy are not so great, but the time could be important depending on the requirements of the application. 3.4 |Assessment of model robustness To assess the robustness of the model and discard the possibility that a single choice of the test set was favorable to obtain good results, six models were built with different training, validation, and test sets, which were randomly split. The results are shown in Table 4. TABLE 2 Result obtained in data augmentation and batch size studies Data augmentation Batch size Test accuracy Nearest 20 93.9 30 96.4 40 95.1 Reflect 20 95.1 30 97.6 40 97.6 TABLE 3 Comparison between images with 150 ×150 and 224 ×224 pixels Size of the images Test accuracy Training time (s) 150 ×150 95.1 230 224 ×224 97.6 275 BORRAZ-MARTÍNEZ ET AL.7of11 137 TABLE 4 Study of the robustness of the model Models Test accuracy 1 96.3 2 96.3 3 97.6 4 96.3 5 97.6 Average 96.8 FIGURE 4 Intermediate activations of the neural network 8of11 BORRAZ-MARTÍNEZ ET AL. 138 The average accuracy obtained was 96.8%, which was a little lower than the best result achieved, 97.6% accuracy, which was reached twice. It is important to note that the difference between 96.3% and 97.6% corresponds to just a mistake in one image. Therefore, all the models showed similar behavior. It is important to highlight that this robustness study was developed under specific illumination conditions, which are described in the Section 2. Therefore, a change in these conditions could yield different results. For this reason, it will be important to keep the same illumination conditions in future implementations. 3.5 |Feature maps The feature maps of the 18 layers of the convolutional base of the Vgg16 (convolutional and max pooling layers included) were studied. From these 18 layers, we chose three representative layers of the CNN, because of the large size of the images. Figure 4 shows the progress of the image along the neural network by visualizing the intermediate activations. It is important to note that due to the high number of filters in each layer, Figure 4 only shows a subset of them. In the first layers, which were represented by the block1_conv1 layer, it is easy to identify the plant in the image. This indicates that this layer works with the whole image and retains almost all the information present in the original image. For this reason, the activation of the filters showed images like the input image. The channels of this first layer process low-level information such as contours, edges, corners, and therefore extract information about the leaf shape and margins. As we move into the neural network, the plant is increasingly more difficult to recognize. In the block3_conv2, which is located in the middle of the network, it was only possible to identify small parts of the plants because the feature map was less visually interpretable. This layer encodes higher-level features, such as parts of the leaves, which implies less information about the visual contents, but more information related to the class of the input image. When observing the activation of the last layer of the convolutional base, block5_- conv3, the abstraction level is very high, and no part resembling the plant can be identified. As the block5_conv3 layer encodes higher-level concepts than block3_conv1 layer, the visual interpretation of the feature maps is even more abstract. When comparing the resulting image in each filter of the same layer, we were able to observe the activation similarities between them, which reaffirms the idea that each layer works as an analysis block, where each channel performs an own extraction of information but all of them in the same analysis level. It is also remarkable that, as we go into the CNN layers, the number of filters in blank increases. In the first layer, all filters are activated by the input image, but in the block3_conv2, one filter in blank was found, and in the last layer, the number of filters in blank was 19. This means the pattern encoded by the filter is not found in the input image. 23 4|CONCLUSIONS In this study, we investigated the most suitable training configuration of a CNN to obtain the best results in the classification of two almond plant varieties of P.dulcis,Soleta and Pentacebas, and the potential of CV together with DL models was evaluated. The importance of the argument fill_mode in the configuration of the data augmentation has been demonstrated. The results indicate that the reflect mode is more suitable than the nearest mode, because the latter generated some distortions of the images, which affected the accuracy of the model. In addition, the study of the batch size showed that batches with 30 or 40 images are the best option. The advantages and disadvantages of working with 224 ×224 or 150 ×150 pixel images were also analyzed. We found that the test accuracy was better for 224 ×224 pixel images but with an increase of the computing time. The robustness of the technique has also been proven. Finally, the study of how the neural network works allowed us to have an idea of the image analysis done by the model and what features of the plant are used to discriminate the varieties. The results of this study show the capacity of CV-DL to discriminate P.dulcis varieties. Future works will try to expand the dataset and the number of varieties and to assess the use of specific images from different structures of the plant, such as leaves and their venation. BORRAZ-MARTÍNEZ ET AL.9of11 139 the deterioration of their corporative image. 2 In this context, we propose using computer vision based on deep learning techniques (CV-DL) as a possible solution to sort out this problem. Computer vision is an old discipline that has recently undergone a qualitative improvement thanks to the use of deep learning algorithms. The goals of computer vision are to achieve a higher level of operational efficiency and productivity, as well as a higher level of automatization. 3 Moreover, it is one of the new technologies that drives the socalled Industry 4.0. Deep learning is a specific subfield of machine learning, which in turn is included in the field of artificial intelligence. Deep learning could be defined as a modality of learning representations from data that emphasize learning successive layers of increasingly meaningful representations. 4 Each layer may be viewed as a nonlinear transform of the outputs of the precedent layer. The transformation parameters (weights) are learned using a supervised strategy. In other words, it consists of training a model from examples of the classes that we want to characterize, in our case the two varieties of almond trees. During the training process, the model calculates the classification error, which is represented as a mathematical function named loss, and with a small set of instructions, it autonomously modifies parameters (weights) of the model to reduce the loss, which allows improving the accuracy of the classification. 5 This process is known as model learning. The deep in deep learning is a reference to the large number of interconnected successive layers, stacked on top of each other and composed of computational neurons, which is called neural network. Nowadays, neural networks involve tens or even hundreds of layers. The structure of deep learning neural networks is divided into three sections. The first is the input layer, which receives the input images that feed the model. The middle section contains the hidden layers, a group of successive layers where the representation of the data takes place. This part constitutes the body of the neural network. Finally, the last section receives the name of output layer. This layer predicts the class to which a sample belongs based on the representation made by the hidden layers. It was decided to use CV-DL because, in other computer vision systems, the final classification is based on the features designed by the engineer. Then, the final quality of the system depends on this previous knowledge of the best features. However, in the case of study, the most important features are very difficult to determine. Therefore, it was considered more appropriate to use CV-DL. In the agronomic sector, the use of computer vision along with deep learning algorithms is recent but is becoming a promising technique with growing popularity. 6 This technology is fast and does not modify or destroy the samples. Moreover, it can be easily implemented or adapted to the production line, enabling the collection of useful information that can be used as a quality control tool or to monitor a process. These advantages make computer vision an attractive tool for the agricultural industry. Despite being an emerging technology, there are several studies where CV-DL has been applied, for example, for crop type classification 7,8 : crop yield estimation, 9,10 plant phenological estimation, 11,12 or even plant recognition. 13,14 In short, CV-DL techniques have great potential in the automation of the agronomic industry, and their capacities and efficiency have been improved in the last decade. 15,16 The objective of this study was to develop a methodology to implement computer vision system for the control of plant varieties in the nursery plant industry and evaluate its capabilities. The study was developed working with two varieties of Prunus dulcis,Pentacebas and Soleta, which are genetically close and almost morphologically indistinguishable. Three datasets of different image scales were used, namely, whole plant, leaf, and venation. It is important to note that this study focuses on the automatic control of nursery plants in the greenhouse, which means we have avoided the manipulation of the plants. This way, we tried to simulate a possible automatic line of image acquisition without sampling. The specific objectives were (1) to compare between different image scales: whole plant, leaf, and venation, to determine which is most suitable for varietal discrimination; (2) to determine which morphological characteristics are most relevant for the classification of varieties; and (3) to evaluate the neural network complexity required for the case of study. 2|MATERIAL AND METHODS 2.1 |Image acquisition The RGB images used were acquired using a Nikon D5300 camera. To keep homogeneous light conditions, plants were introduced inside a professional photo studio box with a dimension of 80 80 80 cm. The photo studio had integrated two LED lamps (color temperature 5,500 K, color rendering index of 93%, and 13,000 lumens), which were placed at the bottom of the box. The idea was to illuminate the leaves from the bottom up to highlight their venous architecture. A textile diffuser was positioned between the canopy plant and the light source to avoid the reflectance of 2of10 BORRAZ-MARTÍNEZ ET AL. 146 the LED lights on the leaves. The camera was placed over the box and subjected by a holder; this way, apical images were collected. This method was developed in a previous study. 17 A balanced sampling was performed and 412 images per variety were used, which means 824 images for each dataset. In total, 2,472 images were employed in the study. Table 1 shows more details about the number of samples used in the study. 2.2 |Image preparation The whole plant image dataset was cropped in 4,000 4,000, 3,000 3,000, and 2,500 2,500 pixels; the leaf dataset was composed of images with a range between 2,000 2,000 and 1,125 1,125 pixels; finally, the images of the venation dataset were cropped in a range of 600 600 and 300 300 pixels. Different images sizes were used to increase the robustness of the model against scale variations. The leaf and venation datasets were obtained from the same set of original images by different cropping factors, so that leaf and venation datasets were constituted by cropping the images contained in the whole plant dataset. This strategy was chosen to reduce the acquisition time of the photos and to increase the robustness of the comparison. In addition, the resolution of all images in all sets was reduced to 224 224 pixels before introducing them into the model. Moreover, the pixels were normalized (1.0/255) with numeric values between zero and one. The reduction of resolution was performed to reduce the computational cost and the normalization to accelerate learning in the deep learning models, thereby decreasing computational time. Figure 1 shows examples of the images of the three data sets used. The set of images used in this study was randomly split into a training set (75% of the images), a validation set (15% of the images), and a test set (10% of the images). Table 1 shows more details about the datasets. The validation set was used to verify the correct convergence of the model and to optimize the selection of hyper-parameters. The test set was used for the final assessment of the network performance. 2.3 |Data augmentation Overfitting tends to occur when neural networks work with small datasets (<1,000 images), and the model fits very specific features of the training images that are not representative of the whole class. Therefore, it reduces the capability of the model to correctly classify images that do not belong to the training dataset. Hence, overfitting means that the system achieves excellent accuracy in modeling the training set at the cost of reducing accuracy in the prediction of validation and test datasets. To reduce overfitting, data augmentation was employed. Data augmentation allows increasing the training data set from the available data. This method consists of generating additional images by modifying the original ones using pre-established random transformations. 18 In this way, it is possible to increase the diversity and the number of images during the training process. Data augmentation reduces overfitting and helps the model to better predict validation/test data and to improve its classification accuracy and robustness. 19 Data augmentation was only applied to the training set, and it consisted of shear in a range of 0.2, zoom in a range of 0.4, horizontal flip, random rotation in a range of 180, width and height shift in a range of 0.2. 2.4 |Convolutional neural network A convolutional neural network (CNN) is a type of network architecture that is widely used in image analysis; for this reason, CNN is commonly used in computer vision for image recognition. 20 Its structural design made it possible to TABLE 1 Description of the study Percentage % Pentacebas Soleta Overall dataset Overall study Training set 75 309 309 618 1,854 Validation set 15 62 62 124 372 Test set 10 41 41 82 246 Total 412 412 824 2,472 BORRAZ-MARTÍNEZ ET AL.3of10 147 reduce the number of parameters of our model, which means a significant reduction in cost and computation time. The layers of a convolutional network have neurons arranged in three dimensions, so the layers have width, height, and depth. Neurons in a convolutional layer are applied using convolution to small local regions of the previous layer, so we avoid wasting completely connected neurons. 5 The convolution is translationally invariable, and kernels may detect different types of features at different scales in every layer. Furthermore, CNN also contains pooling layers that reduce the amount of information obtained from the convolutional layers, creating a condensed version of the information they contain. In this study, two convolutional neural networks have been used: the VGG16 convolutional neural network 21 and the Shallow network. Both networks have the same types of layers, but with different structural complexity. Figure 2 shows the scheme of both neural networks. The Shallow CNN was created specifically for this study. The goal was to build a CNN with less structural complexity than the VGG16 network, that is, with a lower number of parameters. The convolutional base of the Shallow CNN is organized in five blocks. Blocks 1 and 2 contain two convolutional layers, and blocks 3–5 contain one convolutional layer. Concerning the number of filters, blocks 1 and 2 have 32 and 64 filters, respectively. Blocks 3–5 have 128 filters. Every convolutional layer uses a filter with a receptive field of 3 3. The convolution stride is one pixel, and the spatial padding of the convolutional layer input is such that the spatial resolution is preserved after convolution. In addition, one maxpooling layer over a 2 2 pixel window is located at the end of each block. The classifier is composed of two fully connected layers. The first one has 512 neurons with ReLu activation. The last one has one neuron with sigmoid activation. VGG16 was developed by the Geometry Group at the University of Oxford to obtain the state-of-the-art results in the Large Scale Visual Recognition Challenge (LSVRC-2014) competition. 21 This architecture has become very popular and widely used in many image recognition problems. It consists of 16 layers divided into five blocks, which are named convolutional base, together with a fully connected layer named classifier. Every block in the VGG16 is formed by a concatenation of two or three convolutional layers followed by a pooling layer with a stride of 2 2. The classifier is FIGURE 1 Examples of images used in the study 4of10 BORRAZ-MARTÍNEZ ET AL. 148 composed of three fully connected layers. The convolutional base of the VGG16 neural network was downloaded from Keras (https://keras.io/). Then, it was inserted into a new classifier, which consisted of one flattened layer followed by two dense layers. The convolutional neural networks learn local features of the input image. For this reason, the purpose of these fully connected layers is to collect the local information. The flatten layer allows transforming the 3D tensor of the CNN to a 1D tensor, which is required by the dense layer. The first dense layer contained 256 neurons with ReLU activation. This layer integrates all the local features learned by the last CNN layer, taking into account nonlinear combinations. Otherwise, without this inner layer, outputs would be a form of regression of the convolutional layers. The second dense layer had one neuron with sigmoid activation. The sigmoid activation means that the output of the neural network will be in a range between zero and one. As in this case, there are two classes; each image was encoded with a value above 0.5 if the image belonged to the Soleta class and below 0.5 if the image belonged to the Pentacebas class. The complexity of the structure increases the time and the difficulties during the training process. Therefore, it was considered interesting to compare both CNN to assess the complexity required to develop the plant varietal control tool. 2.5 |The training steps 2.5.1 | Training of the VGG16 CNN To facilitate the training process and try to get better results, the transfer learning technique was used. Transfer learning 22 is one of the most important techniques in deep learning as it allows us to use a pre-trained neural network. 23,24 FIGURE 2 Schema of the two convolutional neural networks used. (A) VGG16; (B) Shallow BORRAZ-MARTÍNEZ ET AL.5of10 149 This is an advantage because training a neural network from scratch requires a huge dataset and a lot of computation time due to the large number of parameters that need to be adjusted. Through transfer learning, it is possible to download a pre-trained network and use its parameters as an initial good weight guess, and the fine tune the model by training it with our dataset. In this way, the representations previously learned by the network can be used to extract interesting features from new samples. In this study, a VGG16 convolutional network model, pre-trained with the dataset of ImageNet, was downloaded. This database includes 1.4 million labeled images from 1,000 different classes. ImageNet is one of the most common datasets used to pre-train CNNs in computer vision. There are two modalities of transfer learning, feature extraction and fine-tuning. Based on the results obtained in previous tests, 17 fine-tuning was chosen. Fine-tuning 4 consists of freezing the parameters from the initial layers and training the last layers of the convolutional base, specifically the layers from block 5, together with the classifier. In this way, it is possible to slightly adjust the more abstract representations of the model being reused, in order to make them more relevant for the problem at hand. 4 Through this strategy, the trainable parameters were reduced by 45.4%, from more than 16 million to 9 million. The three datasets were trained using the same strategy, except for the number of epochs, which was chosen based on the convergence between training and validation, shown by the accuracy and loss. The model of the whole plant dataset was trained during 90 epochs because it tended to suffer from overfitting above 100 epochs. In contrast, the leaf and venation models were trained during 110 epochs. The batch size was 30 for the three datasets, and a learning rate of 10 5 was used. Regarding the optimizer, an Adam with a beta 1 =0.9, beta 2 =0.999, and epsilon =1e0.7 was used. Besides, a dropout of 0.5 was applied to avoid the overfitting and to increase the robustness of the models. 2.5.2 | Training of the shallow CNN Since the Shallow network has fewer parameters than VGG16, it was preferred to train it from scratch, allowing us to simplify the process. The strategy followed consisted of training the model using an RMSprop optimizer with a learning rate of 10 5 during 40 epochs. Then, the CNN was trained again with 30 epochs but changing the RMSprop optimizer by the Adam optimizer (beta 1 =0.9, beta 2 =0.999, and epsilon =1e0.7). Throughout the training process, a batch size of 30 epochs was used. 2.6 |Gradient-weighted class activation mapping (grad-CAM) It is not just important to know what type of dataset works best, but it is also interesting to assess why this happens. In the same way, visualization of the activation maps may help to understand missclassifications. The interpretation of how CNN works to assign a label is usually difficult. 25 Grad-CAM 26 is a technique that consists of producing heat maps of class activation over input images. A class activation heat map is a 2D grid of scores associated to a specific output class, computed for every location in any input image, indicating how important each location is for the class under consideration. 4 This way, false color images are used to highlight the most significant regions of the image used in the final classification. Therefore, we relied on the information provided by the Grad-CAM technique to know what features the model used to classify the two classes of each dataset. 3|RESULTS AND DISCUSSION 3.1 |Comparison between datasets The images were collected simulating a typical production line that could be found in any nursery plant company. The idea was to mimic an automatic image acquisition process. Table 2 shows the results obtained in the deep learning models. The model for the leaf dataset provided the best result in the test. The plant and venation datasets got the same accuracy, slightly below the leaf dataset. Before starting the discussion, it is important to remark that there is a resolution reduction step just before the images are introduced in the CNN. So that, in the images of the whole plant dataset, the features related to the 6of10 BORRAZ-MARTÍNEZ ET AL. 150 edge of the leaves and the venation are negligible. This means that the whole plant only provides information about the color, the shape, the relation between length/width of the leaf, and the disposition of the leaves. Concerning the images of the leaf dataset, they contain information about the shape, edge features, and principal veins of the leaves. These characteristics seem to be the most critical to discriminate between the two classes, Soleta and Pentacebas. Using the leaf dataset, a 98.8% of accuracy was achieved in the test, which means the model only misclassified one image. This misclassification corresponds to a Pentacebas image that was erroneously assigned to the Soleta class with a value of 0.61. It is important to remark that the rest of the images, which were correctly classified in both Soleta and Pentacebas classes, had confidence values very close to one and zero, respectively. This result is surprisingly good considering that they are two genetically very close varieties of P. dulcis. This agrees with the botanical science that uses leaf feature taxonomic keys for plant identification. 27,28 Regarding venation, some studies highlight the usefulness of the venation pattern for the identification of vegetal species. 29 In our study, the venation model provided good results but worse than the ones of the leaf dataset. We believe that the methodology chosen to collect the venation images might not be the most suitable. Although the source of light was positioned under the plant to emphasize the venation characters, the illumination was not homogeneous in all the leaves. This lack of homogeneity may have increased the variability within a class, thus increasing the difficulty of varietal identification. Perhaps this approach is underestimating the real potential of venation for varietal discrimination, but this study focused on the automatic acquisition of plant images. Thus, we did not consider sampling individual leaves to obtain better images of the venation. 3.2 |Important features The class activation heat map for each class is shown in Figure 3. For the whole plant, high activation regions of the CNN can be appreciated. These areas were located mainly in the center of the leaves. Leaves with greater activation than others can also be seen, which is because the grad-CAM image represents the features analyzed by one neuron. Other CNN neurons generate complementary activation, so this heat map is extrapolated to the other leaves. Concerning the leaf dataset, a high activation was observed in the center and edges of the leaves. This indicates that the shapes of the edge of the leaves, along with the venation, are interesting features for identification and discrimination between the two classes. By comparing the heat map activation of leaves and whole plants, it is easy to find similarities. This implies the model searches and uses the same features in both cases. The main difference between leaf and whole plant datasets is the scale. In the whole plant dataset, more leaves can be used, each with its own features, but the clarity of the edge shape and the venation is less than in the leaf dataset due to the reduced resolution. In contrast, in the leaf dataset, there is less information due to the limited vision field that is focused on fewer leaves, but the edges and venation are observed with a better resolution than when the image is of the entire plant. Plant-scale images provide a global image compared to leaf-scale images. Despite this, the leaf scale ones offer better information to classify the images correctly because they show better the characteristics that differentiate both classes. The venation dataset did not show any high activation zone, in contrast to what was observed in the other two cases. This indicates that there are no specific features useful for classification other than the entire image. Thus, all the information contained in the image is important for discrimination. By looking at Figure 3 from top to bottom, it can be observed that the model is focused on the center of the leaves in the three datasets, which means the most important characteristics are located in the center of the leaf, that is, the venation. Despite the result obtained with the venation dataset being good, it is not the best due to the variability caused by the position of the leaves in respect to the source of light, which affected the visualization of the veins of the leaves. The way the beam of light pass through the leaves makes the veins are clearly observed in some images but are difficult to appreciate in others. This issue could have made classification difficult as there was no clear pattern. The leaf dataset was the best in the comparison, which can TABLE 2 Results obtained in the comparison of datasets Dataset Test accuracy (%) Whole plant 97.6 Leaf 98.8 Venation 97.6 BORRAZ-MARTÍNEZ ET AL.7of10 151 be explained because leaves contain information extracted from the venation, together with other important features, such as the shape of the edge. Due to the method chosen to collect the images, edge shape was a more robust characteristic than venation, and this can help to improve the discrimination between Soleta and Pentacebas varieties. 3.3 |Comparative between CNNs The leaf dataset was used to compare the VGG16 and Shallow neural networks, because it was the dataset producing the best results in the previous section. Table 3 shows the results of the comparison between both CNNs. Concerning the classification rate, the Shallow network reached a 93.9% of accuracy, which is a good result given the difficulties to discriminate both P. dulcis varieties. Despite the successful classification, the Shallow network provided a classification rate of almost 5% lower than the VGG16 network. This means five images misclassified by the Shallow network against only one image erroneously classified by the VGG16 network. To evaluate these results, it is important to remark that during the training process, 13.5 million parameters were adjusted in the VGG16 network, against only 1.5 million parameters in the Shallow network. Training the VGG16 network requires more time and has a higher computational cost, and definitely, we always have a trade-off between training time and accuracy of the model. The Shallow network proved to be effective, but in the industry, accuracy is very important, even more than the time required to develop an innovation. In addition, once the VGG16 network has been trained, there is not a significant difference in the time required to do a prediction between both networks. For this reason, the VGG16 network seems to be more appropriate in this case. FIGURE 3 Heat map activation from the three datasets TABLE 3 Comparison between Shallow and VGG16 networks Accuracy Number of images misclassified Number of parameters (x10 6 ) VGG16 98.8 1 13.5 Shallow 93.9 5 1.5 8of10 BORRAZ-MARTÍNEZ ET AL. 152 4|CONCLUSIONS In this study, computer vision and deep learning models have been applied for plant varietal discrimination. Three datasets (whole plant, leaf, and venation) have been compared, each of them containing images with a different scale from two varieties of P. dulcis,Soleta and Pentacebas, in nursery plant state. The best results were obtained for the leaf data set, with a classification accuracy of 98.8%, while whole plant and venation datasets obtained 97.6% of accuracy in the test. It was shown that the edge shapes of the leaves, and especially the venation, are the most important characteristic for the identification and discrimination of the classes. Although the venation features had great importance, the image acquisition method used in the study may have limited their potential. Finally, the performances of two CNNs were compared. The VGG16 network performed better than the Shallow network, indicating that the enormous difficulty of discriminating both varieties of P. dulcis requires a complex neural network architecture. These results show that computer vision together with deep learning is a promising technique for automatic control of varietal mixtures. Moreover, it will be interesting to develop a method that allows us to obtain good images of the venation of the leaves without having to take individual leaf samples. Finally, although these models were built using images of nursery almond trees, the idea is to extend the models to other plant species. FUNDING INFORMATION The authors thank the financial support of the Industrial Doctorates Plan of the Secretariat of Universities and Research of the Department of Economy and Knowledge of the Generalitat of Catalonia (project DI-COF 2017) and by the Spanish Ministry of Economy and Competitiveness (project AGL2015-70106-R, AEI/FEDER, UE). PEER REVIEW The peer review history for this article is available at https://publons.com/publon/10.1002/cem.3388. DATA AVAILABILITY STATEMENT Data available on request from the authors. ORCID Sergio Borraz-Martínez https://orcid.org/0000-0002-5607-9462 Joan Sim ohttps://orcid.org/0000-0002-2853-3381 Anna Gras https://orcid.org/0000-0003-0111-7246 Ricard Boqué https://orcid.org/0000-0001-7311-4824 Francesc Tarrés https://orcid.org/0000-0003-0920-4782 REFERENCES 1. Borraz-Martínez S, Boqué R, Sim o J, Mestre M, Gras A. Development of a methodology to analyze leaves from prunus dulcis varieties using near infrared spectroscopy. Talanta. 2019;204:320-328. doi:10.1016/j.talanta.2019.05.105 2. Borraz-Martínez S, Sim o J, Gras A, Mestre M, Boqué R. Multivariate classification of prunus dulcis varieties using leaves of nursery plants and near infrared spectroscopy. Sci Rep. 2019;9(1):1-9. doi:10.1038/s41598-019-56274-5 3. Lu Y. Industry 4.0: a survey on technologies, applications and open research issues. J Ind Inf Integr. 2017;6:1-10. doi:10.1016/j. jii.2017.04.005 4. Chollet F. Deep Learning With Python. Manning Publications; 2018. 5. Buduma N, Locascio N. Fundamentals of Deep Learning: Designing Next-Generation Machine Intelligence Algorithms. Vol. 29. O'Reilly Media, Inc; 2017. 6. Kamilaris A, Prenafeta-Boldú FX. Deep learning in agriculture: a survey. Comput Electron Agric. 2018;147(July 2017):70-90. doi: 10.1016/j.compag.2018.02.016 7. Kussul N, Lavreniuk M, Skakun S, Shelestov A. Deep learning classification of land cover and crop types using remote sensing data. IEEE Geosci Remote Sens Lett. 2017;14(5):778-782. doi:10.1109/LGRS.2017.2681128 8. Debats SR, Luo D, Estes LD, Fuchs TJ, Caylor KK. A generalized computer vision approach to mapping crop fields in heterogeneous agricultural landscapes. Remote Sens Environ. 2016;179:210-221. doi:10.1016/j.rse.2016.03.010 9. Wang Q, Nuske S, Bergerman M, Singh S. Automated Crop Yield Estimation for Apple Orchards. Springer, Heidelberg; 2013:745-758. doi: 10.1007/978-3-319-00065-7_50. 10. Dorj UO, Lee M, Yun S. An yield estimation in citrus orchards via fruit detection and counting using image processing. Comput Electron Agric. 2017;140:103-112. doi:10.1016/j.compag.2017.05.019 BORRAZ-MARTÍNEZ ET AL.9of10 153 11. Yalcin, H. Plant phenology recognition using deep learning: deep-pheno. In 2017 6th International Conference on Agro-Geoinformatics. IEEE; 2017:1-5. doi:10.1109/Agro-Geoinformatics.2017.8046996. 12. Mochida K, Koda S, Inoue K, et al. Computer vision-based phenotyping for improvement of plant productivity: a machine learning perspective. GigaScience. 2018;8(1):1-12. doi:10.1093/gigascience/giy153 13. Zhu X, Zhu M, Ren H. Method of plant leaf recognition based on improved deep convolutional neural network. Cogn Syst Res. 2018;52: 223-233. doi:10.1016/j.cogsys.2018.06.008 14. Barré P, Stöver BC, Müller KF, Steinhage V. LeafNet: a computer vision system for automatic plant species identification. Ecol Inform. 2017;40:50-56. doi:10.1016/j.ecoinf.2017.05.005 15. Dutta S. An overview on the evolution and adoption of deep learning applications used in the industry. Wiley Interdiscip Rev Data min Knowl Discov. 2018;8(4):1-12. doi:10.1002/widm.1257 16. Cheng Y-P, Li C-W, Chen Y-C. Apply computer vision in GUI automation for industrial applications. Math Biosci Eng. 2019:7526-7545. doi:10.3934/mbe.2019378 17. Borraz-Martínez S, Tarrés F, Boqué R, Mestre M, Sim o J, Gras A. Varietal quality control in the nursery plant industry using computer vision and deep learning techniques. J Chemometr. 2020:1-11. doi:10.1002/cem.3320 18. Mikołajczyk A, Grochowski M. Data augmentation for improving deep learning in image classification problem. In 2018 International Interdisciplinary PhD Workshop, IIPhDW 2018. Institute of Electrical and Electronics Engineers Inc.; 2018:117-122. doi: 10.1109/IIPHDW.2018.8388338. 19. Shorten C, Khoshgoftaar TM. A survey on image data augmentation for deep learning. J Big Data. 2019;6(1):1-48. doi:10.1186/s40537- 019-0197-0 20. Qin Z, Yu F, Liu C, Chen X. How convolutional neural networks see the world—a survey of convolutional neural network visualization methods. Math Found Comput. 2018;1(2):149-180. doi:10.3934/mfc.2018008 21. Simonyan K, Zisserman A. Very deep convolutional networks for large-scale image recognition. 3rd Int. Conf. Learn. Represent. ICLR 2015 - Conf. Track Proc. 2014. 22. Pan SJ, Yang Q. A survey on transfer learning. IEEE Trans Knowl. 2010;22(10):1345-1359. doi:10.1109/TKDE.2009.191 23. Mohanty SP, Hughes DP, Salathé M. Using deep learning for image-based plant disease detection. Front Plant Sci. 2016;7(September): 1-10. doi:10.3389/fpls.2016.01419 24. Mehdipour Ghazi M, Yanikoglu B, Aptoula E. Plant identification using deep neural networks via optimization of transfer learning parameters. Neurocomputing. 2017;235(January):228-235. doi:10.1016/j.neucom.2017.01.018 25. Lipton ZC. The mythos of model interpretability. Commun ACM. 2018;61(10):36-43. doi:10.1145/3233231 26. Selvaraju RR, Cogswell M, Das A, Vedantam R, Parikh D, Batra D. Grad-CAM: visual explanations from deep networks via gradientbased localization. Int J Comput vis. 2020;128(2):336-359. doi:10.1007/s11263-019-01228-7 27. Cope JS, Corney D, Clark JY, Remagnino P, Wilkin P. Plant species identification using digital morphometrics: a review. Expert Systems with Applications Pergamon. 2012;39(8):7562-7573. doi:10.1016/j.eswa.2012.01.073 28. Hearn DJ. Shape analysis for the automated identification of plants from images of leaves. Taxon. 2009;58(3):934-954. doi: 10.1002/tax.583021 29. Lee SH, Chan CS, Mayo SJ, Remagnino P. How deep learning extracts and learns leaf features for plant classification. Pattern Recognit. 2017;71:1-13. doi:10.1016/j.patcog.2017.05.015 How to cite this article: Borraz-Martínez S, Sim o J, Gras A, Mestre M, Boqué R, Tarrés F. Combining computer vision and deep learning to classify varieties of Prunus dulcis for the nursery plant industry. Journal of Chemometrics. 2022;e3388. doi:10.1002/cem.3388 10 of 10 BORRAZ-MARTÍNEZ ET AL. 154 Discusión