Distributed recommendation method based on Spark platform

By combining factor decomposition machine and stochastic gradient descent on the Spark platform, parallel computing and data processing are achieved, and the computational complexity problem of FM algorithm under large data sets is solved, processing speed and flexibility are improved, and suitable for large-scale data analysis and machine learning tasks.

CN119004401AInactive Publication Date: 2024-11-22HUAQIAO UNIVERSITY

Patent Information

Application Number
CN202411481662.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-10-23
Publication Date
2024-11-22
Estimated Expiration
Not applicable · inactive patent

AI Technical Summary

Technical Problem

The current technology has high computational complexity when facing large data sets, which leads to the increase in computational complexity of FM algorithms when there are many features, slow training speed, and model parameters occupy a large amount of memory resources, which is especially a challenge for finite memory systems. .

Method used

The distributed recommendation method based on the Spark platform is adopted, and the FM prediction model is constructed in combination with factor decomposition machine and stochastic gradient descent. Parallel gradient calculation and aggregation gradient update parameters are used, and Spark's distributed architecture and fault tolerance mechanism are used to realize parallel computing and data processing. Simplify feature interactive computing and reduce computing complexity and memory usage.

Benefits of technology

It significantly improves processing speed and data processing capabilities, reduces computing complexity, improves model training speed, ensures the reliability and flexibility of tasks, and is suitable for various machine learning tasks, especially in large-scale data scenarios.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119004401A_ABST
    Figure CN119004401A_ABST
Patent Text Reader

Abstract

The invention belongs to the field of recommendation systems, and discloses a distributed recommendation method based on a Spark platform, and the method comprises the steps: combining a factorization machine and stochastic gradient descent to construct an FM prediction model, and the FM prediction model uses a feature matrix including a user, an article and context information as input and output to predict user behaviors; configuring a Spark platform environment, loading original data, and preprocessing the original data to obtain a data set; the Spark platform initializes an FM prediction model and carries out training according to task types, and in the training process, the Spark platform carries out parallel gradient calculation and aggregates gradients to update parameters; and deploying the trained FM prediction model in an actual production environment, and carrying out real-time prediction on different task types to realize recommendation. According to the method, the characteristics of distributed computing power, memory computing, elastic fault tolerance, data locality and the like of the Spark are combined, and the advantages of high computing efficiency, low memory occupation and high convergence speed of the SGD are also combined, so that a large-scale and high-dimension sparse data set can be efficiently processed.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of recommendation systems, and in particular to a distributed recommendation method based on a Spark platform. Background Art

[0002] The Factorization Machines (FM) algorithm was proposed to overcome the limitations of traditional machine learning models in processing high-dimensional sparse data, especially in capturing the interaction between features. The FM algorithm combines the advantages of matrix decomposition and linear models, and introduces latent vectors to model the second-order interactions between features. In many practical applications (such as recommendation systems, advertising click-through rate prediction, etc.), traditional linear models can only capture linear relationships with obvious features, but cannot effectively build interactions between model features; at the same time, the idea of ​​Matrix Factorization (MF) has been successful in recommendation systems. By mapping the feature vectors of users and items into the same latent space, it can capture the interaction between users and items. However, matrix decomposition is mainly applicable to specific structured data (i.e., user-item rating matrix), but not to general high-dimensional sparse data containing multiple features.

[0003] Therefore, Steffen Rendle proposed in 2010 that the idea of ​​matrix decomposition can be extended to general feature interaction modeling. FM introduces a latent vector to represent each feature, so that the interaction between features can be represented by the inner product of these latent vectors. This method not only retains the advantages of matrix decomposition, but also can handle arbitrary feature combinations.

[0004] The factorization machine models the interaction between features by introducing latent factors. Its basic model formula is as follows:

[0005] ;

[0006] in, It is a sample The predicted value of is the global bias term, which represents the overall reference value. It is a feature The direct impact on the predicted value is and It is a feature and The hidden vectors (latent factors) of , each of which has a dimension of k, Representation characteristics and The inner product of the interaction between is calculated as:

[0007] = ;

[0008] Global bias term Represents the overall benchmark prediction value, which is used to capture the average effect of the entire data set and does not depend on any features; linear weight Corresponding to feature i, each feature contributes independently to the prediction result; the latent vector is used to represent the potential characteristics of the feature, and these latent factors capture the interaction between them through the inner product of the feature vector.

