Notebooks
C
Cohere
Entity Extrcation With Generative Language Models

Entity Extrcation With Generative Language Models

guidesnotebookscohere-developer-experience

Entity Extraction with Generative Models

This notebook demonstrates how to use Cohere's generative models to extract the name of a film from the title of an article. This demonstrates Named Entity Recognition (NER) of entities which are harder to isolate using other NLP methods (and where pre-training provides the model with some context on these entities). This also demonstrates the broader usecase of sturctured generation based on providing multiple examples in the prompt.

Extracting Entities from text

We'll use post titles from the r/Movies subreddit. And for each title, we'll extract which movie the post is about. If the model is unable to detect the name of a movie being mentioned, it will return "none".

Setup

Let's start by installing the packages we need.

[ ]

We'll then import these packages and declare the function that retrieves post titles from reddit.

[ ]

You'll need your API key for this next cell. Sign up to Cohere and get one if you haven't yet.

[ ]

Preparing examples for the prompt

In our prompt, we'll present the model with examples for the type of output we're after. We basically get a set of subreddit article titles, and label them ourselves. The label here is the name of the movie mentioned in the title (and "none" if no movie is mentioned).

Labeled dataset of text and extracted text

[ ]

Creating the extraction prompt

We'll create a prompt that demonstrates the task to the model. The prompt contains the examples above, and then presents the input text and asks the model to extract the movie name.

Extraction prompt containing the examples and the input text

[ ]
[ ]
Deadpool 2 | Official HD Deadpool's "Wet on Wet" Teaser | 2018
extract the movie title from the post:Deadpool 2
---
Jordan Peele Just Became the First Black Writer-Director With a $100M Movie Debut
extract the movie title from the post:none
---
Joker Officially Rated “R”
extract the movie title from the post:Joker
---
Ryan Reynolds’ 'Free Guy' Receives July 3, 2020 Release Date - About a bank teller stuck in his routine that discovers he’s an NPC character in brutal open world game.
extract the movie title from the post:Free Guy
---
James Cameron congratulates Kevin Feige and Marvel!
extract the movie title from the post:none
---
The Cast of Guardians of the Galaxy release statement on James Gunn
extract the movie title from the post:Guardians of the Galaxy
---
<input text here>
extract the movie title from the post:

Getting the data

Let's now make the API call to get the top posts for 2021 from r/movies.

[ ]
['Hayao Miyazaki Got So Bored with Retirement He Started Directing Again ‘in Order to Live’',
, "First poster for Pixar's Luca",
, 'New images from Space Jam: A New Legacy',
, 'Official Poster for "Sonic the Hedgehog 2"',
, 'Ng Man Tat, legendary HK actor and frequent collborator of Stephen Chow (Shaolin Soccer, God of Gambler) died at 70',
, 'Zack Snyder’s Justice League has officially been Rated R for for violence and some language',
, 'HBOMax and Disney+ NEED to improve their apps if they want to compete with Netflix.',
, 'I want a sequel to Rat Race where John Cleese’s character dies and invites everyone from the first film to his funeral, BUT, he’s secretly set up a Rat Maze to trap them all in. A sort of post-mortem revenge on them for donating all his wealth to charity.',
, "'Trainspotting' at 25: How an Indie Film About Heroin Became a Feel-Good Classic",
, '‘Avatar: The Last Airbender’ Franchise To Expand With Launch Of Nickelodeon’s Avatar Studios, Animated Theatrical Film To Start Production Later This Year']

Running the model

And now we loop over the posts and process each one of them with our extractor.

[ ]
100%|██████████| 10/10 [00:10<00:00,  1.09s/it]

Let's look at the results:

[ ]

Looking at these results, the model got 9/10 correctly. It didn't pick up on Shaolin Soccer and God of Gambler in example #4. It also called the second example "Pixar's Luca" instead of "Luca". But maybe we'll let this one slide.

When experimenting with extrction prompts, we'll often find edge-cases along the way. What if a post has two movies mentioned, for example? The more we run into such examples, the more examples we can add to the prompt that address these cases.

How well does this work?

We can better measure the performance of this extraction method using a larger labeled dataset. So let's load a test set of 100 examples:

[ ]

Let's run the extractor on these post titles (calling the API in parallel for quicker results):

[ ]

Let's look at some results:

[ ]

Let's calculate the accuracy by comparing to the labeled examples

[ ]
Classification accuracy 89.0%

