Big language model-based customs named entity recognition method
Patent Information
- Application Number
- CN202410935013.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-12
- Publication Date
- 2024-10-18
AI Technical Summary
The scarcity of annotated data in the customs field causes models such as BERT to perform poorly in entity recognition tasks, with low accuracy and efficiency.
Use a large-scale pre-trained language model for fine-tuning, use a small amount of annotated data to perform entity recognition in customs text, automatically extract entities from unannotated text, reduce reliance on manual annotation, and adapt to different text formats and regulatory changes.
Significantly reduces the need for annotated data, improves the efficiency and accuracy of entity identification, provides an efficient and reliable text processing tool, can quickly adapt to changes in customs regulations and regulations, reduces error rates, and improves the efficiency and accuracy of customs management. Regulatory Compliance.
Smart Images

Figure CN118798200A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of entity recognition, and in particular to a customs named entity recognition method based on a large language model. Background Art
[0002] In global trade, the complexity of customs rules and regulations poses a huge challenge to customs management and compliance inspection. Traditional text processing methods mainly rely on manual annotation and rule matching, which is not only time-consuming and labor-intensive, but also prone to errors. Especially in the customs field, annotated samples are usually very limited, which puts higher requirements on classification tasks based on models such as BERT, because these models usually require a large amount of annotated data for effective training.
[0003] In the existing technology, the BERT classification model performs well in entity recognition tasks, but its performance is highly dependent on a large amount of high-quality labeled data; however, labeled data in the customs field is very scarce and cannot meet the needs of model training, resulting in greatly reduced accuracy and efficiency of entity recognition.
[0004] The present invention solves this pain point through the following technical innovations:
[0005] 1. Efficient use of small amounts of annotated data: Using a large-scale pre-trained language model, fine-tuning with a small amount of annotated data enables the model to accurately identify entities in customs texts even when data is scarce;
[0006] 2. Automated entity recognition: Automatically extract entities from a large number of unlabeled customs regulations and legal texts, greatly reducing the reliance on manual labeling;
[0007] 3. Strong adaptability: The model can quickly adapt to changes in different text formats and regulations, maintaining efficiency and accuracy. Summary of the invention
[0008] In view of the shortcomings of existing methods, the present invention significantly reduces the demand for labeled data, improves the efficiency and accuracy of entity recognition, and provides customs management departments with an efficient and reliable text processing tool.
[0009] The technical solution adopted by the present invention is: a method for customs named entity recognition based on a large language model comprises the following steps:
[0010] Step 1: Collect the texts of customs regulations and tariffs, and pre-process the texts to obtain a text library;
[0011] As a preferred implementation of the present invention, preprocessing includes: text conversion of PDF files, loading of Excel files, and entity annotation of text using regular expressions and labelstudio.
[0012] Step 2: Construct the annotated text into Alpaca format according to the prompt word template to obtain a text dataset;
[0013] As a preferred embodiment of the present invention, constructing into Alpaca format includes: storing the annotated text and entity type as input fields, and storing the annotated entity as output fields.
[0014] Step 3: Input the text dataset into the Transformer Encoder model, and use the self-attention mechanism to calculate the attention weight of each word in the input sequence to other words to capture contextual information; use a feedforward neural network to process the output of the self-attention mechanism, normalize each layer, and use residual connections to add the input and output of each layer to obtain the embedding vector of the text data;
[0015] As a preferred implementation of the present invention, the Transformer Encoder model includes 12 Transformer Encoder layers.
[0016] As a preferred embodiment of the present invention, the Transformer Encoder layer includes:
[0017] First, the input text data is converted into a word vector sequence, and the position vector is added to the word vector sequence using the position embedding layer;
[0018] Secondly, the vectors are processed through a multi-head self-attention mechanism to calculate the relationship between words, and the attention distribution is calculated in parallel through different attention heads;
[0019] Secondly, the outputs of multiple attention heads are concatenated together and linearly transformed;
[0020] Secondly, the vector processed by the self-attention mechanism is passed to the feedforward neural network;
[0021] Secondly, perform layer normalization;
[0022] Finally, after the self-attention mechanism and each sub-layer of the feed-forward neural network, the input and output are added together through a residual connection.
[0023] Step 4: Use LoRA to incrementally train the query projection matrix, key projection matrix, value projection matrix, and output projection matrix in the attention mechanism of the Llama3 pre-trained model, insert a low-rank matrix into each layer of the attention structure, and perform gradient descent training through the loss function to obtain parameter increments.
[0024] As a preferred embodiment of the present invention, step 4 specifically includes:
[0025] Step 41: Load the Llama3 pre-trained model and obtain the pre-trained parameters W O ;
[0026] Step 42, calculate the vectors of the query projection matrix, the key projection matrix, the value projection matrix and the output projection matrix;
[0027] Step 43: Use the projection matrix vector to obtain the output of the attention head;
[0028] Step 44: Use the feedforward neural network layer to perform a linear transformation on the output of the attention head;
[0029] Step 45: perform inter-layer normalization and residual connection.
[0030] As a preferred implementation of the present invention, the loss function is a cross entropy loss.
[0031] Step 5: Use the transformers package of huggingface to merge the low-rank matrix with the weight increment of the Llama3 pre-trained model to obtain the Llama-NER model.
[0032] As a preferred embodiment of the present invention, the Llama-NER model is evaluated using selection accuracy, recall rate and F1 score.
[0033] As a preferred embodiment of the present invention, a customs named entity recognition system based on a large language model includes: a memory for storing instructions executable by a processor; a processor for executing the instructions to implement a customs named entity recognition method based on a large language model.
[0034] As a preferred embodiment of the present invention, a computer readable medium stores a computer program code, and when the computer program code is executed by a processor, a method for customs named entity recognition based on a large language model is implemented.
[0035] Beneficial effects of the present invention:
[0036] 1. Reduce data dependence. In professional fields such as customs, high-quality annotated data is often difficult to obtain. The present invention uses the powerful language understanding ability of the large language model to maintain a high entity recognition accuracy rate even when annotated data is scarce.
[0037] 2. High degree of automation. The present invention extracts entities from a large number of unlabeled customs regulations and legal texts in an automated manner, which reduces manual intervention and improves processing speed and efficiency;
[0038] 3. Strong adaptability. Customs regulations and laws are often updated and changed. The present invention can quickly adapt to these changes and maintain the validity and accuracy of the model;
[0039] 4. Improve customs management efficiency. Through automated entity recognition, customs management departments can process large amounts of text data more quickly, improving work efficiency and regulatory compliance;
[0040] 5. Reduce the error rate. Compared with the traditional manual processing method, the present invention utilizes advanced natural language processing technology to significantly reduce the error rate in customs text processing. BRIEF DESCRIPTION OF THE DRAWINGS
[0041] Figure 1 It is a flow chart of the method for customs named entity recognition based on a large language model of the present invention. DETAILED DESCRIPTION
[0042] The present invention is further described below in conjunction with the accompanying drawings and embodiments. This figure is a simplified schematic diagram, which only illustrates the basic structure of the present invention in a schematic manner, and therefore it only shows the components related to the present invention.
[0043] like Figure 1 As shown, a method for customs named entity recognition based on a large language model includes the following steps:
[0044] Step 1: Collect announcements from a website, as well as regulations and tariffs issued by a department, pre-process web pages and attachments (pdf, xls, xlsx) and other data to obtain a text library;
[0045] Preprocessing includes extraction of web page content, text conversion of PDF files, loading of Excel files and data extraction, etc.
[0046] Use regular expressions and labelstudio annotation tools to annotate the text, and organize entities and relationships into BIO sequence format; during the annotation process, entities closely related to customs business, such as ports, customs, ports, inspections, etc., are annotated; entity types include commodities, institutions, freight forwarding companies, cargo owners and regions, etc.; find the connections between entities, entity relationships, and entity types.
[0047] Step 2: Construct the annotated text into Alpaca format according to the prompt word template. During the construction process, the annotated text and entity type are stored as input fields, and the annotated entity is stored as an output field in JSON format.
[0048] For example: "input":"{Extract the triples that can describe this paragraph from text and store them in json format;\",\"text\":\"For goods subject to export quota bidding, regardless of the mode of trade, each authorized issuing agency shall issue export licenses based on the list of winning enterprises and the number of winning bids issued by a certain department and the "Certificate of Applying for Export License for Quota Bidding Goods" issued by a certain department.\"}",
[0049] "output":"[
[0050] {"entity":"Export quota bidding goods","attribute":"issuing agency","value":"authorized issuing agency"};
[0051] {"entity":"Export quota bidding goods","attribute":"issuance basis","value":"list of winning enterprises and their winning quantities issued by a certain department"};
[0052] {"entity":"Export quota bidding goods","attribute":"Certificate of issuance","value":"Certificate of application for export license of goods subject to quota bidding issued by a certain department"};
[0053] {"entity":"Authorized Issuing Authority","attribute":"action","value":"Issue export license"};
[0054] {"entity":"Export License","attribute":"Applicable Goods","value":"Goods subject to export quota bidding"};
[0055] {"entity":"Export License","attribute":"Applicable Trade Method","value":"regardless of trade method"}]"}.
[0056] Step 3: Input the text dataset into the Transformer Encoder model, use the self-attention mechanism to calculate the attention weight of each word in the input sequence to other words, and capture contextual information; use the feedforward neural network to process the output of the self-attention mechanism, normalize each layer, and use the residual connection to add the input and output of each layer to encode the text data into an embedded vector;
[0057] Use the Transformer Encoder model to get the embedding vectors of input and output for the dataset obtained in step 2;
[0058] The overall structure of the Transformer Encoder model consists of multiple Transformer Encoder layers stacked together, each of which contains a self-attention mechanism and a feedforward neural network; the final output passes through a pooling layer and a fully connected layer, and is then output through a Softmax layer for classification or other tasks.
[0059] The number of Transformer Encoder layers is 12, and each layer includes a self-attention mechanism that calculates the attention weight of each word in the input sequence to other words to capture contextual information; the feedforward neural network further processes the output of the self-attention mechanism; layer normalization normalizes the output of each layer to help stabilize and accelerate the training process; residual connections add the input of each layer to its output to alleviate the gradient vanishing problem.
[0060] First, the input text data is converted into a sequence of word vectors. These word vectors are obtained through pre-trained word embedding layers (such as Word2Vec, GloVe, etc.), which represent the initial representation of each word in the text. In order to make the TransformerEncoder model aware of the position information of words, the position embedding layer is used to add position vectors to the word vector sequence. The position vector encodes the position information of the word in the sentence. The formula is as follows:
[0061]
[0062] Among them, PE() is the position information vector, pos is the position of the word in the sentence, i is the dimension index of the word vector, and d model is the dimension of the word vector.
[0063] Next, the vector is processed through the multi-head self-attention mechanism to calculate the relationship between words and capture different aspects of information. The core of the multi-head self-attention mechanism is to calculate the attention distribution in parallel through different attention heads. The calculation formula for each attention head is as follows:
[0064]
[0065] Where Q is the query vector; K is the key vector; V is the value vector; d k is the dimension of the key vector; softmax is the activation function used to normalize the weights.
[0066] The multi-head attention mechanism concatenates the outputs of multiple attention heads and passes a linear transformation to obtain:
[0067] MultiHead(Q,K,V)=Concat(head1,head2,…,head h )W O (4)
[0068] Among them, head h is the hth attention head, W O is the linear transformation matrix.
[0069] Then, the vector processed by the self-attention mechanism is passed to a feed-forward neural network (FFN); each position information vector passes through the same FFN separately. The FFN consists of two linear transformations and an activation function, and the formula is as follows:
[0070] y=FFN(x)=max(0,xW1+b1)W2+b2 (5)
[0071] Among them, W1 and W2 are weight matrices of linear transformation, b1 and b2 are bias vectors, and x is the FFN independent variable, that is, x is the output of MultiHead.
[0072] After the self-attention mechanism and the feedforward neural network, layer normalization is performed to stabilize and accelerate the training process. The formula for layer normalization is as follows:
[0073]
[0074] Among them, μ is the mean, σ 2 is the variance, ∈ is a small constant, ∈ is 10 -6 ; γ and β are trainable parameters, and y is the output of FFN.
[0075] Finally, after each sublayer of the self-attention mechanism and feedforward neural network, there is a residual connection to add the input and output to alleviate the gradient vanishing problem. The formula for the embedding vector is as follows:
[0076] X=Output=LayerNorm(x'+SubLayer(x')) (7)
[0077] Among them, LayerNorm is layer normalization; x' is the input tensor of SubLayer, and SubLayer(x') is the output of the sublayer.
[0078] Through the above steps, the input text data will eventually be encoded into embedding vectors that can capture the complex semantic relationships in the text.
[0079] For example, suppose the input text is: "Customs releases new regulations, import and export companies need to pay attention", first convert the input text data into a word vector sequence, and use the Word2Vec word embedding layer to obtain the initial representation of each word, "Customs", "release", "new regulations", "import and export", "enterprise", "need", "note". In actual operation, each word in the text will be converted into a high-dimensional vector to represent their initial representation.
[0080] In order to make the Transformer Encoder model aware of the position information of words, position vectors are added to the word vector sequence. The results after adding position vectors include:
[0081] The word vector of "customs" + the vector at position 1, the word vector of "release" + the vector at position 2, the word vector of "new regulations" + the vector at position 3, the word vector of "import and export" + the vector at position 4, the word vector of "enterprise" + the vector at position 5, the word vector of "need" + the vector at position 6, and the word vector of "attention" + the vector at position 7. The vectors will be input into the Transformer Encoder.
[0082] The self-attention mechanism calculates the attention weight of each word to all other words. For the input sequence "Customs releases new regulations, import and export enterprises need to pay attention", the self-attention mechanism will consider the relationship between each word and all other words. For example, considering the word "customs", the attention weight of "customs" to "customs" is calculated, the attention weight of "customs" to "release", the attention weight of "customs" to "new regulations", the attention weight of "customs" to "import and export", the attention weight of "customs" to "enterprise", the attention weight of "customs" to "need", and the attention weight of "customs" to "attention" are calculated; similarly, for each other word, their attention weights to all other words in the sequence are also calculated.
[0083] Through the multi-head self-attention mechanism, multiple attention distributions can be calculated in parallel, each attention head processes different aspects of information, and then their outputs are spliced together and passed through a linear transformation.
[0084] Step 4: Use LoRA to incrementally train the four projection matrices q_proj (query projection), k_proj (key projection), v_proj (value projection), and o_proj (output projection) in the attention mechanism of the Llama3 pre-trained model using the embedding vector obtained in step 3, and save the training parameters with the best effect; insert a trainable low-rank matrix into each layer of the attention structure of Llama3, perform gradient descent training through the loss function, and obtain parameter increments;
[0085] Specifically, step 41 first loads the Llama3 pre-trained model and obtains the pre-trained parameters W O ; Insert a trainable low-rank matrix L into each layer of Llama3's attention. The matrix L is used to fine-tune the four projection matrices of the attention in the Llama3 model.
[0086] Step 42: Calculate the corresponding vector according to q_proj, k_proj, v_proj and o_proj. The formula is:
[0087] Q=XW Q +LX (8)
[0088] K=XW K +LX (9)
[0089] V=XW V +LX (10)
[0090] O=XW O +LX (11)
[0091] Among them, Q is the query vector, which means that the embedding vector X and the query projection matrix W Q and the query vector calculated by the low-rank matrix L; K is the key vector, which represents the embedding vector X and the key projection matrix W K and the key vector calculated by the low-rank matrix L; V is the value vector, which represents the embedding vector X and the value projection matrix W V and the value vector calculated by the low-rank matrix L; O is the output vector, which represents the embedding vector X and the output projection matrix W O and the value vector calculated by the low-rank matrix L; W Q is the weight matrix used to calculate the query vector in the pre-trained model; W K is the weight matrix for calculating the key vector; W V is the weight matrix used to calculate the value vector in the pre-trained model; W O It is the weight matrix used to calculate the output vector in the pre-trained model; it is a trainable matrix inserted into each layer structure for incremental training.
[0092] Step 43, then, use the modified query, key and value projection matrices to calculate the self-attention weight, and obtain the modified attention output head' through formula (3), defined as X'.
[0093] Step 44: Then, the feedforward neural network layer further processes these outputs, first performing a linear transformation and an activation function (such as ReLU), and then performing a second linear transformation:
[0094] Hidden=ReLU(X'W1+b1) (12)
[0095] Output'=HiddenW2+b2 (13)
[0096] Among them, ReLU is the activation function used for nonlinear transformation of feedforward neural network; W1 and W2 are the weight matrices of feedforward neural network; b1 and b2 are the biases of feedforward neural network.
[0097] Layer normalization is performed between each layer to stabilize the training process:
[0098] Z=LayerNorm(X'+MultiHead(Q,K,V)) (14)
[0099] Among them, LayerNorm is a layer normalization operation used to stabilize the training process; MultiHead(Q,K,V) is the output of the multi-head self-attention mechanism.
[0100] At the same time, a residual connection is added to retain the input information. The formula is:
[0101] Output”=LayerNorm(Z+FFN(Z)) (15)
[0102] Among them, FFN(Z) is the output of the feedforward neural network.
[0103] Define the loss function. In this example, cross entropy loss is used. The formula is:
[0104] Loss = cross-entropy(y true ,y pred ) (16)
[0105] Among them, cross-entropy(y true ,y pred ) is the cross entropy loss function, which is used to measure the prediction result y pred With the true result y true difference.
[0106] The Llama3 model parameters and the low-rank matrix L are updated through the gradient descent algorithm. At the end of each training cycle, the model performance is evaluated, and if there is an improvement, the current optimal parameters are saved. In this way, the model performance can be effectively improved by inserting a trainable low-rank matrix into the structure of each layer and performing incremental training.
[0107] Step 5: Use the transformers package of huggingface to merge the low-rank matrix L obtained in step 4 with the Llama3 pre-trained model to obtain the Llama-NER model; the merged model can perform entity recognition on customs texts;
[0108] First, apply the LoRA parameters obtained in step 4 to the weights of the Llama3 model. According to the LoRA formula, merge the W0 of the Llama3 pre-trained model and the weight increment ΔW calculated in step 4:
[0109] W=W O +ΔW=W O +BA (17)
[0110] Among them, W O is the weight matrix used to calculate the output vector in the pre-trained model, ΔW is the weight increment calculated by the LoRA method, that is, the low-rank matrix L. The low-rank matrix L is composed of the product of two low-rank matrices B and A. The low-rank matrix L is obtained by the product of two smaller matrices A and B, where:
[0111] A is a d×r matrix, usually initialized randomly; B is an r×k matrix, usually initialized to a zero matrix; here d is the dimension of the input, k is the dimension of the output, and r is the rank of the low-rank matrix.
[0112] The low-rank adapter parameters B and A are applied to the Llama3 model to generate a Llama-NER model suitable for entity recognition in customs texts.
[0113] Load the merged Llama3-NER model, pass the unlabeled text into the model to determine the customs entities that exist, perform entity recognition on the text through the model, and output the recognition results.
[0114] In order to verify the effectiveness of the above method, the method of the present invention was experimented on the DUIE dataset and compared with the baseline results. The method model of the present invention was developed by using Python and Pytorch machine learning library. In order to avoid overfitting of the model, different dropout rates were used in the input layer and hidden layer. And the model was optimized by Adam optimizer. In addition, when the results on the validation set did not improve for 30 consecutive periods, the training of the model was stopped.
[0115] The present invention selects precision (P), recall (R) and F1 score to evaluate the prediction results on the data set. If the boundary and type of the entity are correct, the entity is judged to be correct; when the type and parameter entity of the relationship are correct, the relationship is correct.
[0116] Table 1 Experimental results on DUIE dataset
[0117]
[0118] Based on the above ideal embodiments of the present invention, the relevant staff can make various changes and modifications without departing from the technical concept of the present invention through the above description. The technical scope of the present invention is not limited to the contents of the specification, and its technical scope must be determined according to the scope of the claims.
Claims
1. A customs named entity recognition method based on a large language model, characterized in that: The following steps are involved: Step 1: Collect customs regulations and tariff texts, and pre-process the texts to obtain a text library; Step 2: Construct the annotated text into Alpaca format according to the prompt word template to obtain a text dataset; Step 3: Input the text dataset into the Transformer Encoder model and use the self-attention mechanism to calculate the attention weight of each word in the input sequence to other words to capture contextual information. The output of the self-attention mechanism is processed using a feedforward neural network, each layer is normalized, and the input and output of each layer are added using a residual connection to obtain the embedding vector of the text data; Step 4: Use LoRA to incrementally train the query projection matrix, key projection matrix, value projection matrix, and output projection matrix in the attention mechanism of the Llama3 pre-trained model, insert a low-rank matrix into each layer of the attention structure, and perform gradient descent training through the loss function to obtain parameter increments. Step 5. Use the transformers package of huggingface to merge the low-rank matrix with the weight increment of the Llama3 pre-trained model to obtain the Llama-NER model.
2. The method for customs named entity recognition based on a large language model according to claim 1 is characterized in that: The Transformer Encoder model consists of 12 Transformer Encoder layers.
3. The method for customs named entity recognition based on a large language model according to claim 2 is characterized in that: The Transformer Encoder layer includes: First, the input text data is converted into a word vector sequence, and the position vector is added to the word vector sequence using the position embedding layer; Secondly, the vectors are processed through a multi-head self-attention mechanism to calculate the relationship between words, and the attention distribution is calculated in parallel through different attention heads; Secondly, the outputs of multiple attention heads are concatenated together and linearly transformed; Secondly, the vector processed by the self-attention mechanism is passed to the feedforward neural network; Secondly, perform layer normalization; Finally, after the self-attention mechanism and each sub-layer of the feed-forward neural network, the input and output are added together through a residual connection.
4. The method for customs named entity recognition based on a large language model according to claim 1 is characterized in that: Step 4 specifically includes: Step 41: Load the Llama3 pre-trained model and obtain the pre-trained parameters W O ; Step 42, calculate the vectors of the query projection matrix, the key projection matrix, the value projection matrix and the output projection matrix; Step 43: Use the projection matrix vector to obtain the output of the attention head; Step 44: Use the feedforward neural network layer to perform a linear transformation on the output of the attention head; Step 45: perform inter-layer normalization and residual connection.
5. The method for customs named entity recognition based on a large language model according to claim 1 is characterized in that: The loss function is cross entropy loss.
6. The method for customs named entity recognition based on a large language model according to claim 1, characterized in that: The Llama-NER model was evaluated using selection precision, recall and F1 score.
7. The method for customs named entity recognition based on a large language model according to claim 1, characterized in that: Preprocessing includes: text conversion of PDF files, loading of Excel files, regular expressions and entity annotation of text using LabelStudio.
8. The method for customs named entity recognition based on a large language model according to claim 1, characterized in that: Building into the Alpaca format involves storing the annotated text and entity types as input fields, and the annotated entities as output fields.
9. Customs named entity recognition system based on large language model, characterized by: include: a memory for storing instructions executable by a processor; A processor, configured to execute instructions to implement the method for customs named entity recognition based on a large language model as described in any one of claims 1 to 8.
10. A computer readable medium storing computer program code, characterized in that: When the computer program code is executed by a processor, the method for customs named entity recognition based on a large language model as described in any one of claims 1 to 8 is implemented.
Citation Information
Cited By
Urban subway passenger flow volume prediction method and system based on large language model
CN119761573A