[0009] The FM algorithm is a very effective feature learning algorithm in machine learning. It can be used to predict real-valued outputs, such as binary classification or regression tasks. By efficiently simulating and accurately capturing the interaction effects between different features in the data, it performs well in recommendation systems, click-through rate prediction, and ranking problems. In the field of recommendation systems, FM can alleviate the sparsity problem by considering additional features and provide users with more accurate recommendations; in the field of click-through rate prediction, the FM algorithm can use the feature interaction information between users and ads to help users estimate the probability of clicking on a certain content, thereby better predicting CTR; in problems such as movie rating prediction, the FM algorithm can more accurately process different types of features and complex interaction patterns to analyze the interaction between users and movies for rating prediction; in text classification and natural language processing, data sets usually have ultra-high-dimensional features, and the FM algorithm can help reduce computational complexity while maintaining a high accuracy rate; in social network analysis, FM can simulate complex relationships between users and can be used to predict user behavior, such as product preferences, community affiliation, etc.

[0010] FM and its improved algorithms have excellent performance in many tasks, but with the increase of model complexity, data sparsity and computational efficiency have become key points that cannot be ignored. Although many scholars in the industry have tried to improve the FM algorithm, these improvements have improved the performance of the FM algorithm to a certain extent and have achieved good results in engineering practice, but these models all have some problems and challenges to a greater or lesser extent. FFM is a variant of FM, which further allows each feature to have a different vector representation when interacting with different domains, so that the interaction between features can be captured more carefully. However, its parameter count grows exponentially with the number of domains, causing the model to become too large, increasing the complexity of training and the risk of overfitting. DeepFM aims to extract deeper feature interaction information by combining deep neural network DNN and FM to obtain better prediction performance. DeepFM does not require predefined interactions between features and can automatically learn high-order feature interactions. However, high-order feature interactions are very demanding on computers and are very time-consuming, especially on large-scale data sets, where computational efficiency becomes a problem. Some studies have attempted to introduce attention mechanisms into FM models so that the model can automatically identify the importance differences between different feature interactions. This can enhance the model's ability to capture important information and further improve the model's accuracy and generalization capabilities. However, when faced with severe sparsity, the model may find it difficult to learn effective feature representations. Although the FM algorithm has advantages in processing interactions between features and sparse data, it still needs to traverse all feature pairs when facing large data sets, which leads to increased computational complexity and heavier computational burden when the number of features is very large, and slow training speed. At the same time, intermediate calculation results and massive model parameters will also take up a lot of memory resources, which is also a challenge for systems with limited memory, so more exploration is needed. Summary of the invention

[0011] The purpose of the present invention is to solve the problem of high computational complexity in the prior art when facing large data sets.

[0012] The technical solution adopted by the present invention to solve the technical problem is: to provide a distributed recommendation method based on the Spark platform, comprising the following steps:

[0013] A FM prediction model is constructed by combining factorization machine and stochastic gradient descent. The FM prediction model takes a feature matrix including user, item and context information as input and outputs predicted user behavior;

[0014] Configure the Spark platform environment and load the original data, and preprocess the original data to obtain the data set;

[0015] The Spark platform initializes the FM prediction model and trains it according to the task type. During the training process, the Spark platform performs parallel gradient calculations and aggregates gradients to update parameters.

[0016] Deploy the trained FM prediction model to the actual production environment to perform real-time predictions for different task types and implement recommendations.

[0017] Preferably, configuring the Spark platform environment and loading the original data specifically includes:

[0018] Install and configure the Spark on YARN cluster;

[0019] Load raw data including user, item, and context information from HDFS or local file system.

[0020] Preferably, the preprocessing of the original data to obtain the data set includes:

[0021] Data cleaning, including deleting missing value records and filling missing values ​​with the mean value, and replacing outliers with the mean median;

[0022] Feature engineering, including one-hot encoding of categorical variables and standardization of numerical variables;

[0023] Feature vectorization, using Spark's VectorAssembler to combine all feature columns into a vector column and convert it into a feature vector.

[0024] Preferably, the process of initializing the FM prediction model includes:

[0025] Initialize the factor matrix to represent implicit interactions between features;

[0026] Initialize the weights and biases for each feature.

[0027] Preferably, the training according to the task type comprises the following steps:

[0028] In the data partitioning step, Spark divides the data set into multiple partitions and distributes them to different nodes;

[0029] Convergence judgment step: judge whether the current model training reaches the convergence standard. If yes, save the model and end the training; otherwise, perform local training on the model on each node according to the data assigned to the node until the local training reaches the communication granularity threshold, and then enter the update step;

[0030] In the update step, the local training data is summarized to update the model parameters and return to the convergence judgment step.

[0031] Preferably, the model is locally trained on each node according to the data assigned to the node, and the process of local training on each node includes the following steps:

[0032] The predicted value is obtained by the inner product of the feature vector and the model parameter, and the error between the predicted value and the actual value is calculated;

[0033] The gradient derivative of the loss function with respect to the model parameters is calculated based on the error between the predicted value and the actual value, and the gradient and loss of the partition are obtained by accumulating the data in each node.

[0034] Preferably, the updating step is specifically as follows: globally accumulating the gradients and losses of all nodes; and updating the model parameters based on the gradients and losses obtained by the global accumulation.

[0035] Preferably, the task types include:

[0036] For regression tasks, the FM prediction model predicts the user's rating of the item based on the input feature matrix; for regression tasks, the loss function uses the mean square error function;

[0037] For classification tasks, the FM prediction model predicts whether the user clicks on the item based on the input feature matrix; for classification tasks, the loss function uses a logarithmic function or a cross entropy loss function.

[0038] Preferably, the Spark platform performs parallel gradient calculation and gradient aggregation in a mini-batch manner, specifically:

[0039] The sample function is used to sample the data in the dataset and select a small part of the data to calculate the gradient of each iteration. Only a part of the data is used to calculate the gradient in each iteration, thus realizing the distributed SGD in mini-batch mode.

[0040] Preferably, deploying the trained FM prediction model to an actual production environment comprises the following steps:

[0041] Save the trained model to HDFS and local file system;

[0042] The trained model can be loaded according to the task type, and the model can be used for real-time prediction in the actual production environment. The present invention has the following beneficial effects:

[0043] (1) Traditional FM algorithms face limitations in memory and computing resources when faced with increasingly large data. Spark's distributed architecture distributes data and computing tasks to multiple nodes, and can use multiple nodes in the cluster for parallel computing, greatly improving processing speed and data processing capabilities. At the same time, Spark has a fault-tolerant mechanism that traditional FM algorithms do not have. When a node fails, the computing task can be re-executed on other nodes to ensure the reliability and continuity of the task.

[0044] (2) Although FM is mainly used for recommendation system tasks such as CTR prediction, through the Spark platform, the FM algorithm can be extended to various machine learning tasks, such as classification and regression, and has a wider applicability. The Spark platform provides a wealth of tools and APIs that can easily integrate multiple data sources and data processing pipelines. The FMwithSGD algorithm based on Spark can be seamlessly integrated into the existing big data processing process, improving the flexibility of the application.

[0045] (3) Although Spark can efficiently utilize cluster resources through memory management and task scheduling, it cannot solve the huge computational overhead of the traditional FM algorithm when calculating closed-form solutions in the face of large-scale data. By parallelizing SGD optimization, it is possible to better utilize computing resources, reduce computing bottlenecks, and improve the overall efficiency of the algorithm. At the same time, the FMwithSGD algorithm based on Spark can significantly speed up the training of the model in large-scale data scenarios and obtain convergence results in a short time.

[0046] The present invention is further described in detail below in conjunction with the accompanying drawings and embodiments, but the present invention is not limited to the embodiments. BRIEF DESCRIPTION OF THE DRAWINGS

[0047] Figure 1 A method step diagram of an embodiment of the present invention;

[0048] Figure 2 It is a schematic diagram of a flow chart of an embodiment of the present invention;

[0049] Figure 3 This is a flow chart of distributed execution of data in Spark according to an embodiment of the present invention;

[0050] Figure 4 This is a parallel partition iterative calculation flow chart of an embodiment of the present invention; DETAILED DESCRIPTION

[0051] See also Figure 1 and Figure 2 The method step diagram and flow chart of an embodiment of the present invention are shown, which include the following steps:

[0052] S101, combining factorization machine and stochastic gradient descent to build a FM prediction model, wherein the FM prediction model takes a feature matrix including user, item and context information as input and outputs predicted user behavior;

[0053] S103, configuring the Spark platform environment and loading the original data, and preprocessing the original data to obtain a data set;

