I have the following code to train a model with data from a csv file.
import spacy
from spacy.tokens import DocBin
from spacy.training import Example
from spacy.util import minibatch, compounding
import spacy.symbols as syms
import pandas as pd
import random
import re
Load a blank English model
nlp = spacy.blank("en")
Get the current infix patterns
infixes = nlp.Defaults.infixes
Remove patterns that split on commas and hyphens
infixes = [pattern for pattern in infixes if pattern not in [r'(?<=[0-9])[.,]', r'(?<=[0-9])[-,]']]
Create a new infix regex using the revised patterns
if "ner" not in nlp.pipe_names:
ner = nlp.add_pipe("ner", last=True)
else:
ner = nlp.get_pipe("ner")
Add the new entity label to the NER component
ner.add_label("ARTICLE_NUMBER")
Read the training data from a CSV file into a Pandas DataFrame
df = pd.read_csv("training_data_articles.csv")
Create a DocBin object for efficiently storing spaCy Docs
doc_bin = DocBin(attrs=["ENT_IOB", "ENT_TYPE"])
Process and annotate the data
for index, row in df.iterrows():
doc = nlp.make_doc(row["text"])
annotations = {"entities": [(int(row["article_start"]), int(row["article_end"]), "ARTICLE_NUMBER")]}
example = Example.from_dict(doc, annotations)
doc_bin.add(example.reference)
Save the DocBin to disk
doc_bin.to_disk("train.spacy")
Load the training data saved as DocBin
train_data = DocBin().from_disk("train.spacy")
Get the Doc objects in the training data
train_docs = list(train_data.get_docs(nlp.vocab))
Initialize the model with random weights
nlp.begin_training()
Training the NER model
Disable other pipes during training
with nlp.disable_pipes(*[pipe for pipe in nlp.pipe_names if pipe != "ner"]):
optimizer = nlp.resume_training()
for itn in range(10): # Number of training iterations
random.shuffle(train_docs)
losses = {}
batches = minibatch(train_docs, size=compounding(4., 32., 1.001))
for batch in batches:
examples = [Example.from_dict(doc, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]}) for doc in batch]
nlp.update(
examples,
drop=0.5, # Dropout rate
losses=losses,
sgd=optimizer
)
print(f"Iteration {itn}, Losses: {losses}")
Save the trained model to disk
nlp.to_disk("trained_model")
Assistant
Your code snippet shows the use of spaCy to create a Named Entity Recognition (NER) model for identifying ARTICLE_NUMBER entities in text. The model is trained using data from a CSV file. Here is an overview of what the code is doing:
You start by importing the necessary libraries and setting up a blank English spaCy model using spacy.blank("en").
You modify the tokenization rules to prevent splitting on commas and hyphens by adjusting the infix patterns.
You then add an NER pipeline to the blank model if it doesn't already exist.
You add a new entity label "ARTICLE_NUMBER" which your model will learn to identify.
The training data is read from a CSV file named "training_data_articles.csv" into a pandas DataFrame.
You create a DocBin object which will store the Doc objects. Doc objects in spaCy encapsulate the annotations.
You iterate through the DataFrame, converting each text into a spaCy Doc with its associated annotations (entities) using the Example.from_dict() method.
You add the Doc into the DocBin.
After processing all the data, you save the DocBin object to the disk with to_disk("train.spacy").
You load the DocBin object from the disk and obtain a list of Doc objects that will be used as training data.
You initialize the model with random weights with nlp.begin_training().
The training loop follows, where you train the NER model. You disable other components of the pipeline (nlp.disable_pipes) to focus on the NER part.
The model is trained for 10 iterations (epochs).
Training data is shuffled for each iteration to improve learning.
Losses are tracked to see how the model is improving.
A custom dropout rate is applied to prevent overfitting.
The training is performed in minibatches with a compounding batch size, which starts at 4 and increases to 32.
At the end of each iteration, you print the loss so you can monitor the model's performance.
Finally, you save the trained model to the disk.
Please note that this script assumes that the CSV file contains the columns "text", "article_start", and "article_end" with the appropriate information to train the NER model.
If you receive any errors or experience issues while running the code, be sure to check that the CSV file is formatted correctly, the spaCy library and its dependencies are installed properly, and your hardware resources are sufficient for training the model.
User
The above code runs without any error and creates a model but if i test the model with the following code i get no output.
Load the trained model and test it
nlp2 = spacy.load("trained_model")
test_texts = [
"We need 50 units of product 7380-2-4x55 for our next project.",
"Can you provide a quote for 14583-4-2,5x8?",
"Please ship 20 units of item 7380-2-4x55 ASAP"
]
for text in test_texts:
doc = nlp2(text)
for ent in doc.ents:
print(f"Entity found: {ent.text}, Label: {ent.label_}")
Assistant
If the code runs without any error and successfully trains a model, but you get no output when testing the model, there might be a few reasons for this behavior:
Training data quality and quantity: If the training data is too limited or not representative of the variety seen in the test, the model may not generalize well. Make sure your training data contains enough examples of ARTICLE_NUMBER in various contexts.
Incorrect entity annotations: Double-check the correctness of the start and end indexes in your training data. If entities are not properly annotated, the model will not learn to predict them correctly.
Complexity of entity patterns: If the patterns of ARTICLE_NUMBER are complex and not covered well in the training examples, the model might struggle to identify similar patterns in the test set.
Hyperparameters: The dropout rate, number of iterations, batch sizes, and learning rates are all critical to the model's performance. Adjusting these might improve the results.
Overfitting/Underfitting: If the model is overfitting, it will perform well on the training data but poorly on the test data. Similarly, if it is underfitting, it may not have learned enough to perform well on any data.
Saved/Loaded model mismatch: Ensure that the model saved to disk after training ("trained_model") is the model being loaded for testing.
Testing Procedure:
When you test the model, you're iterating through test_texts and printing entities found by the model. If no output appears, it means that doc.ents is empty for those test documents, implying that the model did not recognize any entities.
Here is a modified version of your testing code that will provide output whether or not entities are found, which might help in debugging:
python
# Load the trained model and test it
nlp2 = spacy.load("trained_model")
test_texts = [
"We need 50 units of product 7380-2-4x55 for our next project.",
"Can you provide a quote for 14583-4-2,5x8?",
"Please ship 20 units of item 7380-2-4x55 ASAP"
]
for text in test_texts:
doc = nlp2(text)
if doc.ents:
for ent in doc.ents:
print(f"Entity found: {ent.text}, Label: {ent.label_}")
else:
print(f"No entities found in: {text}")
User
The text "Please ship 20 units of item 7380-2-4x55 ASAP" is one to one got from the training data.
The training data is a csv file with the folloing content:
text,article_start,article_end,article_number
Please ship 20 units of item 7380-2-4x55 ASAP,29,40,7380-2-4x55
"Invoice for items listed: 10x 14583-4-2,5x8 required",30,43,"14583-4-2,5x8"
XYZxyzg hat die beste Camera für Selfies,22,28,Camera
Assistant
It's clear from your training data that the article_start and article_end columns are meant to denote the start and end positions of the article_number entity within the text. However, there appears to be a discrepancy in the end indices provided in your samples. Indices in Python are zero-based and the end index is exclusive, so something might be off.
Here's the proper annotation for the first training sample based on zero-based indexing:
Text: "Please ship 20 units of item 7380-2-4x55 ASAP"
Entity text: "7380-2-4x55"
Start index should be 29 (starting from 0)
End index should be 41 (article_end should be one more than the actual end index since the ending index in Python slicing is exclusive)
Likewise for the second and the third, although the third example seems to be of a different entity type (presumably you only want to detect ARTICLE_NUMBER):
Text: "Invoice for items listed: 10x 14583-4-2,5x8 required"
Entity text: "14583-4-2,5x8"
Start index should be 30
End index should be 44
Also, it's worth noting that the comma within the article_number in the second example could potentially interfere with CSV parsing, so be sure it's properly enclosed in quotes, as you have done.
Given that the start and end indices seem incorrect in your initial CSV excerpt, the result will be that the model is trained with wrong annotations, which will in turn skew its predictions during inference time.
Correcting the article_end indices in your training data file should look like this:
code
text,article_start,article_end,article_number
Please ship 20 units of item 7380-2-4x55 ASAP,29,41,7380-2-4x55
"Invoice for items listed: 10x 14583-4-2,5x8 required",30,44,"14583-4-2,5x8"
XYZxyzg hat die beste Camera für Selfies,22,28,Camera
After making these corrections, you should retrain your model with the corrected annotations.
Here are the fixed lines from your code where you process and annotate the data for clarity:
python
# Process and annotate the data
for index, row in df.iterrows():
doc = nlp.make_doc(row["text"])
annotations = {"entities": [(int(row["article_start"]), int(row["article_end"]), "ARTICLE_NUMBER")]}
example = Example.from_dict(doc, annotations)
doc_bin.add(example.reference)
User
if i change the Start index to 29 and the End index to 41 from the first entry in the csv field i get an warning UserWarning: [W030] Some entities could not be aligned in the text "Please ship 20 units of item 7380-2-4x55 ASAP" with entities "[(29, 41, 'ARTICLE_NUMBER')]".
Assistant
The warning indicates a misalignment between the text and the specified entity span, meaning the character indices referenced in your entity span (29, 41, 'ARTICLE_NUMBER') do not align with the actual entity in your text.
Given the text "Please ship 20 units of item 7380-2-4x55 ASAP" and its corresponding indices, let's check the entity annotation once more to see where the misalignment could be happening:
The entity "7380-2-4x55" starts at index 29, which is directly after the whitespace following the word "item". The entity ends at the last digit 5, which should be at index 40 considering zero-based indexing in Python. That means your entity span should technically be (29, 40, 'ARTICLE_NUMBER'), not (29, 41, 'ARTICLE_NUMBER').
Let's correct this in the CSV so that the entity span matches exactly the start and end positions of the entity within the text:
code
text,article_start,article_end,article_number
Please ship 20 units of item 7380-2-4x55 ASAP,29,40,7380-2-4x55
"Invoice for items listed: 10x 14583-4-2,5x8 required",30,43,"14583-4-2,5x8"
XYZxyzg hat die beste Camera für Selfies,22,28,Camera
Also, ensure there are no leading or trailing whitespaces around the indices in the CSV file, as they can cause issues with the parsing of integer values and ultimately how the spans are calculated.
After making the correction to your CSV file, retrain your model with the updated annotations. Make sure to verify that each entity span correctly matches the substring in the text from the article_start to the article_end. Keep in mind that the start index is inclusive and the end index is exclusive when represented as Python's string slicing (text[start:end]).
Once you have retrained the model with the corrected entity spans, you should not see the misalignment warning, and the model should begin to identify the ARTICLE_NUMBER entities when testing.
User
Yes with the corrected alignment i dont get the warning anymore but i still get the message "No entities found in: Please ship 20 units of item 7380-2-4x55 ASAP" with your provided code to test.
Load the trained model and test it
nlp2 = spacy.load("trained_model")
test_texts = [
"We need 50 units of product 7380-2-4x55 for our next project.",
"Can you provide a quote for 14583-4-2,5x8?",
"Please ship 20 units of item 7380-2-4x55 ASAP"
]
for text in test_texts:
doc = nlp2(text)
if doc.ents:
for ent in doc.ents:
print(f"Entity found: {ent.text}, Label: {ent.label_}")
else:
print(f"No entities found in: {text}")
Assistant
Given that the entity alignment issues have been corrected and assuming no other errors have been made, there are a few reasons you still might not be seeing any entities recognized:
Insufficient Training Data: If the corrected alignment was the only one in your training data, your model may be underfitting due to an insufficient quantity and variety of examples.
Model Generalization: The model might not be generalizing well beyond the specific examples it was trained on. To improve generalization, you would need a larger and more diverse training dataset that captures the variability of ARTICLE_NUMBER entities.
Hyperparameter Tuning: The default hyperparameters might not be suitable for your classification task. Different learning rates, number of iterations, dropout rates, and batch sizes can significantly affect performance.
Model Configuration: It's possible that there's an issue with the configuration of your model upon saving or loading it. Try testing the model in the same script where you train it, right after training, without saving and loading, to ensure the trained model works as expected before serialization.
Pipeline Configuration: Ensure that the "ner" pipeline component is present, and the model's architecture is consistent with what was trained. You might want to check this using nlp2.pipe_names and nlp2.get_pipe("ner").labels.
Dataset Format: Ensure the text in your test set is formatted, tokenized, and punctuated similarly to your training data.
To test the actual pipeline, you can use the following code in your training script right after the training process to see if it can predict something immediately after it was trained (this will eliminate serialization/deserialization as potential factors):
python
for text in test_texts:
doc = nlp(text) # Note that we're using the same `nlp` object used for training
if doc.ents:
for ent in doc.ents:
print(f"Entity found: {ent.text}, Label: {ent.label_}")
else:
print(f"No entities found in: {text}")
If the same code snippet produces the expected output immediately after training, there may be an issue with how the model is being saved or loaded.
: Make sure that during training, the losses are decreasing and the model is learning. If the losses aren't going down, it might indicate a problem with the training loop or data.
User
should work as the text from training data is the same as in the test data.
same as 1
i've tested the model right after the training using doc = nlp(text) but still get "No entities found in: Please ship 20 units of item 7380-2-4x55 ASAP"
i've checked the output of lp2.pipe_names and nlp2.get_pipe("ner").labels and get the folloing:
['ner']
('ARTICLE_NUMBER',)
Assistant
The fact that you're testing with the exact text from the training data, and still not getting the expected output even right after training, suggests that the model is not learning from the provided examples. Since we've ruled out serialization and deserialization issues, let's consider some other possible reasons:
Training Data Preparation: The way the Example objects are created from the training data could be incorrect.
Learning Rate: The learning rate in the optimizer might not be suitable – either too high (causing the model to skip over solutions) or too low (not making enough progress).
Random Initialization: The weights of the neural network are usually initialized randomly, which means that sometimes they might just get unlucky and not manage to learn. You could try reinitializing and retraining the model to see if the results improve.
Version Compatibility: Ensure that you are using the same spaCy version for both training and inference, as there can sometimes be compatibility issues between different versions.
Model Capacity: The default blank model may be too simple to capture the complexity of the task. Try using a more complex model as a starting point, such as en_core_web_sm.
Here's an additional strategy for debugging:
After training for each epoch, use the nlp.evaluate function with a few Example objects from training data to see the scores directly after training. If the scores are very low, this indicates that training isn't happening correctly.
Here's a rough example of how to perform evaluation after each epoch:
python
from spacy.scorer import Scorer
for itn in range(10): # Number of training iterations
# Your training loop code...
print(f"Iteration {itn}, Losses: {losses}")
# Evaluation
scorer = Scorer()
for text, annotations in train_data:
doc = nlp.make_doc(text)
example = Example.from_dict(doc, annotations)
scorer.score(example)
# Print score for each epoch
print(f"Scores at iteration {itn}: {scorer.scores}")
You should adapt the code for your training loop and how you've formatted your training data. If you consistently get low scores when doing this, it's clear the model isn't learning effectively.
User
what if i get the message "TypeError: 'DocBin' object is not iterable"?
Assistant
The error message "TypeError: 'DocBin' object is not iterable" indicates that there's an attempt to iterate over a DocBin object, but DocBin objects themselves are not directly iterable.
The code you posted earlier reads the DocBin from disk like this:
python
train_data = DocBin().from_disk("train.spacy")
And then iterates over the Doc objects it contains:
python
train_docs = list(train_data.get_docs(nlp.vocab))
However, the TypeError suggests that at some point in your code, you are trying to iterate over train_data directly instead of using train_data.get_docs(nlp.vocab). This might happen if you're using for text, annotations in train_data: somewhere, for example.
To solve the issue, confirm that anywhere you want to iterate over the documents in your DocBin, you are doing so correctly:
python
# Correct way to iterate over Docs in DocBin
train_docs = list(train_data.get_docs(nlp.vocab))
for doc in train_docs:
# Your processing code here
If you're trying to retrieve the texts and annotations used for training for evaluation purposes, you must ensure you use the Doc objects you've retrieved from the DocBin using get_docs.
Remember that DocBin provides storage for Doc objects, typically for the purpose of saving them to file or loading them from file, and DocBin.get_docs yields Doc objects when iterated over, which is what you should iterate through to access the original documents and their annotations.
Make sure that you haven't accidentally replaced the call to train_data.get_docs(nlp.vocab) with something else that is causing the error. If you're using some kind of evaluation loop where you need both texts and annotations, you will need to have stored or generated that information someplace else, as DocBin will only yield the Doc objects themselves, not the original text-annotation pairs.
If you provide the full context or the code snippet where the error occurs, I could give more specific advice on resolving the issue.
User
ok, if you look at the following code, what is the problem with the train_data in the score output?
import spacy
from spacy.tokens import DocBin
from spacy.training import Example
from spacy.util import minibatch, compounding
from spacy.scorer import Scorer
import spacy.symbols as syms
import pandas as pd
import random
import re
import en_core_web_sm
Load a blank English model
nlp = spacy.blank("en")
Get the current infix patterns
infixes = nlp.Defaults.infixes
Remove patterns that split on commas and hyphens
infixes = [pattern for pattern in infixes if pattern not in [r'(?<=[0-9])[.,]', r'(?<=[0-9])[-,]']]
Create a new infix regex using the revised patterns
if "ner" not in nlp.pipe_names:
ner = nlp.add_pipe("ner", last=True)
else:
ner = nlp.get_pipe("ner")
Add the new entity label to the NER component
ner.add_label("ARTICLE_NUMBER")
Read the training data from a CSV file into a Pandas DataFrame
df = pd.read_csv("training_data_articles.csv")
Create a DocBin object for efficiently storing spaCy Docs
doc_bin = DocBin(attrs=["ENT_IOB", "ENT_TYPE"])
Process and annotate the data
for index, row in df.iterrows():
doc = nlp.make_doc(row["text"])
annotations = {"entities": [(int(row["article_start"]), int(row["article_end"]), "ARTICLE_NUMBER")]}
example = Example.from_dict(doc, annotations)
doc_bin.add(example.reference)
Save the DocBin to disk
doc_bin.to_disk("train.spacy")
Load the training data saved as DocBin
train_data = DocBin().from_disk("train.spacy")
Get the Doc objects in the training data
train_docs = list(train_data.get_docs(nlp.vocab))
Initialize the model with random weights
nlp.begin_training()
Training the NER model
Disable other pipes during training
with nlp.disable_pipes(*[pipe for pipe in nlp.pipe_names if pipe != "ner"]):
optimizer = nlp.resume_training()
for itn in range(10): # Number of training iterations
random.shuffle(train_docs)
losses = {}
batches = minibatch(train_docs, size=compounding(4., 32., 1.001))
for batch in batches:
examples = [Example.from_dict(doc, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]}) for doc in batch]
nlp.update(
examples,
drop=0.5, # Dropout rate
losses=losses,
sgd=optimizer
)
print(f"Iteration {itn}, Losses: {losses}")
code
Assistant
The issue in the code is in the evaluation section during the training loop:
python
# Evaluation
scorer = Scorer()
for text, annotations in train_data:
doc = nlp.make_doc(text)
example = Example.from_dict(doc, annotations)
scorer.score(example)
The variable train_data is a DocBin object and is not directly iterable as mentioned in the "TypeError: 'DocBin' object is not iterable" error description.
Instead, you should iterate over the documents obtained from get_docs(nlp.vocab) which is done previously in the code with train_docs = list(train_data.get_docs(nlp.vocab)). Each Doc object returned by get_docs can be used directly to create an Example for scoring.
Here's how to fix the code:
Replace the following:
python
for text, annotations in train_data:
doc = nlp.make_doc(text)
example = Example.from_dict(doc, annotations)
scorer.score(example)
With the correct iteration code using train_docs that contains Doc objects from train_data:
python
# Evaluation
scorer = Scorer()
examples = []
for doc in train_docs:
examples.append(Example.from_dict(doc, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]}))
scorer.score(examples)
Make sure that the examples generated for scoring in the evaluation match the format expected by scorer.score(); it requires a list of Example objects.
Therefore, the revised training loop with the correct evaluation code should look like this:
The scorer.score function returns a dictionary of scores that evaluate different aspects of the model's performance. These scores reflect how well the model is predicting the annotations compared to the gold-standard annotations provided. Here's what the keys mean:
token_acc: Token accuracy. The percentage of tokens where the predicted token is exactly the same as the gold token.
token_p: Token precision. The percentage of tokens in the predicted output that are also present in the gold-standard output.
token_r: Token recall. The percentage of tokens in the gold-standard output that are also present in the predicted output.
token_f: Token F1 score. The harmonic mean of precision and recall for tokens.
The above scores measure token-based predictions, which may include settings where token classification (like part-of-speech tagging) is relevant. However, for NER, you'll focus on the entity recognition-related scores:
ents_p: Precision for entity recognition. The proportion of predicted entities that were correct.
ents_r: Recall for entity recognition. The proportion of actual entities that were correctly predicted by the model.
ents_f: F1 score for entity recognition. The harmonic mean of precision and recall for entity recognition, giving an overall accuracy score.
There's also ents_per_type, which gives precision (p), recall (r), and F1 score (f) for each entity type:
ents_per_type: A detailed breakdown of precision, recall, and F1 score for each entity type present in the data.
In your case, since you're dealing with NER, the most relevant scores are ents_p, ents_r, ents_f, and the scores within the ents_per_type dictionary, which shows the performance exclusively for the ARTICLE_NUMBER entity type.
According to the score you provided, you have the following values:
ents_p: 1.0 (100% precision, meaning all entities that the model predicts are correct)
ents_r: 1.0 (100% recall, meaning the model is capturing all the correct entities from the gold-standard data)
ents_f: 1.0 (100% F1 score, reflecting the balanced high precision and high recall)
However, these perfect scores are quite uncommon in practice, especially on unseen data or datasets with variability. It's important to ensure that the dataset used for evaluation is separate from the training data and is representative of the type of text the model will encounter in production. It might be the case that your evaluation ran on the same data the model was trained on, leading to overly optimistic results.
User
So if the score is a perfect score the test with some content from the training data should give a result?
Assistant
In theory, yes. If your model is receiving perfect evaluation scores on the training data, and you're testing it with text directly from that training data, you should expect it to predict the same entities with high confidence.
However, perfect scores can sometimes be misleading for several reasons:
Overfitting: If the model is overfitting the training data, it means that it has learned to predict that data almost perfectly but may not generalize well to new, unseen data. Overfitting can occur due to having too much complexity in the model compared to the amount and variety of training data.
Data Leaks: Sometimes, the test data can accidentally be included in the training data. This is known as a data leak and leads to unrealistically high scores because the model is effectively being tested on data it has already seen.
Evaluation Mistake: There might be a mistake in the code where the evaluation metrics are calculated. For example, if the example objects used in evaluation are not set up correctly, it could lead to incorrect perfect scores.
Identical Training and Test Set: If you are using the same text for training and evaluation, perfect scores are expected on that specific text. However, it doesn't mean the model has learned to generalize.
Given the concern you've raised—that a text from the training data used for testing doesn't yield any recognized entities—there may be an error somewhere in the training or testing process that's not immediately apparent.
Here's what you can do to further diagnose the problem:
Re-evaluate the training and evaluation processes to ensure there are no mix-ups in the data or how the Example objects are created.
Double-check the code used to run the model for inference (testing) to make sure it matches how you are running the model for training and evaluation.
Consider evaluating your model on a completely separate validation set. If the scores remain perfect, that's a strong indication of an error in the evaluation setup.
Introduce basic print statements to verify the data you're using at each step of the testing process. For example, print out the text and the ents predicted by the model right after you call nlp(text) during testing.
Remember, perfect scores are highly unusual in machine learning, especially on real-world data or tasks with any significant complexity. Always scrutinize such results for potential errors or overfitting.
User
Ok, if i try to use en_core_web_sm as mentioned before, how do i extend the training data with my csv file?
Assistant
When extending an existing spaCy model like en_core_web_sm with additional training data (e.g., for new entity types), you should approach it similarly to training a new model but also take into consideration that the model already has learned weights. Here's how you can do it:
Load the pre-trained model:
Instead of starting with a blank English model (spacy.blank("en")), you load the pre-trained model.
python
import spacy
# Load the pre-trained English model
nlp = spacy.load("en_core_web_sm")
# Reminder: If you haven't downloaded the model before, run `python -m spacy download en_core_web_sm` in your terminal.
Add the new entity label to the NER pipeline:
Since your new data includes the entity label ARTICLE_NUMBER, which is not part of the pre-trained model, you need to add this new label to the existing NER pipeline.
python
# Add the new entity label to the NER component
ner = nlp.get_pipe("ner")
ner.add_label("ARTICLE_NUMBER")
Create the training data:
Your training data creation process remains the same. You read the data from the CSV file, create Doc objects, annotate them with the entity spans, and store them in a DocBin object.
Train the model with the new data:
With the pre-trained model loaded, when you call nlp.begin_training(), spaCy will initialize the new entity label with random weights, but retain the pre-existing weights for the other entity types.
python
# Disable other pipes to train only NER
with nlp.disable_pipes(*[pipe for pipe in nlp.pipe_names if pipe != "ner"]):
optimizer = nlp.resume_training()
for itn in range(10): # Number of training iterations
random.shuffle(train_docs)
losses = {}
# Your training batch logic and nlp.update() calls
User
i get the error Can't find table(s) lexeme_norm for language 'en' in spacy-lookups-data. Make sure you have the package installed or provide your own lookup tables if no default lookups are available for your language.
Assistant
The error message you're seeing indicates that the model is expecting to find lookup tables containing normalization data, but they are not present. The spacy-lookups-data package provides various lookup tables and lists, like lemmatization data and normalization tables, for different languages.
To resolve the issue, you can install the package spacy-lookups-data by running the following command in your terminal or command prompt:
bash
pip install spacy-lookups-data
This package is an optional spaCy dependency that includes additional data and can be helpful especially for languages for which no statistical model like en_core_web_sm is available. However, for the English language, the en_core_web_sm model should include lexeme normalization data as part of its pipeline components.
If you're encountering this error, it may be due to one of the following reasons:
Outdated spaCy or Model Version: Make sure you are using compatible versions of spaCy and en_core_web_sm. You may need to update spaCy and its models to ensure compatibility.
Corrupted Model Installation: The model files might be corrupted or not properly installed. Try reinstalling the model with:
bash
python -m spacy download en_core_web_sm
Custom Configuration: If you're using a custom nlp configuration that requires the lookup tables, make sure the package is installed or adjust your configuration accordingly.
After installing spacy-lookups-data, if you're still encountering issues, try the following:
Verify your installation and spaCy's version with pip show spacy and ensure that it's up-to-date.
Validate that the en_core_web_sm model is properly installed with the command python -m spacy validate.
If problems persist, uninstall both spaCy and the English model (pip uninstall spacy and pip uninstall en_core_web_sm), and then reinstall them to ensure a clean setup.
Installing spacy-lookups-data should solve the problem, but if it doesn't, the issue might be more complex, and checking these other areas will help narrow down the cause.
User
ok, now everything is updated i get the following warnings:
/home/user/anaconda3/lib/python3.11/site-packages/spacy/pipeline/attributeruler.py:150: UserWarning: [W036] The component 'matcher' does not have any patterns defined.
matches = self.matcher(doc, allow_missing=True, as_spans=False)
/home/user/anaconda3/lib/python3.11/site-packages/spacy/pipeline/lemmatizer.py:211: UserWarning: [W108] The rule-based lemmatizer did not find POS annotation for one or more tokens. Check that your pipeline includes components that assign token.pos, typically 'tagger'+'attribute_ruler' or 'morphologizer'.
warnings.warn(Warnings.W108)
Assistant
These warnings are informing you about two potential issues in your NLP pipeline that might affect your results if not addressed properly:
AttributeRuler Warning ([W036]): This warning suggests that the AttributeRuler component is trying to match patterns in your documents, but no patterns are defined. If your workflow doesn't rely on pattern matching, you may remove the AttributeRuler component or ignore this warning. However, AttributeRuler is a component that comes with pre-trained pipelines, and it's responsible for setting attributes based on patterns. It's likely there's a misconfiguration during model initialization.
Lemmatizer Warning ([W108]): This warning indicates that the rule-based lemmatizer expects POS (part of speech) tags to be assigned to tokens, but those tags were not found for one or more tokens. The lemmatization phase of the pipeline relies on the POS tags to correctly determine the base form of words (lemmas). You should ensure that your pipeline includes components that assign token.pos, such as tagger and attribute_ruler, before the lemmatizer is run.
The typical pipeline for a model like en_core_web_sm includes the following components in order: tagger, parser, attribute_ruler, lemmatizer, and ner. The attribute_ruler is typically configured with the model and only needs user configuration if you're specifying custom rules. Similarly, the tagger should automatically add POS tags to tokens and thus should precede the lemmatizer.
To handle these warnings, you may want to inspect and potentially reconfigure your pipeline after loading the en_core_web_sm model and before training. Here's an example of how you could configure your pipeline to include the necessary components:
python
User
ok, now i've updated my code like this:
import spacy
from spacy.tokens import DocBin
from spacy.training import Example
from spacy.util import minibatch, compounding
from spacy.scorer import Scorer
import spacy.symbols as syms
import pandas as pd
import random
import re
import en_core_web_sm
Load English model to extend
nlp = spacy.load("en_core_web_sm")
Check the current pipeline components
print("Before modification:", nlp.pipe_names)
If the ‘tagger’ is not in the pipeline, add it (it is normally included in ‘en_core_web_sm’)
if "tagger" not in nlp.pipe_names:
nlp.add_pipe("tagger", before="lemmatizer")
If the ‘attribute_ruler’ or ‘lemmatizer’ are causing issues and you don’t need them, you can remove them:
if "ner" not in nlp.pipe_names:
ner = nlp.add_pipe("ner", last=True)
else:
ner = nlp.get_pipe("ner")
Add the new entity label to the NER component
ner.add_label("ARTICLE_NUMBER")
Check the updated pipeline components
print("After modification:", nlp.pipe_names)
Read the training data from a CSV file into a Pandas DataFrame
df = pd.read_csv("training_data_articles.csv")
Create a DocBin object for efficiently storing spaCy Docs
doc_bin = DocBin(attrs=["ENT_IOB", "ENT_TYPE"])
Process and annotate the data
for index, row in df.iterrows():
doc = nlp.make_doc(row["text"])
annotations = {"entities": [(int(row["article_start"]), int(row["article_end"]), "ARTICLE_NUMBER")]}
example = Example.from_dict(doc, annotations)
doc_bin.add(example.reference)
Save the DocBin to disk
Assistant
Seeing that only the first part of the article number is being recognized as an entity, and as an incorrect entity type (ORG) at that, suggests that the pre-trained model's existing entity recognition patterns may be interfering with your new ARTICLE_NUMBER entity. This kind of issue is known as "catastrophic forgetting" and occurs when the model forgets the previously learned entities due to new training data introducing different patterns. Here's how we can attempt to solve it:
Revise Your Entity Definitions: Make sure that your new entity doesn’t overlap with entities that the pre-trained model has been trained to recognize. The ORG label might be getting assigned because the model previously learned to recognize numbers followed by dashes as part of an organization's name. Since you're introducing a new type of entity that includes similar patterns, there's a conflict.
Update Training Data Format: Ensure that your training data includes the correct annotations and that they're formatted in a way that spaCy expects.
Prevent Catastrophic Forgetting: To address catastrophic forgetting, consider using the following techniques:
Include Existing Entities in Training: Alongside your new training data for ARTICLE_NUMBER, include examples of the existing pre-trained entities ORG, PERSON, etc. This can be achieved by mixing a sample of the original training data for en_core_web_sm with your new data.
Use a Component That Has Been Trained on the Updated Data: If you find that the ORG predictions are interfering too much, you might consider excluding ORG (if it's not relevant to your use case) from predicted entities for the time being:
python
ner = nlp.get_pipe("ner")
ner.add_label("ARTICLE_NUMBER")
for label in ner.labels:
if label not in ["ARTICLE_NUMBER"]: # Exclude all other labels
ner.add_label(label)
EntityRuler: Use an EntityRuler to add patterns that will identify ARTICLE_NUMBER instances, which can help improve the model's predictions.
EntityRuler to Create New Patterns: EntityRuler is a spaCy component that uses token-based patterns to find and label entities in text. It can be especially helpful in cases where entities follow a discernible structure.
User
i get UserWarning: [W036] The component 'entity_ruler' does not have any patterns defined.
Assistant
The warning [W036] The component 'entity_ruler' does not have any patterns defined indicates that the EntityRuler has been added to the spaCy pipeline, but no patterns have been defined for it to match.
The EntityRuler is an additional component in spaCy that can be used to match entities based on pattern rules you define. These patterns can be simple token strings or more complex token attributes, and they’re especially useful for recognizing entities that follow a predictable structure (like phone numbers, product codes, etc.).
Here’s how you can define and add patterns to the EntityRuler:
Define the patterns list. Each pattern is a dictionary representing one rule to match an entity.
Add the EntityRuler to the pipeline if it's not already there.
Load the patterns into the EntityRuler using entity_ruler.add_patterns(patterns).
Here's an example, assuming that article numbers are of the form of dddd-dd-dxdd:
python
patterns = [
{"label": "ARTICLE_NUMBER", "pattern": [{"SHAPE": "dddd"}, {"IS_PUNCT": True, "OP": "?"}, {"SHAPE": "dd"}, {"IS_PUNCT": True, "OP": "?"}, {"SHAPE": "d"}, {"SHAPE": "x"}, {"SHAPE": "dd"}]}
]
# Check if EntityRuler exists and add the patterns
if 'entity_ruler' not in nlp.pipe_names:
entity_ruler = nlp.add_pipe('entity_ruler')
entity_ruler.add_patterns(patterns)
The pattern above is an example, and you would need to adjust it to fit the actual shapes and separators of the article numbers you’re working with. The SHAPE attribute corresponds to the shape of the token where d represents any digit, and IS_PUNCT checks if the token is a punctuation mark. The OP key specifies the operator, which can be ? (the token is optional), * (token can match 0 or multiple times), + (token must match once or more times), or ! (assertion that the token shouldn't be present).
After defining the patterns and loading them into the EntityRuler, make sure you save your model again. When you load the saved model, the EntityRuler will be restored along with the patterns.
Remember that spaCy's built-in linguistic features such as , , etc., are there to help with the pattern matching, but you might need to also use regex patterns for more complex entities. The availability of the properties depends on the spaCy version and the underlying model capabilities.
User
can you provide me a complete rewritten code?
Assistant
Certainly! Below is a revised version of your code with some changes. Remember to adjust the patterns to match the specific format of article numbers you're working with:
python
User
if i like to find quantities also in the text and return an json with found entries like {"order":[{"item":"7380-2-4x55", "quantity":50}]} what will i have to do?
Assistant
To find quantities alongside article numbers and return JSON data with this information, you'll need to approach it in several steps:
Modify the entity recognition to include a new label for quantities (e.g., QUANTITY).
Train the NER model to recognize QUANTITY entities, along with ARTICLE_NUMBER entities, in your texts.
After NER, create a function to extract the entities from the text and format them into the desired JSON structure.
Here's a broad outline of how the updated code might look:
Step 1: Add quantity patterns and label to the EntityRuler and NER.
python
patterns = [
{"label": "ARTICLE_NUMBER", "pattern": [{"SHAPE": "dddd"}, {"TEXT": "-"}, {"SHAPE": "d+"}, {"TEXT": "-"}, {"SHAPE": "d"}, {"TEXT": "x"}, {"SHAPE": "dd"}]},
# Define patterns for `QUANTITY`
{"label": "QUANTITY", "pattern": [{"LIKE_NUM": True}]},
# More patterns may be needed depending on the formats of your quantities.
]
Step 2: Annotate your training data to include QUANTITY entities where appropriate.
The CSV should now include quantity_start and quantity_end columns, similar to article number annotations.
Step 3: Extend the DocBin creation loop to include QUANTITY entities.
python
for index, row in df.iterrows():
doc = nlp.make_doc(row["text"])
annotations = {
"entities": [
(int(row["article_start"]), int(row["article_end"]), "ARTICLE_NUMBER"),
(int(row["quantity_start"]), int(row["quantity_end"]), "QUANTITY")
]
}
example = Example.from_dict(doc, annotations)
doc_bin.add(example.reference)
Step 4: Modify training and add the QUANTITY label.
python
ner.add_label("QUANTITY")
User
the pattern {“label”: “QUANTITY”, “pattern”: [{“LIKE_NUM”: True}]}, breaks the recognition of article numbers
Assistant
Including a pattern that matches every token that LIKE_NUM can indeed interfere with the more specific patterns you have for ARTICLE_NUMBER. The token matching for quantities in this generic form might result in any numeral being labeled as QUANTITY, which can be problematic if the numerals are part of ARTICLE_NUMBER.
Here's a revised approach:
Create more specific patterns for quantities, e.g., numbers followed by measurement units or other contextual clues that are typical in your data.
Remove the overly generic patterns and replace them with these more specific patterns.
Make use of the surrounding context to identify quantities, such as looking for words like "units" or "pieces" etc.
Use custom logic after entity recognition to resolve conflicts between QUANTITY and ARTICLE_NUMBER annotations. This could involve checking the proximity of entity annotations to each other and the context they appear in.
If a token can be either a part of an ARTICLE_NUMBER or a QUANTITY, prioritize the ARTICLE_NUMBER pattern. In the conflict resolution step, use custom rules to reassess whether a QUANTITY entity should be labeled differently.
As for the JSON generation function, it can remain mostly the same; you'll just need to fine-tune it based on the context in which quantity-related entities appear.
Here's a revised example of how you might implement a more context-aware rule for quantities and a custom logic for resolving entity labels:
Define patterns for EntityRuler with specific units or indicators for quantities:
python
patterns = [
# ... (Keep the patterns for ARTICLE_NUMBER)
# Examples of more specific patterns for QUANTITY, customize as needed
{"label": "QUANTITY", "pattern": [{"LIKE_NUM": True}, {"LOWER": {"IN": ["units", "pieces", "items", "boxes"]}}]},
]
Custom logic for resolving annotation conflicts:
python
def resolve_conflicts(ents):
# Your logic to resolve conflicts between QUANTITY and ARTICLE_NUMBER
# ...
return resolved_ents
# After applying NER and the EntityRuler
ents = resolve_conflicts(doc.ents)
User
ok, now i get Entity found: 20 units, Label: QUANTITY and an ValueError: invalid literal for int() with base 10: '20 units'.
How do i get only the 20 in the quantity?
Assistant
The error ValueError: invalid literal for int() with base 10: '20 units' is occurring because the function that generates the JSON is attempting to directly convert a string that contains both numbers and letters to an integer. In this case, the entity 20 units is captured as a whole by spaCy, and when your script tries int(quantity.text), it fails because int() expects a purely numerical string, not one that includes letters or other non-digit characters.
To extract only the numerical part of a QUANTITY entity, you can use regular expressions to find the digits within the string:
python
import re
def extract_numerical_quantity(text):
match = re.search(r'\d+', text)
if match:
return int(match.group())
return None
# Inside the generate_order_json function, use the extract_numerical_quantity function:
def generate_order_json(doc):
orders = []
quantities = [ent for ent in doc.ents if ent.label_ == "QUANTITY"]
articles = [ent for ent in doc.ents if ent.label_ == "ARTICLE_NUMBER"]
# naive approach: assumes that quantity and article number entities appear in order
for article, quantity in zip(articles, quantities):
# Use the new function to extract numerical values
quantity_number = extract_numerical_quantity(quantity.text)
if quantity_number is not None:
order = {"item": article.text, "quantity": quantity_number}
orders.append(order)
return {"order": orders}
What's happening in extract_numerical_quantity(): the function re.search(r'\d+', text) is finding the first occurrence of one or more digits (\d+) in the text and returning it as a match object. By calling .group() on this object, we get the actual string that was matched, which is then safely converted to an integer.
Note: Depending on the complexity of your text and the possible variety of your quantity expressions, you might have to use more advanced regex patterns that account for decimal numbers, thousands separators, units of measure, etc.
By applying this change, only the numerical part of the quantity should be captured and converted to an integer, preventing errors during JSON generation. It also ensures that even if spaCy's entity recognition is a bit overzealous (capturing more text than just the number), you can still extract the actual numerical quantity.
User
is there also a way to modify the pattern of the entity_ruler to find entries with pattern but only recognize the numerical part as quantity?
Assistant
Yes, the EntityRuler in spaCy allows for more nuanced pattern definitions, including the use of regex patterns. However, currently (as of version 3.x), the EntityRuler doesn't provide direct functionality to capture only a part of the matched pattern as an entity. The entire segment of text that matches a pattern is captured as the entity's text.
To match only numerical parts as QUANTITY, you can refine your patterns to be more selective and align more closely with how quantities are represented in your text, but you'll still capture the whole pattern, not just the number part.
Here's an example where patterns match specific phrases indicating quantities (this will still match the whole phrase, not just the number):
python
patterns = [
{"label": "QUANTITY", "pattern": [{"LIKE_NUM": True}, {"LOWER": "units"}]},
{"label": "QUANTITY", "pattern": [{"LIKE_NUM": True}, {"LOWER": "pieces"}]},
# etc. for other quantity-indicating terms
]
Following this, you would apply the post-processing step described in the previous answer to extract the numerical part.
However, if you're interested in directly capturing just the digits as part of the entity, you would need to consider using a custom processing component that employs regex or similar methods to process the text after the entity ruler has run. Here's an example of how you might do that:
python
from spacy.tokens import Span
import spacy
nlp = spacy.load("en_core_web_sm")
patterns = [
{"label": "QUANTITY_PATTERN", "pattern": [{"LIKE_NUM": True}, {"LOWER": "units"}]},
# Your original patterns here
]
entity_ruler = nlp.add_pipe("entity_ruler")
entity_ruler.add_patterns(patterns)
@nlp.component("quantity_extractor")
def quantity_extractor(doc):
new_ents = []
for ent in doc.ents:
if ent.label_ == "QUANTITY_PATTERN":
# Extract only the numerical part of the entity
match = re.search(r'\d+', ent.text)
if match:
start, end = match.span()
new_ent = Span(doc, ent.start + (start // len(doc[ent.start].text)), ent.start + (end // len(doc[ent.start].text)), label="QUANTITY")
new_ents.append(new_ent)
else:
new_ents.append(ent)
doc.ents = new_ents
return doc
# Add the custom component to the pipeline after the entity ruler
nlp.add_pipe("quantity_extractor", after="entity_ruler")
# Example usage
doc = nlp("Send me 5 units of product X.")
for ent in doc.ents:
print(ent.text, ent.label_)
User
what is wrong with the code
def generate_order_line_json(doc):
quantities = [ent for ent in doc.ents if ent.label_ == "QUANTITY"]
articles = [ent for ent in doc.ents if ent.label_ == "ARTICLE_NUMBER"]
order_line = {}
# naive approach: assumes that quantity and article number entities appear in order
for article, quantity in zip(articles, quantities):
quantity_number = extract_numerical_quantity(quantity.text)
if quantity_number is not None:
order_line = {"item": article.text, "quantity": quantity_number}
if quantity_number is None:
order_line = {"item": article.text, "quantity": 0}
print(order_line)
return order_line
if the quantity is none i get an empty object
Assistant
To ensure that your code captures all pairs of quantities and article numbers and properly returns an order line object even when there isn't a quantity found, you should make a few changes:
order_line should be a list of dictionaries since you're likely to deal with multiple order lines per document.
Handle the case where quantities may not align with articles in a one-to-one correspondence due to missing quantities or mismatches in the text.
Here's the revised function:
python
def generate_order_line_json(doc):
quantities = [ent for ent in doc.ents if ent.label_ == "QUANTITY"]
articles = [ent for ent in doc.ents if ent.label_ == "ARTICLE_NUMBER"]
order_lines = []
# Assume that the closest quantity to an article number is the correct pair
for article in articles:
# Find the nearest quantity to this article (naive approach)
closest_quantity = min(quantities, key=lambda q: abs(q.start - article.start), default=None)
if closest_quantity:
# Extract numbers only if QUANTITY is found
quantity_number = extract_numerical_quantity(closest_quantity.text)
else:
# Assign zero quantity if no QUANTITY is found
quantity_number = 0
# Create the order line JSON object
order_lines.append({"item": article.text, "quantity": quantity_number})
return order_lines
In this code:
order_lines is now a list that contains dictionaries for each article number found.
For each article, the code finds the closest QUANTITY entity. It uses the min() function along with a key argument, which computes the difference between the start indices of the quantity entities and article number. This is based on the assumption that the relevant quantity is near the article number text in the document.
User
Yes, that is a nice approach but i wanted to know why the returned order_line in my code returns an empty object if quantity is None
Assistant
The issue in your original function arises because it only sets order_line once for each pair of article and quantity. If the last iteration in the zip loop encounters a None quantity, it will set order_line to contain an item but a quantity of 0. However, if there are no quantities at all (meaning quantities is an empty list), the loop doesn't run, and you end up with an empty order_line object.
Furthermore, since order_line is a single dictionary that is being overwritten on each iteration, you're only keeping the most recent article and quantity pair. If there are multiple articles and quantities, you will only end up with the last pair in your JSON object.
To fix this issue, you should aggregate all item-quantity pairs into a list instead of a single dictionary object, and you need to account for the situations where quantities is empty or there are more articles than quantities. Here's the modified code, similar to what I provided in the previous answer, using a list instead:
python
def generate_order_line_json(doc):
quantities = [ent for ent in doc.ents if ent.label_ == "QUANTITY"]
articles = [ent for ent in doc.ents if ent.label_ == "ARTICLE_NUMBER"]
order_lines = [] # Use a list to hold all order line dictionaries
# Assuming that each ARTICLE_NUMBER must have a QUANTITY paired with it
for article in articles:
quantity_number = 0 # Default quantity
if quantities:
# Indexes for text spans are calculated relative to the start of the document
# Therefore, it's safe to use the index to extract quantity entities
closest_quantity = min(quantities, key=lambda q: abs(q.start - article.start), default=None)
if closest_quantity:
quantity_number = extract_numerical_quantity(closest_quantity.text)
quantities.remove(closest_quantity) # Remove the used quantity to avoid reusing it
order_lines.append({"item": article.text, "quantity": quantity_number})
return order_lines # Return a list of dictionaries
# Helper function to extract only numeric part of the quantity
def extract_numerical_quantity(text):
match = re.search(r'\d+', text)
return int(match.group()) if match else None
User
but i need a function that only returns the current line not all lines
Assistant
Ah, I see. If you only need to return a dictionary for the current line pair of article and quantity, then your original function could be modified slightly to ensure that the order_line entry is returned correctly even when no quantity is found.
Here's how you can adjust your function:
python
def generate_order_line_json(doc):
quantities = [ent for ent in doc.ents if ent.label_ == "QUANTITY"]
articles = [ent for ent in doc.ents if ent.label_ == "ARTICLE_NUMBER"]
order_lines = [] # This will still collect all the lines to return the current one
# This will pair each article with a quantity. If the quantity is None, it will pair it with quantity 0
# It assumes that for every article, there is a matching quantity
for article in articles:
quantity_number = 0 # Default quantity
for quantity in quantities:
# Check if quantity entity follows article entity closely in the text
# Assuming the quantity should be right before the article number
if quantity.end == article.start:
quantity_number = extract_numerical_quantity(quantity.text)
break # Stop looking for quantities once we find a match
order_lines.append({"item": article.text, "quantity": quantity_number})
# Assuming you want to return the last line matched, or None if no matching occurred
return order_lines[-1] if order_lines else None
# Helper function to extract only numeric part of the quantity
def extract_numerical_quantity(text):
match = re.search(r'\d+', text)
return int(match.group()) if match else 0 # Return 0 if no numbers are found
Assistant
It seems like your last message might have been sent by accident without any content. If you have any additional questions or need further clarification on the previous solution, please don't hesitate to let me know. I'm here to help!
User
Lets try something other
Assistant
Certainly! If you're looking for assistance with a different topic or have a new question, feel free to ask. I'm here to help with any information or guidance you might need.
User
Is there a way to train a system with incoming email texts and final resulting json to get a valid model?
Assistant
Yes, you can train a machine learning model on incoming email texts and their associated JSON outputs if you have a dataset that pairs these emails with their corresponding structured information.
Here's a general approach to achieve this:
Data Collection and Annotation: Collect a dataset of emails and the resulting JSONs that you want the model to produce. If you don't already have annotated data, you'll need to manually annotate the emails, identifying the information to be extracted that corresponds to the JSON fields.
Data Preprocessing: Preprocess the texts to format them for training. This may include cleaning the text, tokenizing, and encoding the relevant parts of the emails that map to your target JSON.
Feature Engineering: Extract features from your email texts. This could mean using bag-of-words, TF-IDF, word embeddings (like Word2Vec or GloVe), or any other relevant features that could help with the prediction of JSON fields.
Model Selection: Choose a model architecture. Depending on your task, you might opt for a traditional machine learning model (like Random Forest or SVM), or a neural network model (like LSTM or Transformers for more complex dependencies).
Named Entity Recognition (NER): For information extraction where entities need to be identified (such as dates, product references, or quantities), you could use a tool like spaCy to train an NER model specifically to recognize these entities in the text.
Entity Linking: Where entities are found in the text, you need to determine the relationships between entities and structure this information to match the JSON format. This might require entity relation prediction, which is a more advanced NER task.
Training: Train your chosen model(s) on the preprocessed and feature-extracted dataset. Remember to use an appropriate validation strategy, such as k-fold cross-validation, to evaluate the performance of the model.
Model Evaluation: After training, evaluate the model's performance against a separate test set of annotated email and JSON pairs.
Pipeline Creation: For a complete solution, you may need to set up a pipeline process where the raw email text is preprocessed, entities are extracted, the relations between entities are identified, and then transformed into the desired JSON format.
Deployment: Once the model is trained and evaluated, deploy the model and integrate it with your email processing workflow to automatically generate JSONs from incoming emails.
User
does the code we've worked on help with this?
Assistant
Yes, the code we've discussed earlier can be part of this process, particularly for training a Named Entity Recognition (NER) system that can identify specific entities in the text of the emails.
Here's how the previous code can help:
Entity Recognition: The spaCy code with the EntityRuler and custom patterns can be used to recognize predefined entities in the email texts, such as product codes, quantities, and other relevant information.
Entity Relations: Although not covered in the code we have gone over, to develop a model that predicts JSON outputs from emails, you'll need to identify not just entities but also the relationships between them. The code can be adjusted to include entity relationship recognition if needed.
Data Annotation: The spaCy DocBin data structure and the Example objects used in the training script can help create an efficient annotation process, allowing you to turn raw emails and associated JSON data into training data for the NER model.
Model Training: The loop where you train the spaCy model and update it with batches of examples is essentially how you would train any other machine learning model, including those meant for structured prediction tasks.
To extend the use of this code to accomplish the full task of converting email text to JSON, you would typically follow these additional steps:
Upon recognizing all relevant entities, you'll need additional logic to construct the JSON structure based on these entities and their inferred relationships.
Depending on the complexity of the task, you may need to train a separate model or use rule-based logic to infer the relationships and proper ordering of entities to construct the JSON.
After NER, you would have a post-processing step where you take the entities identified by the NER model and arrange them into the structured JSON format you desire.
If you're working with complex, free-form text such as emails, you may need a more advanced approach, possibly involving sequence-to-sequence (seq2seq) neural network models, which are specifically designed for tasks that translate one form of data (e.g., text) into another (e.g., JSON).
For deep learning-based models, you might use a library like Hugging Face's Transformers and fine-tune a pre-trained model, such as T5 or BERT, on a seq2seq task to generate JSON from email content.
The provided code could serve as a building block in a larger system that includes these additional components. However, the overall system’s architecture and complexity would depend on the scale and scope of the information extraction and transformation task at hand.
This script will print a message for each text, even when no entities have been identified.
Steps to Troubleshoot:
Verify the structure and annotations in your training data CSV.
Evaluate the model on a held-out test set that's correctly annotated to estimate its performance quantitatively.
Experiment with the training hyperparameters and consider increasing the variety and volume of training data.
Check if after loading the model nlp2 has the 'ner' pipeline component with: print(nlp2.pipe_names) and print(nlp2.get_pipe("ner").labels) to ensure that "ARTICLE_NUMBER" is a recognized label.
By investigating these potential issues, you can begin to understand why the model isn't producing the expected output on your test data.
The error in indexing would have caused the training process to fail to correctly learn the ARTICLE_NUMBER entities.
After retraining with the corrected annotations, your testing code should work if you load the new model and your ARTICLE_NUMBER entities should be recognized in the example texts. Remember to ensure that your test examples reflect the same format as your training data.
Debugging the Training Process
Here's how you can debug your training process:
Check the losses after each epoch to ensure they are generally decreasing.
Evaluate your model on a development set (a separate set of annotated data) after each epoch to find out if the model is improving.
Review a few predictions by making inference on your training data to see if it's learning correctly.
Start by verifying the immediate post-training predictions and follow through with the above steps to isolate the issue.
Other debugging steps could include:
Checking if there are sufficient examples of the ARTICLE_NUMBER entity in different contexts.
Trying a small, controlled subset of the training data where you are sure entities are coded correctly, and using that to see if the model can overfit to a small dataset (which is usually a good sign that the model has the capacity to learn).
Revising the creation of your DocBin and ensuring that the examples are correctly added.
If none of these steps reveal the issue, it might be helpful to provide more details about the training data and the complete training script, so that I could give you more targeted advice.
# Evaluation
scorer = Scorer()
for text, annotations in train_data:
doc = nlp.make_doc(text)
example = Example.from_dict(doc, annotations)
scorer.score(example)
# Print score for each epoch
print(f"Scores at iteration {itn}: {scorer.scores}")
test_texts = [
"We need 50 units of product 7380-2-4x55 for our next project.",
"Can you provide a quote for 14583-4-2,5x8?",
"Please ship 20 units of item 7380-2-4x55 ASAP"
]
for text in test_texts:
doc = nlp(text)
if doc.ents:
for ent in doc.ents:
print(f"Entity found: {ent.text}, Label: {ent.label_}")
else:
print(f"No entities found in: {text}")
Save the trained model to disk
nlp.to_disk("trained_model")
# Training the NER model
# Disable other pipes during training
with nlp.disable_pipes(*[pipe for pipe in nlp.pipe_names if pipe != "ner"]):
optimizer = nlp.resume_training()
for itn in range(10): # Number of training iterations
random.shuffle(train_docs)
losses = {}
batches = minibatch(train_docs, size=compounding(4., 32., 1.001))
for batch in batches:
examples = [Example.from_dict(doc, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]}) for doc in batch]
nlp.update(
examples,
drop=0.5, # Dropout rate
losses=losses,
sgd=optimizer
)
print(f"Iteration {itn}, Losses: {losses}")
# Evaluation
scorer = Scorer()
examples = [] # List to store example objects
for doc in train_docs:
example = Example.from_dict(doc, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]})
examples.append(example)
scores = scorer.score(examples) # Pass the list of examples to scorer.score()
# Print score for each epoch
print(f"Scores at iteration {itn}: {scores}")
Lastly, make sure the entities in the train_docs are correctly annotated, as this will also affect the scoring. If they are not accurately annotated due to earlier preprocessing, the training won't be effective, and the scores will reflect that.
Scores for other aspects of NLP, like sentence boundary detection (sents_p, sents_r, sents_f), part-of-speech tagging (tag_acc), morphological tagging (morph_acc), and dependency parsing (dep_uas, dep_las), are None because your current nlp model pipeline either does not predict these annotations or this script is not calculating them. Since this model is focused on NER, it's expected that those values are not applicable.
For more robust performance evaluation, consider:
Using a validation set that the model has never seen during training.
Performing cross-validation if enough data is available.
Analyzing false positives and false negatives to understand where the model is making mistakes.
Test and save your updated model:
After training, test your model and, if satisfied with the performance, save the updated model as before.
python
# Save the updated model to disk
nlp.to_disk("updated_trained_model")
Note that extending a pre-trained model has a few caveats:
Catastrophic Forgetting: When updating a pre-trained model with new examples for new or existing categories, the model might forget its previous knowledge. To prevent this, mix in examples of the entities it was originally trained on along with the new examples, or perform more sophisticated training strategies, like using dropout and lower learning rates, and continuing from the pre-existing optimizer state.
Data balancing: Ensure that the new training data is well-balanced with respect to the existing entity types in the pre-trained model. If the new entity type dominates the training updates, you might skew the model's understanding of other entities.
Consistent tokenization: The tokenization of your additional training data should be consistent with the tokenization performed by the pre-trained model.
If you aim to improve the model's performance for a wide variety of texts or entity types, it's crucial to provide a diverse and representative set of training examples. This strategy improves the robustness of the NER component for both the original and new entity types.
import spacy
# Load the pre-trained English model
nlp = spacy.load("en_core_web_sm")
# Check the current pipeline components
print("Before modification:", nlp.pipe_names)
# If you're not using custom patterns and don't need the matcher,
# you can remove matcher/attribute_ruler or configure it with the necessary patterns
# If the 'tagger' is not in the pipeline, add it (it is normally included in 'en_core_web_sm')
if "tagger" not in nlp.pipe_names:
nlp.add_pipe("tagger", before="lemmatizer")
# If the 'attribute_ruler' or 'lemmatizer' are causing issues and you don't need them, you can remove them:
# nlp.remove_pipe("attribute_ruler")
# nlp.remove_pipe("lemmatizer")
# Check if 'ner' exists, if not, add it
if "ner" not in nlp.pipe_names:
ner = nlp.add_pipe("ner")
else:
ner = nlp.get_pipe("ner")
# Add your new label to 'ner'
ner.add_label("ARTICLE_NUMBER")
# Check the updated pipeline components
print("After modification:", nlp.pipe_names)
# ... Continue with training setup and training as before
You should ensure that the pipeline has all necessary components before you start training. If you're specifically training for NER, you may want to disable the non-essential components during the training to speed up the process and avoid the warnings related to them.
If you're not using particular components for your specific task, it is safe to disable or remove them from the pipeline, as long as you're aware of how it might affect the processing. If you're solely focused on Named Entity Recognition (NER), aspects like lemmatization might be less critical.
Always ensure that after modifying the pipeline, you check its components with nlp.pipe_names to confirm that all required components are properly configured.
with nlp.disable_pipes(*[pipe for pipe in nlp.pipe_names if pipe != "ner"]):
optimizer = nlp.resume_training()
for itn in range(1000): # Number of training iterations
random.shuffle(train_docs)
losses = {}
batches = minibatch(train_docs, size=compounding(4., 32., 1.001))
for batch in batches:
examples = [Example.from_dict(doc, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]}) for doc in batch]
nlp.update(
examples,
drop=0.5, # Dropout rate
losses=losses,
sgd=optimizer
)
if itn%100 == 0:
print(f"Iteration {itn}, Losses: {losses}")
test_texts = [
"We need 50 units of product 7380-2-4x55 for our next project.",
"Can you provide a quote for 14583-4-2,5x8?",
"Please ship 20 units of item 7380-2-4x55 ASAP"
]
for text in test_texts:
doc = nlp(text)
if doc.ents:
for ent in doc.ents:
print(f"Entity found: {ent.text}, Label: {ent.label_}")
else:
print(f"No entities found in: {text}")
Save the trained model to disk
nlp.to_disk("updated_trained_model")
And i like to find artikle numbers like "7380-2-4x55", "14583-4-2,5x8" or "7380-2-4x55"
but i only get
Entity found: 7380, Label: ORG
Entity found: 14583, Label: ORG
Entity found: 7380, Label: ORG
With the first part of the Article Number and the Label ORG
This approach includes creating token patterns that match the structure of article numbers. The pattern above assumes that article numbers have a specific shape: four digits, a hyphen, one or more digits, a hyphen, one or more digits, an 'x', followed by one or more digits. Adjust it according to your specific pattern requirements.
Retrain and Test: After adjusting your NER model and its training data, retrain your model and test the performance again.
To summarize, you need to balance your training data between your new ARTICLE_NUMBER entities and the existing entities to teach the model to recognize both correctly. It’s also helpful to add specific instructions using rules or patterns to help your model differentiate between similar-looking entities. Remember to mix in examples of existing entity types to maintain the knowledge the model has already acquired.
SHAPE
IS_PUNCT
You might also consider creating simpler patterns, such as {"label": "ARTICLE_NUMBER", "pattern": "7380-2-4x55"} or more complex regular expressions if needed.
Finally, don't forget to test your pattern matching with a few examples to ensure they are properly capturing the intended entities before retraining your model.
import spacy
from spacy.tokens import DocBin
from spacy.training import Example
from spacy.util import minibatch, compounding
import pandas as pd
import random
# Load the pre-trained English model
nlp = spacy.load("en_core_web_sm")
# Define patterns for the EntityRuler
patterns = [
{"label": "ARTICLE_NUMBER", "pattern": [{"SHAPE": "dddd"}, {"TEXT": "-"}, {"SHAPE": "d+"}, {"TEXT": "-"}, {"SHAPE": "d"}, {"TEXT": "x"}, {"SHAPE": "dd"}]}
# Add more patterns as needed
]
# Create the EntityRuler if it doesn't exist and add it before ner.
# You can skip adding the EntityRuler if you opt to only use the ner component with additional examples.
if "entity_ruler" not in nlp.pipe_names:
entity_ruler = nlp.add_pipe("entity_ruler", before="ner")
entity_ruler.add_patterns(patterns)
# Get the NER pipeline component
ner = nlp.get_pipe("ner")
# Add the new entity label to the NER
ner.add_label("ARTICLE_NUMBER")
# Read the training data from a CSV file into a Pandas DataFrame
df = pd.read_csv("training_data_articles.csv")
# Create a DocBin object for efficiently storing spaCy Docs
doc_bin = DocBin(attrs=["ENT_IOB", "ENT_TYPE"])
# Process and annotate the data
for index, row in df.iterrows():
doc = nlp.make_doc(row["text"])
annotations = {"entities": [(int(row["article_start"]), int(row["article_end"]), "ARTICLE_NUMBER")]}
example = Example.from_dict(doc, annotations)
doc_bin.add(example.reference)
# Save the DocBin to disk
doc_bin.to_disk("updated_train.spacy")
# Load the training data saved as DocBin
train_data = DocBin().from_disk("updated_train.spacy")
# Get the Doc objects in the training data
train_docs = list(train_data.get_docs(nlp.vocab))
# Disable other pipes during training to only train NER
with nlp.disable_pipes(*[pipe for pipe in nlp.pipe_names if pipe != "ner"]):
# Resume training
optimizer = nlp.create_optimizer()
# Training loop
for itn in range(1000): # Number of training iterations
random.shuffle(train_docs)
losses = {}
# Batch up the examples using spaCy's minibatch
batches = minibatch(train_docs, size=compounding(4., 32., 1.001))
for batch in batches:
examples = []
for doc in batch:
# Because there's no alignment necessary for new entity, we don't create Example.from_dict here
examples.append(Example.from_dict(doc, {"entities": [(ent.start_char, ent.end_char, ent.label_) for ent in doc.ents]}))
nlp.update(
examples,
drop=0.5, # Dropout - make it harder to memorise data
losses=losses,
sgd=optimizer
)
if itn % 100 == 0:
print(f"Iteration {itn}, Losses: {losses}")
# Test the trained model
test_texts = [
"We need 50 units of product 7380-2-4x55 for our next project.",
"Can you provide a quote for 14583-4-2,5x8?",
"Please ship 20 units of item 7380-2-4x55 ASAP"
]
for text in test_texts:
doc = nlp(text)
print(f"Entities in '{text}':")
for ent in doc.ents:
print(f" - Entity found: {ent.text}, Label: {ent.label_}")
# Save the trained model to disk
nlp.to_disk("updated_trained_model")
Some points to consider:
Make sure to properly adjust the SHAPE within the patterns based on the format of your article numbers.
Review whether you should use the EntityRuler (which is a rule-based entity extraction logic) or the statistical NER (ner), or both, in your pipeline. Rules in the EntityRuler may override predictions made by the ner. If using both, be sure the patterns don't conflict with the ner component's predictions.
Although the EntityRuler is added before ner in this script, you may choose to move it after ner if you want the ner component's predictions to take precedence.
The line optimizer = nlp.create_optimizer() creates a new optimizer. If you're continuing from trained weights, you might need to use resume_training() instead.
I removed the infix regex customization as it was not completed. If needed, you should finish this part to match your specific tokenization requirements.
Training is a time-consuming process and the number of iterations (itn) and batch sizes will greatly affect the model's quality. This is set to 1000 just as a placeholder. In practice, you will often need to adjust these hyperparameters.
The testing segment prints all entities. For a real application, you might want to limit this to ARTICLE_NUMBER entities, ignoring others.
Lastly, do not forget to test the model on a validation set and adjust the training as needed to avoid overfitting on the training data and to accurately represent the real-world performance of the model.
Above the steps, ensure that the training data includes both ARTICLE_NUMBER and QUANTITY entities.
Step 5: Extract the information and generate the JSON.
After training and processing texts, you can create a function to transform the detected entities into the desired JSON format:
python
def generate_order_json(doc):
orders = []
quantities = [ent for ent in doc.ents if ent.label_ == "QUANTITY"]
articles = [ent for ent in doc.ents if ent.label_ == "ARTICLE_NUMBER"]
# naive approach: assumes that quantity and article number entities appear in order
for article, quantity in zip(articles, quantities):
order = {"item": article.text, "quantity": int(quantity.text)}
orders.append(order)
return {"order": orders}
# Later in your processing code, after making a prediction with nlp(text):
doc = nlp(text)
order_json = generate_order_json(doc)
print(order_json)
A few important notes:
The above code for generate_order_json assumes a simple, 1:1 correlation between quantities and items in a linear sequence. In practice, entity relation extraction can be more complex, and you might have to implement a more sophisticated method of heuristics or pattern matching to pair quantities and items correctly.
The function generate_order_json naïvely casts the quantity text to an int, which might fail if the quantity has non-numeric characters or is not a whole number (use float() in that case, and handle exceptions).
It is crucial to ensure that the entities are annotated precisely in the training data for QUANTITY labels to be learned and recognized, just as with the ARTICLE_NUMBER labels.
Keep in mind that real text can be complex, and you may need a more nuanced approach to determine the relationship between quantities and items, particularly if they aren't presented in a consistent format. This might include dependency parsing to understand the grammatical structure of sentences and deduce which quantity refers to which item.
This custom function should elaborate on the specific logic needed to determine whether a recognized numeric entity should be labeled as QUANTITY or as part of an ARTICLE_NUMBER. It could also be the case that some LIKE_NUM tokens labeled as QUANTITY actually belong to ARTICLE_NUMBER and should be relabeled or merged with adjacent tokens.
Please adjust everything based on your specific rules and the typical structure of your dataset.
The overall idea is to train your model to recognize specific context-dependent quantity expressions, which shouldn't conflict with your article number entities. Then apply heuristics or rules on the recognized entities to decide whether a potential QUANTITY should really be considered as such, or if it's part of an ARTICLE_NUMBER. Remember that this kind of post-processing requires an understanding of the structure and nuances of your specific text data.
In the quantity_extractor component, we create a new component that searches for entities with the QUANTITY_PATTERN label and replaces them with a new span capturing only the digit part. The re.search() function is used to find the span of digits within the entity text, and match.span() provides the start and end indices of this numerical part.
Remember to add your custom component after the entity_ruler in the pipeline to ensure it processes the entities recognized by the entity_ruler.
This code is custom-made for your specific use case and assumes that a QUANTITY_PATTERN entity will be followed by the custom component to correctly set the QUANTITY entity as just the numerical part. Adjust parallelly to your use case.
If no quantity is found for an article number (i.e., closest_quantity is None), quantity_number is set to 0.
The order line JSON object for each article is appended to the order_lines list.
This approach assumes that quantities are near their corresponding article numbers. It's a simple heuristic that might not cover more complex cases, so you should fine-tune this depending on the actual structure of your data.
Also, note that this function now calls extract_numerical_quantity, so make sure you have defined this helper function in your script:
python
import re
def extract_numerical_quantity(text):
match = re.search(r'\d+', text)
if match:
return int(match.group())
return 0 # Return 0 if no numbers are found
The modified generate_order_line_json function now returns a list of dictionary objects each representing an 'order line', with zero quantity for articles where no quantity was specified.
This code processes each article individually, assigns a default quantity of 0, and tries to find the nearest quantity. After processing, each article-quantity pair is stored in a list named order_lines. This ensures that even if there is no quantity found, the article still gets added with a quantity of 0. It also ensures that every article is represented in the output JSON, even if the quantity is None. If there are fewer quantities than articles, the code handles that gracefully, ensuring that the result will always be a list with every article that was found in the input text.
Let's go through the changes:
quantities and articles lists are still computed at the start since you need to evaluate all detected entity spans and pair them accordingly.
The for loop creates order_lines, but if you only need the current line being processed (let's assume the "current" line is the last one in the text), you can return order_lines[-1], which accesses the last item added to the list; this will be the "current line."
In the helper function extract_numerical_quantity, a failure to find a number (match is None) will now return 0 instead of None to prevent int() conversion issues.
This function will now return a single dictionary representing the most recent (last) order line found in the document, or None if no items were found at all.
Finally, if you need the function to work with a specific article and quantity, you'd have to pass these in as arguments to the function. This would make more sense if your overall script is processing these entities line-by-line, such as in a loop or streaming context. This current version processes the entire doc to find all articles and quantities, returning the last one it finds. Adjust it as needed based on the definition of "current line" in your application context.
Feedback Loop: Implement a feedback system to allow for corrections to incorrect outputs. These corrections should be fed back into the training data to improve the model over time.
For this kind of system, you could use powerful NLP libraries like spaCy or Hugging Face’s Transformers to process and extract information from the text. More advanced solutions might employ sequence-to-sequence models (seq2seq), such as the Transformer models with architectures designed for generating structured outputs from unstructured text.
Implementing such a system can be quite complex and would likely need to be tailored to the specifics of your data, including the format of the emails and the structure of the target JSON. This often requires both machine learning expertise and domain expertise to ensure accuracy and effectiveness.