Frontiers in Computing and Intelligent Systems ISSN: 2832-6024 | Vol. 13, No. 2, 2025 98 Research on Non‐destructive Detection of Kiwi Fruit Internal Quality Based on Deep Learning Yanan Xue *, Zhipeng Li School of Electronic Information, Xijing University, Xi 'an, Shaanxi, China * Corresponding author: Yanan Xue Abstract: In recent years, as people's awareness of dietary health has continuously increased, the nutritional value and intrinsic quality of fruits have gradually become the focus of consumers' attention. However, in China, the classification of fresh fruits still relies on empirical methods such as manual observation, lacking unified and scientific standards, resulting in uneven fruit quality in the market. To improve the accuracy and efficiency of fruit quality classification, this paper takes kiwifruit as the research object and proposes a non-destructive detection technology that integrates near-infrared spectroscopy technology and deep learning models to achieve kiwifruit quality classification based on soluble solid content (SSC). This study first collected full-band spectral data of kiwifruit samples using a near-infrared spectrometer and combined the physicochemical values of SSC measured by a refractometer to establish a complete dataset containing spectral and quality labels. In the data preprocessing stage, three common algorithms, MSC, SG, and CT, were tried, and their effects in noise reduction and smoothing were compared. The experiment found that the SG preprocessing method could most effectively improve the overall performance of the model. Subsequently, this paper built a deep neural network model based on the LSTM model, combining BiLSTM (bidirectional long short-term memory network) and MHA (multi-head attention mechanism), to better capture the temporal features and key band information in the spectral sequence. The final results show that the combination of SNV + BiLSTM + MHA performs excellently in the classification detection of apple SSC content, with an accuracy rate of 0.9574, a precision rate of 0.9575, a recall rate of 0.9601, and an F1 score of 0.9586, fully verifying the effectiveness and application potential of this method in the non-destructive detection of kiwifruit quality. Keywords: Near-infrared Spectroscopy; Kiwifruit; Quality Grading; LSTM. 1. Introduction Kiwi fruit, as a nutritious and distinctive fruit, is highly favored by consumers. Its quality directly affects consumers' purchasing intention and market value. Traditional methods for quality inspection of kiwi fruit mainly rely on manual sensory evaluation and physicochemical index analysis, which have problems such as strong subjectivity, low efficiency, and sample damage, and thus are unable to meet the requirements of modern fruit industry for rapid, non- destructive, and online detection. Near-infrared spectroscopy (NIR) technology, as a rapid, efficient, and environmentally friendly non-destructive detection method, has shown great application potential in the field of fruit quality inspection in recent years. This technology utilizes the multiphase and harmonics absorption characteristics of hydrogen-containing groups such as C-H, O-H, and N-H in organic substances in the near-infrared [4] region to quickly obtain information about the composition and structure of samples, enabling non-destructive detection of the internal quality of fruits. In recent years, scholars at home and abroad have applied NIR technology to the detection of quality indicators such as soluble solids content (SSC), hardness, and dry matter content, and have achieved certain research results. Zhang Fu et al. [1] used visible/near-infrared technology to conduct non- destructive detection of soluble solids content (SSC) in tomatoes and improved the BP neural network model to provide an effective solution for the rapid assessment of the internal quality of tomatoes. Zhou Danrong et al. [2] used visible/near-infrared technology to conduct a study on the nutritional quality during the ripening period of hibiscus fruit, screened out four core indicators such as fructose, glucose, and two anthocyanin glycosides, and constructed an appearance prediction model based on color value. The results showed that this model had high prediction accuracy and reliability for quality indicators, providing a convenient method for the comprehensive quality evaluation of hibiscus fruit. Bi Shuhui et al. [3] used genetic algorithms to extract characteristic wavelengths and improved the evaluation performance of apple classification. Foreign scholars Mahayothee et al. [4] used a new frame camera combined with hyperspectral imaging technology (450-998 nm) to conduct non-destructive detection of mango hardness, total soluble solids (TSS), and titratable acidity (TA), and established a prediction model through partial least squares regression (PLS). After optimization through multiple linear regression (MLR), it was found that the high-spectrum data could help consumers buy more favorable and delicious fruits, further improving domestic fruit trade. This study takes kiwi fruit as an example, based on near- infrared spectroscopy, using excellent algorithm models from machine learning and deep learning to achieve non- destructive detection and variety classification of kiwi fruit quality. By exploring the application of NIR technology in the internal quality detection of kiwi fruit, a classification model for the internal soluble solids content of kiwi fruit was established. 99 2. Experimental Section 2.1. Materials and Equipment The experimental samples for this study were "Cuixiang" kiwifruit, which were collected from the Biyue Kiwifruit Orchard in Xi'an City, Shaanxi Province. The collection date was October 2, 2024. The samples were collected following the principle of random sampling, and were selected evenly from the fruits of different trees in the orchard. After preliminary screening, the fruits with damaged skins, pests, diseases, or abnormal shapes were excluded, and only the high-quality samples with consistent softness were retained. To maintain the freshness of the samples, all kiwifruits were immediately transferred to a 3-6℃ constant-temperature cold storage for storage. 24 hours before the experiment, the samples were removed from the refrigeration environment and placed in a (22±2) ℃ constant-temperature room for temperature balance treatment. Regarding the potential interference of the fine hairs on the kiwifruit's surface on the spectral signals, before the experiment, the samples were gently wiped with a fine cloth to ensure the test area was smooth and free of obstructions. After cleaning, each of the 234 valid samples was numbered and marked one by one. The spectral collection was carried out using the Pynet NIR-R210 reflective spectrometer. This instrument is equipped with a handheld near-infrared module and an internal light source, covering a wavelength range of 900- 1700 nm. It can accurately obtain the sample's diffuse reflection spectral data, providing a basis for subsequent chemometric modeling. At the same time, the Atago PAL- BX/ACID8 handheld sugar content meter was used to measure the soluble solid content (SSC). This device has a built-in compensation curve correction function, which can effectively reduce environmental errors and ensure the repeatability and accuracy of the sugar content measurement results. The collaborative application of the two instruments forms a complete data collection system, providing technical support for the research on non-destructive detection of kiwifruit quality. 2.2. Data Acquisition This study used the Pynet NIR-R210 reflective spectrometer (Figure 1) to collect the spectral data of kiwifruit, and the standard white board of the same brand, STD-DR100 (spectral range: 200 - 2500 nm, full spectral band reflectance ≥ 98%), was used as a companion. The specific experimental process is as follows: 1) Sample pre-treatment and positioning Mark the kiwifruit samples at multiple angles: set a measurement point every 90° along the equatorial plane of the fruit (a total of 4 points), and attach a digital identification label at each point to ensure precise positioning. 2) Instrument system initialization After turning on the built-in light source of the spectrometer, perform 10-minute preheating treatment to ensure the stability of the light source output and eliminate the influence of environmental temperature fluctuations on the optical system. 3) Standardization calibration Before sample detection, collect the reference spectrum through the STD-DR100 standard white board to establish the baseline reflectance calibration value, in order to eliminate instrument drift and environmental stray light interference. 4) Spectral collection: Carefully adjust the kiwifruit sample to ensure that its surface is 90° perpendicular to the collection surface of the spectrometer, and strictly control the distance between this area and the fruit surface to effectively reduce the interference of other light on the experimental results. 5) Soluble solids content (SSC) data collection: First, remove the skin of the kiwifruit sample, precisely cut uniform tissue blocks at each measurement point, and obtain the sample juice after thorough crushing by a juicer. Use high- density non-woven fabric for double filtration to completely remove suspended impurities. Take the clarified juice and conduct sugar content detection using the PAL-BX/ACID8 handheld refractometer, implement three independent repeated measurements, and calculate the arithmetic mean as the final determination result. Based on the Chinese national industry standard NY/T 2002-2011 "Determination of Soluble Solid Content in Fruits and Products - Refractometer Method", a grading system was established: when SSC ≥ 14%, it is determined as Class I high-quality fruit; those with SSC in the range of 10% - 14% (including the lower limit but excluding the upper limit) are classified as Class II standard fruit; and those with SSC < 10% are classified as Class III fruit to be improved. This classification standard is precisely quantified and determined by the handheld refractometer to ensure the scientificity and operability of the grading system. 2.3. Multi-class Evaluation Metrics This study has constructed a three-dimensional quantitative assessment framework, systematically quantifying the predictive efficacy of the model through three-dimensional indicators of accuracy (Accuracy), precision (Precision), and recall (Recall). Among them: Accuracy, as a global evaluation parameter, comprehensively reflects the overall discrimination ability of the model for positive and negative samples. Its mathematical expression is: Accuracy TP TN TP FP FNTP TN 1 In the formula, TP (True Positive) represents the number of true positive samples, TN (True Negative) represents the number of true negative samples, FP (False Positive) represents the number of false positive samples, and FN (False Negative) represents the number of false negative samples. Precision, as a reliability indicator for positive predictions, precisely measures the proportion of actual true positives among the predicted positive samples. The calculation formula is: Precision TP TP FP 2 This indicator mainly assesses the confidence level of the prediction results; The recall rate serves as the target capture sensitivity indicator, effectively quantifying the coverage of the correct identification of the true positive samples. Its definition is: Recall TP TP FN 3 This indicator mainly reflects the model's ability to capture key targets. All three indicators are measured within the standardized 100 range of [0, 1]. The closer the value is to 1, the more the model's performance in this evaluation dimension approaches the theoretical optimal value. When the three-dimensional indicators achieve a high-level coordinated balance, the model will simultaneously exhibit global prediction stability, precise identification ability of key targets, and strong capture efficiency of potential positive examples, forming the optimal solution space for the prediction effect. If any of the dimension indicators deviate significantly, it indicates that the model has a systematic bias in this evaluation dimension, and it is necessary to optimize the algorithm architecture or adjust the parameter configuration to improve the overall prediction efficiency. 2.4. Near-Infrared Spectroscopy Preprocessing Method When establishing a model using the original spectra and the soluble solid content (SSC) values, due to the complexity of the spectral data and the interference of noise, the prediction accuracy of the model is relatively low. To improve the model performance, the near-infrared spectral data of kiwifruit is first preprocessed to remove noise, correct baseline drift, and enhance spectral features. The preprocessed data is then divided into a training set and a prediction set to ensure that the two sets have consistent representativeness in the feature space. Finally, feature wavelengths are extracted to select the most contributing wavelengths for SSC prediction, thereby improving the prediction accuracy and generalization ability of the model. 2.4.1. Dataset Division In order to effectively evaluate the generalization performance of the model, this study employed the SPXY algorithm to divide the dataset. This algorithm takes into account the distance between spectral and physicochemical values, ensuring the consistency of the distribution of the training set and the test set. The dataset contains 234 samples, which are divided into a training set and a test set in a ratio of 60% to 40%. Finally, 140 training samples and 94 test samples were obtained. Table1 shows the number of samples of the three categories in the test set. Table 1. Classification situation of the test set after division. Sample category Type I fruit Type II fruit Type III fruit SPXY 32 35 27 2.4.2. Extraction of Characteristic Wavelengths When using the CARS algorithm for feature wavelength extraction, the optimal feature wavelength combination was selected based on minimizing the cross-validation root mean square error (RMSECV). The variation patterns of the number of sampled variables and the number of samplings are shown in Figure 1, the root mean square error values are shown in Figure 2, and the variation pattern of the number of samplings is shown in Figure 4. By comprehensively analyzing Figures 1 and 2, it can be found that the RMSECV of SSC reaches the lowest value at the 58th sampling, and the optimal variable set consists of 15 feature variables. The feature wavelengths extracted by CARS are shown in Table 2. Figure 1. Changes in the Number of Feature Variables Figure 2. RMSE Changes Figure 3. Regression Coefficients Figure 4. Distribution of feature wavelengths extracted by CARS. 101 Table 2. Selection of Characteristic Variables. Algorithm type Number Characteristic wavelength point (nm) CARS 15 900,924.67,1114.98,1118.50,1213.66,1231.28, 1326.43,1340.53,1347.58,1414.53, 1495.591516.74,1520.26,1654.18,1678.85 To improve the accuracy of the model, in response to the differences and noise issues of spectral data, this study employed the chemical metrology method to select appropriate feature wavelength extraction methods and data preprocessing algorithms. By constructing the PLS-DA model, the accuracy rates of each data preprocessing algorithm on the test set were compared, thereby determining the best feature wavelength selection method and preprocessing algorithm combination. The accuracy rates of the PLS-DA models processed by each algorithm are detailed in Table 3. Table 3. The Impact of Different Data Preprocessing Methods on Model Performance. Data preprocessing Data set division Model selection Accuracy rate Original spectrum SPXY PLS_DA 0.8036 SG SPXY PLS_DA 0.8519 SG+CARS SPXY PLS_DA 0.8704 MSC SPXY PLS_DA 0.7407 MSC+CARS SPXY PLS_DA 0.7962 CT SPXY PLS_DA 0.8148 CT+CARS SPXY PLS_DA 0.8333 After comparison, among the three preprocessing algorithms and the two feature wavelength selection algorithms, the PLS-DA model established by the algorithm combination of SG+CARS has the highest classification accuracy and the best effect, reaching 0.8704, which is superior to other preprocessing methods. Therefore, the SG+CARS preprocessing combination was ultimately selected. 3. Construction of the Prediction Model 3.1. LSTM This study constructed an LSTM three-classification model for spectral data analysis of kiwifruit. The model structure consists of an input layer, an LSTM layer (with 64 hidden units and ReLU activation function), a Dropout layer with a dropout rate of 0.25, a fully connected layer with an output dimension of 3, and an output layer. The model uses the cross- entropy loss function in PyTorch to achieve multi- classification. During training, the batch size is 32, the number of iterations is 500, the initial learning rate is 0.001, the learning rate decay factor is 0.0005, and the minimum learning rate is set to 1e-6. If the model's performance does not improve for 20 consecutive iterations, the learning rate will be decayed. The model structure is shown in Figure 5. Figure 5. Structure Diagram of LSTM Model After the SG+CARS preprocessing, the performance indicators of the LSTM model have significantly improved. All evaluation indicators show that the LSTM model has achieved a relatively ideal classification effect in the kiwi fruit spectral classification task. The accuracy rate is 0.9149, the precision rate is 0.9130, the recall rate is 0.9146, and the F1 value is 0.9144. During the model training process, an early stopping strategy was introduced. When the performance on the training set reached the preset threshold, the training was automatically stopped, effectively avoiding the problems of overfitting or underfitting of the model. The specific model parameters and performance results are shown in Table 4. Table 4. LSTM Model Parameters and Performance. Model Name Batch size Number of iterations Optimizer Dropout Accuracy rate Precision Recall rate F1 score LSTM 32 500 ReLU 0.25 0.9149 0.9139 0.9161 0.9144 The scatter plot showing the classification of apple spectral data by the LSTM classification model based on SSC content is shown in Figure 6, The confusion matrix is presented in the Table 5. 3.2. BiLSTM This study further incorporates Bidirectional Long Short- Term Memory (BiLSTM) on the basis of the LSTM model. BiLSTM is a special type of recurrent neural network (RNN) that can simultaneously capture the context information both before and after the sequence data[5]. Unlike the traditional unidirectional LSTM, BiLSTM consists of two opposite- directional LSTM layers. One processes information from the starting position to the end point in a forward manner, while the other processes information from the end point to the starting position in a backward manner. These two directions' LSTM layers independently extract features and then fuse 102 them through concatenation or summation at each time step to better utilize the context relationships in the sequence[6]. Figure 6. Scatter plot of LSTM classification results Table 5. Confusion Matrix of LSTM Classification Results. Real Label Classfication results of LSTM Type I fruit Type II fruit Type III fruit In total Type I fruit 27 1 4 32 Type II fruit 2 33 0 35 Type III fruit 1 0 26 27 In total 31 35 28 94 The advantage of the LSTM network lies in its unique gating structure, including the forget gate, input gate, and output gate. These gating units can effectively regulate the inflow and outflow of information, thereby effectively alleviating the common problems of gradient disappearance or explosion in traditional RNNs, enabling the model to stably learn long-distance dependencies. BiLSTM further enhances this advantage by introducing a bidirectional information transmission mechanism, demonstrating superior modeling capabilities in handling complex context-dependent data tasks. The specific structure of the BiLSTM network is shown in Figure 7. The figure clearly presents the input layer, forward LSTM layer, backward LSTM layer, and the output layer that integrates the bidirectional information. Figure 7. Structure Diagram of BiLSTM Network The BiLSTM model demonstrates excellent performance advantages in the classification task of near-infrared spectroscopy data. As shown in Table 6, the accuracy rate of the BiLSTM model for spectral data classification reaches 0.9255, the precision rate is 0.9235, the recall rate is 0.9269, and the F1 score is 0.9247. These indicators indicate that the BiLSTM model can effectively capture the feature information in near-infrared spectroscopy data, thereby improving the overall effect of the classification task. The scatter plot showing the classification of apple spectral data based on the SSC content by the BiLSTM classification model is shown in Figure 8. The confusion matrix is presented in Table 7. 3.3. BiLSTM+MHA The key idea of the Multi-Head Attention (MHA) mechanism lies in computing the attention weights in parallel through multiple attention heads, in order to capture richer 103 correlation information between different positions in the input sequence. This structure enables the model to simultaneously focus on multiple aspects of the sequence data, thereby enhancing the ability to extract and represent data features[7]. Table 6. Performance of BiLSTM Model. Model Name Training batch Number of iterations Optimizer Dropout Accuracy rate Precision Recall rate F1 score BiLSTM 32 500 ReLU 0.25 0.9255 0.9235 0.9269 0.9247 Figure 8. Scatter plot of BiLSTM classification results Table 7. Confusion Matrix of BiLSTM Classification Results. Real Label Classfication results of BiLSTM Type I fruit Type II fruit Type III fruit In total Type I fruit 28 1 3 32 Type II fruit 2 33 0 35 Type III fruit 1 0 26 27 In total 31 34 29 94 The specific implementation steps of the multi-head attention mechanism adopted in this study are as follows: Step 1 (Linear Mapping): Firstly, the input sequence X is transformed into a series of query (Q), key (K), and value (V) vectors through multiple independent linear mappings, where each attention head has its own independent mapping parameters. Step 2 (Attention Score Calculation): For each attention head, the corresponding attention score is calculated using the Q, K, and V vectors obtained from the respective mappings. The calculation formula is: Attebtion Q, K, V softmax QK d V 4 In the formula, dk represents the dimension of the key vector (K). The introduced factor is to prevent the inner product from being too large, thereby alleviating the possible problem of gradient disappearance. Step 3 (Headline Integration): The attention outputs obtained from independently calculating multiple heads are concatenated into a single feature representation, and then integrated through a linear mapping to obtain the final multi-head attention output. Step 4 (Subsequent Processing): The integrated multi-head attention output can be used for further feature processing and prediction in the subsequent network layers. This study further combines the multi-head attention mechanism with the BiLSTM model, and its overall structure is shown in Figure 9. The model consists of 1 input layer, 1 BiLSTM layer, 1 multi-head attention layer, 1 Dropout layer, and 1 fully connected layer. The output dimension of the fully connected layer is set to 3. The specific parameter settings are as follows: the number of attention heads is 4, the multi-head attention layer is located between the BiLSTM layer and the Dropout layer to help the BiLSTM capture features more effectively; the dropout rate of the Dropout layer is 0.25; the initial learning rate is 0.001, the learning rate decay factor is 0.0005, and the minimum learning rate is limited to 1×10-6. When the model performance does not improve for 20 consecutive iterations, the learning rate decay strategy will be automatically triggered. After introducing the multi-head attention mechanism (MHA) into the BiLSTM model, the performance of the model has been significantly improved. According to the data in Table 8, the accuracy of the BiLSTM + MHA model is 0.9574, the precision is 0.9575, the recall rate is 0.9601, and the F1 score is 0.9586. Figure 10 shows the prediction classification results of the BiLSTM + MHA model, and Table 9 presents the confusion matrix of the F classification results of the BiLSTM + MHA model. 104 Figure 9. Structure of the BiLSTM + MHA model Table 8. Model Performance. Model Name Training batch Number of iterations Optimizer Dropout Accuracy rate Precision Recall rate F1 score BiLSTM+MHA 32 500 ReLU 0.25 0.9574 0.9575 0.9601 0.9586 Figure 10. Scatter plot of classification results of BiLSTM + MHA. Table 9. Confusion Matrix of BiLSTM+MHA Classification Results. Real Label Classfication results of BiLSTM+MHA Type I fruit Type II fruit Type III fruit In total Type I fruit 30 1 1 32 Type II fruit 2 33 0 35 Type III fruit 0 0 27 27 In total 32 34 28 94 Based on the model performance comparison table analysis, the accuracy rate, precision rate, recall rate, and F1 score of the BiLSTM + MHA model is all superior to those of the other two models. This result indicates that the improvement made to the LSTM model in this paper is more suitable for solving the classification problem of kiwi fruit SSC content in this research. The confusion matrices of the three models in Tables 5, 7, and 9 show their performance on different classifications. Table 5 is the confusion matrix of the LSTM network. In each category, there will be classification errors. Table 7 is the BiLSTM model, which has improved relatively compared to the LSTM model. Table 9, after adding the multi-head attention mechanism, the model has better improved the accuracy rate of category I fruits and completely corrected the misclassification of the three categories of fruits. This indicates that the model can more accurately capture features when processing data, thereby improving the overall classification accuracy. 4. Conclusion This study successfully achieved non-destructive detection and classification of kiwi fruit quality by integrating near- infrared spectroscopy technology with machine learning and deep learning models. In the data preprocessing stage, considering the noise and complexity of the kiwi fruit spectral data, the SG smoothing and CARS feature extraction methods were adopted, significantly improving the data quality and model prediction ability. Among them, the SG+CARS combination scheme achieved the best results, with an accuracy rate of 0.8704. In terms of the classification model, three models, LSTM, BiLSTM, and BiLSTM + MHA, were constructed and compared. The results showed that the BiLSTM + MHA model performed optimally in terms of accuracy, precision, recall rate, and F1 value, being 0.9574, 0.9575, 0.9601, and 0.9586 respectively. This demonstrates its strong generalization ability in the kiwi fruit classification task, providing an effective technical path for fruit quality 105 evaluation based on near-infrared spectroscopy. This study indicates that the combination of near-infrared spectroscopy data with deep learning algorithms, especially BiLSTM and multi-head attention mechanism, can effectively improve the performance of kiwi fruit quality classification, bringing new ideas and methods to the field of fruit quality detection, and meeting the requirements of modern fruit industry for rapid and non-destructive detection. References [1] Zhang Fu, Cao Weihua, Cui Xiahua, et al. Non-destructive testing of soluble solids in cherry Tomatoes by Visible/near- infrared Spectroscopy Based on SG-CARS-IBP [J] Spectroscopy and Spectral Analysis, 2023, 43 (03): 737-743. (in Chinese) [2] Zhou Danrong, Lin Yanjuan, Fang Zhizhen, et al. Screening of Comprehensive Quality Evaluation Indicators and Construction of Appearance Prediction Model during Fruit Maturity of Furong Plum [J] Journal of food safety and quality testing, 2024, 15 (12) : 210-219. The DOI: 10.19812 / j.carol carroll nki/ts jfsq11-5956. 20240311002. (in Chinese) [3] Bi Shuhui, Li Xue, Shen Tao, et al. Apple classification method Based on Multi-model Evidence Fusion [J]. Transactions of the Chinese Society of Agricultural Engineering, 2022, 38 (13): 141-149. (in Chinese) [4] Mahayothee B, Rungpichayapichet P, Yuwanbun P, et al. Temporal changes in the spatial distribution of physicochemical properties during postharvest ripening of mango fruit[J]. Journal of Food Measurement and Characterization, 2020, 14: 992-1001. [5] Graves A, Schmidhuber J. Framewise phoneme classification with bidirectional LSTM and other neural network architectures[J]. Neural networks, 2005, 18(5-6): 602-610. [6] Gullifa G, Barone L, Papa E, et al. Portable NIR spectroscopy: The route to green analytical chemistry[J]. Frontiers in Chemistry, 2023, 11: 1214825. [7] Vaswani A. Attention is all you need[J]. Advances in Neural Information Processing Systems, 2017.