[0054] S104, the Spark platform initializes the FM prediction model and performs training according to the task type. During the training process, the Spark platform performs parallel gradient calculations and aggregates gradients to update parameters;

[0055] S104, deploy the trained FM prediction model to the actual production environment, perform real-time prediction of different task types, and implement recommendations.

[0056] Specifically, the context information refers to external or environmental factors that may affect the user-item interaction. For example, when buying a computer, the context information includes the time of purchase, the location, the browsing history before purchase, social information, and whether the product is discounted.

[0057] Specifically, S102 uses Spark's DataFrame or RDD to load and preprocess data, ensuring that the data format is correct and that the features have been properly encoded and standardized.

[0058] Specifically, in S103, the global bias term , feature weight and the feature latent vector These parameters can be initialized randomly or with prior knowledge. For each iteration, the model parameters are updated using gradient descent or other optimization algorithms. In Spark implementation, the gradient of each data point can be calculated in parallel through map-reduce operations, and then the gradients are accumulated and the model parameters are updated. Part of the calculation, simplify the interaction terms, and optimize the computing and storage efficiency in a distributed environment. Spark provides an advanced feature called accumulators to aggregate information across task boundaries. During the parameter update process of the FM model, accumulators can be used to collect the gradients of different partitions. Use Spark clusters for parallel computing. Distribute data on multiple nodes, each node calculates the gradient of a part of the data, and then aggregates these gradients to update the model parameters.

[0059] Specifically, Spark's distributed computing capabilities are used to perform model evaluation and hyperparameter tuning, such as selecting the optimal model configuration through cross-validation. The model formula is expressed as:

[0060] ;

[0061] The calculation of interaction terms is the core of the FM model and is in the following form:

[0062] ;

[0063] in, and are the latent vectors of the i-th and j-th eigenvectors, and are their corresponding eigenvalues.

[0064] In the original quadratic term calculation, it is necessary to traverse all the eigenvalues and To calculate their interaction effect, the computational complexity is ,in is the number of features, is the dimension of the latent vector. By calculating the sum of the dot products of the latent vectors and the eigenvalues ​​of all features, then calculating the square of this sum, and finally subtracting the sum of the products of the squares of each latent vector and the square of the eigenvalue, the computational complexity is reduced to .

[0065] The simplified formula is as follows:

[0066] ;

[0067] Through this mathematical transformation, the simplified formula avoids directly calculating the interaction between each pair of features, but first accumulates and then calculates the square and the difference of the accumulated squares, thus avoiding expensive nested loops. This idea of ​​converting the calculation of interaction terms into summing first and then calculating the square reduces repeated multiplications and speeds up operations. For large-scale features, this optimization significantly improves computational efficiency, and the simplified calculation is more suitable for distributed and parallel processing because it converts the more complex interaction calculation into vector operations that are easier to perform efficiently in a distributed environment.

[0068] At the same time, the introduction of stochastic gradient descent SGD in the FM algorithm is a commonly used optimization method for training model parameters, but it is still rarely used in the Spark big data environment. In fact, SGD is particularly effective when processing large-scale data, because it only uses one or a small number of samples in each iteration to update model parameters instead of the entire data set, thereby speeding up the training process, and RDD can effectively retain intermediate results in memory. The combination of the two can significantly improve access performance. In addition, Spark itself supports dimension reduction optimization. By reducing the number of features through feature selection and dimension reduction technology, the model complexity and computational overhead can be reduced. In practical applications, data can be reasonably partitioned to each computing node to ensure uniform data distribution, which can also improve resource utilization and computing efficiency; in addition, a custom accumulator aggregate gradients across nodes can be designed to parallelize gradient calculations. By allowing each data partition to independently calculate its contributed gradient and then perform gradient aggregation, parallel gradient calculation level optimization can be achieved.

[0069] Finally, in the Spark-based parallel FM algorithm, the objective function is usually to minimize the prediction error. For different problems, there may be different loss functions.

[0070] 1. Regression tasks. For regression tasks, such as predicting users’ ratings of products, the mean squared error (MSE) can be used as the loss function. The objective function is roughly as follows:

[0071] .

[0072] in, represents the regularization parameter.

[0073] 2. Classification tasks. For classification tasks, especially binary classification problems, such as click-through rate prediction (CTR), the logistic loss function is usually used, and the objective function is as follows:

[0074] .

[0075] The goal of the Spark-based parallel FM algorithm is to find a set of model parameters , so that the loss function defined above Minimize. Implementing these objective functions in Spark can take advantage of RDD (Resilient Distributed Dataset) operations or DataFrame APIs to parallelize the calculation of losses and gradients on multiple cluster nodes. Of course, the Spark MLlib library also provides direct support and high-level APIs for some optimization algorithms to help simplify the process.

[0076] The embodiment of the present invention takes the CTR advertisement click rate prediction as an example, and predicts the user's preference probability by predicting the CTR advertisement click rate of the user; adopts Spark on Yarn cluster, master-slave architecture, and uses HDFS (Hadoop distributed file system) to store and load data; uses Spark cluster as the computing engine, and then uses the factorization machine (FM) model optimized for parallelization to predict the user's click on the recommended items, and generates the final recommendation sequence based on the click rate prediction. The method can process massive data and improve the click-through conversion rate, and specifically includes the following steps:

[0077] First, download Hadoop 2.7.6, configure Hadoop environment variables and the core file core-site.xml, then configure hdfs-site.xml and yarn-site.xml, format hdfs, and enter the command: "hdfsnamenode -format" "start-dfs.sh" "start-yarn.sh" to start hadoop. Download spark 2.4.4, configure Spark environment variables, and modify the default cluster mode of spark-defaults.conf to Yarn, and then start the Spark cluster with the command: "start-all.sh". Ensure that the Spark cluster and the corresponding environment are running correctly.

[0078] Secondly, use Spark's DataFrame or RDDAPI to load data from the data source and preprocess the raw data. This step includes three steps: data cleaning, feature engineering, and feature vectorization. Data cleaning is a key step to ensure data quality, including deleting missing value records and filling missing values ​​with the average value, and then replacing outliers with the average median. Feature engineering includes one-hot encoding of categorical variables and standardization of numerical variables, converting categorical variables into indexes using "StringIndexer", one-hot encoding using "OneHotEncoder", and standardizing numerical variables using "StandardScalar". Then use Spark's VectorAssembler to combine all feature columns into a vector column and use VectorAssembler to convert feature columns into feature vectors. Divide the data set into training, validation, and test sets.

[0079] Again, the data structure of the FM model is designed to store model parameters, including global bias, linear term weights, and latent vectors. Spark provides two classes, FMRegressor (regression task class) and FMClassifier (classification task class), which encapsulate the factorization machine (FM) algorithm for regression and classification problems, respectively. Using these classes can greatly simplify the implementation and application of the FM model on Spark. The CTR advertising click-through rate prediction in the embodiment of the present invention belongs to a classification problem. The calculation formula of FMRegressor is: In addition to the linear part (similar to linear regression), the model also contains a quadratic term that models the interaction of features. This quadratic term is obtained by the latent vector representation of the feature vector and the dot product calculation between the latent vectors, so that the model can capture the complex relationship between features. This is the key feature that distinguishes the FM model from other linear models. At the same time, in the Spark implementation, FMRegressor usually requires users to specify some hyperparameters, such as: featuresCol input feature column, labelCol label column, predictionCol prediction result column name, maxIter maximum number of iterations; stepSize learning rate, used to control the step size of gradient descent; factorSize dimension of the latent vector, that is, in the above formula and The dimensions of these parameters control the model's ability to capture feature interactions. By adjusting these parameters, the performance of the model can be optimized to adapt to application scenarios with different data sets. The core calculation formula of FMClassifier is similar to that of FMRegressor, but the sigmoid function or other activation functions suitable for classification tasks are used in the final output to map the predicted values ​​into the probability space for prediction of binary or multi-classification problems. In order to perform classification, FMClassifier converts the original predicted values ​​into Mapped to probability space through the sigmoid function (or possibly the softmax function in multi-classification problems): ;here Represents a given input feature When The probability of being 1. Based on this probability and a preset threshold (such as 0.5), the prediction result can be converted into a class label. In the binary classification problem, if , the predicted category is 1, otherwise the predicted category is 0.

[0080] Gradient calculation and weight update in FMwithSGD are implemented by stochastic gradient descent. Based on the calculated gradient, the SGD formula is used to update the model parameters:

[0081] ;

[0082] in, is the t-th iteration parameter, is the learning rate, is the loss function over parameters gradient.