So it seems this prompt works well on this small test set. It's not guaranteed it will do as well on other sets, however. The prompt can be improved by trying on more data, discovering edge cases, and adding more examples to the prompt.

We can look at the examples it got wrong:

[ ]

It indeed failed to pick up a few examples. Sometimes this uncovers edge cases and understandable mistakes (e.g. two films are mentioned in the text).

We can look at the classification report for a more detailed look at what's included in the test set, and what the model got right and wrong:

[ ]
                                      precision    recall  f1-score   support

                                1917       0.00      0.00      0.00         2
               2001: a space odyssey       1.00      1.00      1.00         1
                            ad astra       1.00      1.00      1.00         1
     alice doesn't live here anymore       1.00      1.00      1.00         1
                       austin powers       1.00      1.00      1.00         1
                  back to the future       0.00      0.00      0.00         0
               back to the future ii       0.00      0.00      0.00         1
                        blood simple       1.00      1.00      1.00         1
                   bohemian rhapsody       1.00      1.00      1.00         1
                         borderlands       1.00      1.00      1.00         1
                     brief encounter       1.00      1.00      1.00         1
                                cats       1.00      1.00      1.00         1
                               congo       1.00      1.00      1.00         1
                         death rider       0.00      0.00      0.00         0
death rider in the house of vampires       0.00      0.00      0.00         1
                 dolemite is my name       1.00      1.00      1.00         1
                      dracula untold       1.00      1.00      1.00         1
                              dreams       1.00      1.00      1.00         1
                                dune       1.00      1.00      1.00         1
                    edge of tomorrow       1.00      1.00      1.00         1
                             el topo       1.00      1.00      1.00         1
                        end of watch       1.00      1.00      1.00         1
                         faith based       1.00      1.00      1.00         1
                            fun home       1.00      1.00      1.00         1
                          goodfellas       0.00      0.00      0.00         1
                   gretel and hansel       1.00      1.00      1.00         1
                           hair love       1.00      1.00      1.00         1
                         hard boiled       1.00      1.00      1.00         1
                        interstellar       1.00      1.00      1.00         1
                           john wick       1.00      1.00      1.00         1
                         jojo rabbit       1.00      1.00      1.00         2
                           king kong       1.00      1.00      1.00         1
                          knives out       1.00      1.00      1.00         1
                        little women       1.00      1.00      1.00         1
                             mad max       0.00      0.00      0.00         1
                      marriage story       1.00      1.00      1.00         1
                              movies       0.00      0.00      0.00         0
                          ni no kuni       1.00      1.00      1.00         1
                                none       0.81      0.97      0.88        30
       once upon a time in hollywood       1.00      1.00      1.00         2
                            parasite       1.00      1.00      1.00         5
                         ratatouille       1.00      1.00      1.00         1
                            ricochet       1.00      1.00      1.00         1
                             robocop       1.00      1.00      1.00         1
                               rocky       1.00      1.00      1.00         1
                        rocky balboa       1.00      1.00      1.00         1
                                 run       1.00      1.00      1.00         1
                       shin godzilla       1.00      1.00      1.00         1
                           star wars       0.00      0.00      0.00         1
                             swallow       1.00      1.00      1.00         1
                        the big year       1.00      1.00      1.00         1
                     the flintstones       1.00      1.00      1.00         1
                           the grude       1.00      1.00      1.00         1
                          the grudge       1.00      1.00      1.00         3
                        the ice road       1.00      1.00      1.00         1
                        the irishman       0.00      0.00      0.00         1
                      the lighthouse       1.00      1.00      1.00         1
                       the two popes       1.00      1.00      1.00         1
                                togo       1.00      1.00      1.00         1
                             tumbbad       1.00      1.00      1.00         1
                          uncut gems       0.00      0.00      0.00         1
                     unknown soldier       1.00      1.00      1.00         1
                          waterworld       0.00      0.00      0.00         0
                              willow       1.00      1.00      1.00         1
                        wonder woman       0.00      0.00      0.00         1
                   wonder woman 1984       1.00      1.00      1.00         1

                            accuracy                           0.89       100
                           macro avg       0.80      0.80      0.80       100
                        weighted avg       0.84      0.89      0.86       100

This type of extraction is interesting because it doesn't just blindly look at the text. The model has picked up on movie information during its pretraining process and that helps it understand the task from only a few examples.

You can think about extending this to other subreddits, to extract other kinds of entities and information. Let us know in the forum what you experiment with and what kinds of results you see!

Happy building!