[0083] In order to make it distributed in Spark, we can use Spark's parallel computing function to batch process data and calculate gradients. Figure 3 As shown in the figure, the calculation process is divided into three stages: Stage 1, data preprocessing, including dividing the data set DS into multiple blocks; preprocessing each block and converting it into RDD (Resilient Distributed Dataset), which is the basic data structure of Spark; applying Map operation to each RDD to convert the data into DataFrame, so that more efficient operations can be performed using Spark's DataFrame API; Reduce operation, that is, converting features into output results, usually involving aggregation or summary operations; finally, dividing the processed features into training sets and test sets to prepare for subsequent model training and evaluation. Stage 2, model training, including further dividing the training set results into multiple Split blocks for parallel processing; converting each Split block into DataFrame through Map operation, and then performing Reduce operation; using factor decomposition machine combined with stochastic gradient descent (SGD) algorithm for prediction, judging whether the prediction result is less than a certain threshold, if it is less than the threshold, returning to Map operation for reprocessing; if it is greater than the threshold, passing the result to the next stage. Stage 3, the process is similar to Stage 2, the difference is that the training set is replaced by the test set.

[0084] See also Figure 4 As shown in the figure, the training process is to distribute data to different working nodes through Spark. Each working node performs local gradient calculation based on the data set it is assigned and determines whether it has converged. If it has, the model is saved to HDFS and the training ends. Otherwise, further local training is performed on the working node (using the SGD method). There is a communication granularity threshold in the training process to determine whether enough training has been completed locally. If the set communication granularity threshold is not reached locally, more training will continue locally; if the threshold is reached, the local model will be calculated and the parameters will be uploaded. The server summarizes the parameters of all working nodes to update the global model, and then starts the next partition to calculate the gradient and determine whether it has converged. Iterate continuously until the model reaches the convergence standard.

[0085] The specific implementation process of Spark's distributed computing and parallel partition iterative computing of data is as follows:

[0086] The constructor of the FMwithSGD class is used to initialize various properties of the FM model, including the task type, learning rate, number of iterations, model dimension (dim), regularization parameter (regParam), and mini-batch data ratio. These methods are used to set and modify the parameters of the model, and flexibly adjust the model configuration after the object is created. The generateInitWeights() method is used to generate the initial weight vector, including the factor matrix v, the first-order interaction weight w, and the global bias term The trained weight vector is converted into the FM model object FMModel through the createModel() method, and the weight vector is split into the factor matrix v, the first-order weight w and the global bias term , convert v to DenseMatrix, w to Vector and return the FMModel object. Determine numFeatures by reading the first data point, and determine the range of labels according to the task type (regression or classification). If it is a regression task, the minimum and maximum label values ​​are calculated through aggregation operations to ensure that the data is within a specific range; if it is a classification task, the label is a discrete category label, so the set of categories needs to be determined. Determine the range of labels by mapping these category labels to integer indices (for example, 0, 1, 2, ...) to ensure that the category information of the data can be used correctly during training. Define the gradient calculation method FMGradient() for the optimizer and FMUpdater() for updating weights, where FMGradient() is responsible for calculating the gradient of the factorization machine model, where the calculation method of the gradient is affected by the task type and model dimension. FMUpdater() is responsible for performing weight updates, including the processing of regularization terms). Use the GradientDescent optimizer based on the incoming gradient and updater to gradually update the weights of the model, and configure the stochastic gradient descent algorithm, including the learning rate, number of iterations, and mini-batch ratio. Finally, the input data is processed according to the task type (regression or classification). If it is a classification task, the label value is converted to 1.0 if it is positive, otherwise the label value is converted to 0.0 if it is negative. The optimizer's optimize method is called to input the data and initial weights, perform stochastic gradient descent, return the optimized weights, and use the optimized weights to generate the final FM model.

[0087] When executing SGD, mini-batch is usually used to reduce variance and improve convergence speed. In Spark, the sample function is used to sample data and select a small part of the data to calculate the gradient of each iteration. In this way, only a part of the data is used to calculate the gradient in each iteration, thus realizing distributed SGD in mini-batch mode. In Spark, broadcast variables allow efficient sharing of read-only data in the cluster. The current model parameters (such as weight vectors) can be broadcast to all computing nodes to reduce communication overhead: the inner product operation is performed with the feature vector of the sample to obtain the predicted value. Further, the error between the predicted value and the true target value is calculated, and based on the error, the rule of the selected loss function (such as square error, logarithmic loss, etc.) is applied to calculate the contribution of the data point to the model gradient and the corresponding loss value. Within each partition, Spark will first aggregate the gradient and loss of the partition, which can reduce the burden of cross-node communication. Through operations such as reduce or treeAggregate, the gradients and losses of all partitions are aggregated to the driver node for global accumulation. The data structures used in this process are usually sparse vectors or accumulator types to improve efficiency. The aggregated global gradients are used to update the parameters. This can be a simple gradient descent or a more complex optimization algorithm (such as stochastic gradient descent (SGD), momentum gradient descent (Momentum), RMSprop, Adam, etc.). The update step may include a strategy for dynamically adjusting the learning rate, such as learning rate decay or adaptive learning rate for each parameter. Regularization terms (such as L1, L2 regularization) may also be applied during the update process to avoid overfitting and promote generalization. The updated model parameters are sent back to each node in the cluster through Spark's broadcast mechanism. This means that the latest model parameters can be used for the next round of iterative calculations.

[0088] The above gradient calculation steps and batch processing steps form an iterative loop, which is repeated many times until the convergence condition is met (for example, the maximum number of iterations is reached, or the loss improvement is lower than a threshold).

[0089] After the model training is completed, the performance of the model needs to be evaluated. On the driver node, the convergence of the model will be evaluated by comparing the loss difference between consecutive iterations. During the iteration process, if any node fails, Spark's fault tolerance mechanism can restart the task to execute on other nodes, ensuring the robustness of the calculation. And because Spark's RDD and DataFrame operations are all performed in memory, this process is faster than traditional disk IO. Use the trained model to make predictions on the validation set. Mean square error (MSE) is one of the commonly used evaluation metrics for regression models. It measures the average squared error between the predicted value and the actual value. For classification tasks, accuracy, recall, and F1 score can be calculated. These metrics can be calculated using the MulticlassClassificationEvaluator function provided by Spark. AUC (area under the ROC curve) is a common metric for measuring classifier performance, especially for binary classification problems. It represents the ability of the model to distinguish between positive and negative samples, and can be implemented using the BinaryClassificationEvaluator function provided by Spark.

[0090] Apache Spark's MLlib provides CrossValidator, ParamGridBuilder, and evaluators (such as BinaryClassificationEvaluator) to form a powerful tool set for automated model selection and hyperparameter tuning. The first step is to define an evaluator, that is, the model you want to train. In Spark MLlib, an evaluator can be any algorithm, such as LogisticRegression, RandomForestClassifier, or FMClassifier. The second step is to use ParamGridBuilder to define the parameter combinations you want to experiment with. For example, for a factorization machine, you may want to adjust the parameters including the learning rate (stepSize), regularization parameter (regParam), factor dimension (factorSize), etc. The third step is to select the evaluation criterion and define the evaluation criterion used to measure the performance of the model. This can be done with an evaluator, such as BinaryClassificationEvaluator for binary classification problems, which can evaluate AUC, accuracy, etc. The fourth step is to configure cross validation. Use CrossValidator to configure the cross validation process. Specify the evaluator (model), parameter grid, evaluator, and the number of cross validation folds (usually 3, 5, or 10 folds). The fifth step is to run cross validation to select the best parameters, pass the dataset to the cross validator, and run the cross validation process. CrossValidator will automatically train and evaluate each parameter combination and select the parameter combination that performs best on the given evaluation metric. Finally, use the selected best model parameters to evaluate model performance on the validation dataset or test dataset.

[0091] Finally, the trained Spark MLlib model can be saved to HDFS through the write.save() method to achieve distributed storage and backup, ensuring the persistence and reusability of the model. After loading the model, you can use the model for real-time prediction in the actual production environment.

[0092] It can be seen that the present invention provides a method for parallelizing the FMwithSGD algorithm based on Spark, which can efficiently process large-scale, high-dimensional sparse data sets through the distributed computing capabilities, memory computing, elastic fault tolerance and data locality of Spark and the high computing efficiency, low memory usage and fast convergence speed of SGD. This method not only improves the computing speed and scalability, but also ensures the reliability and flexibility of the calculation, and is suitable for various big data analysis and machine learning tasks.

[0093] The above are only preferred embodiments of the present invention and are not intended to limit the present invention. Any modifications, equivalent substitutions, improvements, etc. made within the spirit and principles of the present invention should be included in the protection scope of the present invention.

Claims

1. A distributed recommendation method based on Spark platform, It is characterized in that The following steps are involved: A FM prediction model is constructed by combining factorization machine and stochastic gradient descent. The FM prediction model takes a feature matrix including user, item and context information as input and outputs predicted user behavior; Configure the Spark platform environment and load the original data, and preprocess the original data to obtain the data set; The Spark platform initializes the FM prediction model and trains it according to the task type. During the training process, the Spark platform performs parallel gradient calculations and aggregates gradients to update parameters. Deploy the trained FM prediction model to the actual production environment to perform real-time predictions for different task types and implement recommendations.

2. According to the Spark platform-based distributed recommendation method of claim 1, It is characterized in that The Spark platform environment is configured and the original data is loaded, specifically: Install and configure the Spark on YARN cluster; Load raw data including user, item, and context information from HDFS or local file system.

3. According to the Spark platform-based distributed recommendation method of claim 1, It is characterized in that The preprocessing of the original data to obtain the data set includes: Data cleaning, including deleting missing value records and filling missing values ​​with the mean value, and replacing outliers with the mean median; Feature engineering, including one-hot encoding of categorical variables and standardization of numerical variables; Feature vectorization, using Spark's VectorAssembler to combine all feature columns into a vector column and convert it into a feature vector.

4. The distributed recommendation method based on the Spark platform according to claim 3, It is characterized in that The process of initializing the FM prediction model includes: Initialize the factor matrix to represent implicit interactions between features; Initialize the weights and biases for each feature.

5. According to the Spark platform-based distributed recommendation method of claim 4, It is characterized in that The training according to the task type includes the following steps: In the data partitioning step, Spark divides the data set into multiple partitions and distributes them to different nodes; Convergence judgment step: judge whether the current model training reaches the convergence standard. If yes, save the model and end the training; otherwise, perform local training on the model on each node according to the data assigned to the node until the local training reaches the communication granularity threshold, and then enter the update step; In the update step, the local training data is summarized to update the model parameters and return to the convergence judgment step.

6. The distributed recommendation method based on the Spark platform according to claim 5, It is characterized in that The model is locally trained on each node according to the data assigned to the node, and the process of local training on each node includes the following steps: The predicted value is obtained by the inner product of the feature vector and the model parameter, and the error between the predicted value and the actual value is calculated; The gradient derivative of the loss function with respect to the model parameters is calculated based on the error between the predicted value and the actual value, and the gradient and loss of the partition are obtained by accumulating the data in each node.

7. The distributed recommendation method based on the Spark platform according to claim 6, It is characterized in that The updating step specifically comprises: globally accumulating the gradients and losses of all nodes; and updating the model parameters based on the gradients and losses obtained by the global accumulation.

8. The distributed recommendation method based on the Spark platform according to claim 6, It is characterized in that The task types include: For regression tasks, the FM prediction model predicts the user's rating of the item based on the input feature matrix; for regression tasks, the loss function uses the mean square error function; For classification tasks, the FM prediction model predicts whether the user clicks on the item based on the input feature matrix; for classification tasks, the loss function uses a logarithmic function or a cross entropy loss function.

9. The distributed recommendation method based on the Spark platform according to claim 7, It is characterized in that The Spark platform performs parallel gradient calculation and aggregates gradients in a mini-batch manner, specifically: The sample function is used to sample the data in the dataset and select a small part of the data to calculate the gradient of each iteration. Only a part of the data is used to calculate the gradient in each iteration, thus realizing the distributed SGD in mini-batch mode.

10. The distributed recommendation method based on Spark platform according to claim 1, It is characterized in that The deployment of the trained FM prediction model to the actual production environment includes the following steps: Save the trained model to HDFS and local file system; Load the trained model according to the task type, and use the model for real-time prediction in the actual production environment.

Citation Information

Patent Citations

  • Distributed recommendation method based on Spark platform

    CN107451267A

  • Large-batch decentralized distributed image classifier training method and system

    CN114186671A

  • Systems and methods for self-guided sequence selection and extrapolation

    US20240070744A1

Cited By

  • Model optimization method and device suitable for extra-long prediction

    CN120046813A