Giter VIP home page Giter VIP logo

mastering-spacy's Introduction

Mastering spaCy

Mastering spaCy

This is the code repository for Mastering spaCy, published by Packt.

An end-to-end practical guide to implementing NLP applications using the Python ecosystem

What is this book about?

spaCy is an industrial-grade, efficient NLP Python library. It offers various pre-trained models and ready-to-use features. Mastering spaCy provides you with end-to-end coverage of spaCy's features and real-world applications.

This book covers the following exciting features:

  • Install spaCy, get started easily, and write your first Python script
  • Understand core linguistic operations of spaCy
  • Discover how to combine rule-based components with spaCy statistical models
  • Become well-versed with named entity and keyword extraction
  • Build your own ML pipelines using spaCy

If you feel this book is for you, get your copy today!

https://www.packtpub.com/

Errata

page 10

How it looks like: word.index(e) How it should be: word.index("e")

How it looks like: vecs = np.vstack([word.vector for word in vocab if word.has_vector]) How it should be: vecs = np.vstack([word.vector for word in vocab if word.has_vector])

Instructions and Navigations

All of the code is organized into folders. For example, Chapter02.

The code will look like the following:

import spacy
nlp = spacy.load("en_subwords_wiki_lg"

Following is what you need for this book: This book is for data scientists and machine learners who want to excel in NLP as well as NLP developers who want to master spaCy and build applications with it. Language and speech professionals who want to get hands-on with Python and spaCy and software developers who want to quickly prototype applications with spaCy will also find this book helpful. Beginner-level knowledge of the Python programming language is required to get the most out of this book. A beginner-level understanding of linguistics such as parsing, POS tags, and semantic similarity will also be useful.

With the following software and hardware list you can run all code files present in the book (Chapter 1-15).

Software and Hardware List

Chapter Software required OS required
1 Python>=3.6 Windows, Mac OS X, and Linux (Any)
2 spaCy v3.0 Windows, Mac OS X, and Linux (Any)
3 Tensorflow 2.0 Windows, Mac OS X, and Linux (Any)
4 Transformers Windows, Mac OS X, and Linux (Any)
5 scikit-learn Windows, Mac OS X, and Linux (Any)
6 pandas Windows, Mac OS X, and Linux (Any)
7 NumPy Windows, Mac OS X, and Linux (Any)
8 matplotlib Windows, Mac OS X, and Linux (Any)
9 Jupyter Windows, Mac OS X, and Linux (Any)

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. Click here to download it.

Related products

Get to Know the Author

Duygu AltΔ±nok is a senior Natural Language Processing (NLP) engineer with 12 years of experience in almost all areas of NLP, including search engine technology, speech recognition, text analytics, and conversational AI. She has published several publications in the NLP area at conferences such as LREC and CLNLP. She also enjoys working on open source projects and is a contributor to the spaCy library. Duygu earned her undergraduate degree in computer engineering from METU, Ankara, in 2010 and later earned her master's degree in mathematics from Bilkent University, Ankara, in 2012. She is currently a senior engineer at German Autolabs with a focus on conversational AI for voice assistants. Originally from Istanbul, Duygu currently resides in Berlin, Germany, with her cute dog Adele.

Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.

https://packt.link/free-ebook/9781800563353

mastering-spacy's People

Contributors

duygua avatar kevinlu1248 avatar packt-itservice avatar packtutkarshr avatar roshank10 avatar sonam-packt avatar thomashallam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mastering-spacy's Issues

Lemmatization in NLU example doesn't work with spaCy 3.0

Like the title says, the example on pages 46 and 47 throws an error if you are using spaCy 3.0 as described here.

To that end, I changed the code using the template provided here like this:

import spacy   
nlp = spacy.load('en_core_web_md')   
nlp.get_pipe("attribute_ruler").add([[{"TEXT": "Angeltown"}]], {"LEMMA": "Los Angeles"})
doc = nlp("I am flying to Angeltown.")
for token in doc: 
    print(token.text, token.lemma_)

and got the desired output.

A real-world example NER example Chapter 03

Hi everyone I am copying from the book the code that takes the NY times article but I cannot get the book's output and also the code is not in chapter 03

from bs4 import BeautifulSoup
import requests
import spacy
def url_text(url_string):
res = requests.get(url_string)
html = res.text
soup = BeautifulSoup(html, 'html5lib')
for script in soup(["script", "style", 'aside']):
script.extract()
text = soup.get_text()
return " ".join(text.split())
ny_art = url_text("https://www.nytimes.com/2021/01/12/opinion/trump-america-allies.html")
nlp = spacy.load("en_core_web_md")
doc = nlp(ny_art)
len(doc.ents)
from collections import Counter
labels = [ent.label_ for ent in doc.ents]
Counter(labels)

Thank you

Chapter 4 [os error "en" model and it takes only two positions]

image

This is the error, I have solved this using three things.

  1. instead of using model 'en' we can use the "en_core_web_md" model.
  2. You will get another error like it take only 2 positions but you have given 3. for that just remove the none.
  3. You will get another error like list of dictionary not needed, you can enclose the matcher pattern inside the two dimension array(like nested list)

Here's my code!

image

Recognizing the intent using wordlists

Most likely due to a spaCy upgrade to 3.0 the book code doesn't work, here's the better version. Corrections in comments.

doc   = nlp("i want to make a reservation for a flight")
dObj  = None
tVerb = None

#extract the direct object and its transitive verb
for token in doc:
    if token.dep_ == "dobj":
        dObj = token      
        tVerb= token.head 

# extract the helper verb
intentVerb = None

verbList = ["want","like","need","order"]
if tVerb.text in verbList:
    intentVerb = tVerb
else:
    if tVerb.head.dep_ == "ROOT":
        intentVerb = tVerb.head # <---------- intentVerb instead of helperVerb
        
#extract the object of the intent
intentObj = None
objList = ["flight","meal","booking"]
if dObj.text in objList:
    intentObj=dObj 
else:
    for child in tVerb.children: # <---------- this was dObj instead of tVerb
        if child.dep_ == "prep":
            intentObj= list(child.children)[0]
            break
        elif child.dep_ == "compound":
            intentObj = child
            break

print(intentVerb.text+intentObj.text.capitalize())

The graph now looks a little different, so need to look for the prep link from the root's children.
displacy.render(doc,style='dep') shows:
Bildschirmfoto 2021-10-26 um 17 43 46

Trichotillomania

Hi Duygu, on page 116:

doc = nlp("I suffered from Trichotillomania when I was in college. The doctor prescribed me psychosomatic medicine.")
pattern = [{"LENGTH": {">=":10}}]
matcher.add("longWords", [pattern])
matches = matcher(doc)
for mid, start, end in matches:
    print(start, end, doc[start:end])

I'm getting

0 1 I
3 4 Trichotillomania
5 6 I
12 13 prescribed
14 15 psychosomatic

Having "prescribed" in there is fine (page 116 however says differently), yet finding "I" is sort of unexplainable to me. I'm on spaCy version 3.1.3. Is this a bug or a feature?

Greets, rudisoft

Lemmatization in NLU

Hi Duygu, in the book mastering spaCy, page 46, chapter 2 we have the following code:

import spacy
from spacy.symbols import ORTH, LEMMA
nlp=spacy.load('en')
special_case = [{ORTH: "Angeltown", LEMMA: "Los Angeles"}]
nlp.tokenizer.add_special_case(u'Angeltown',special_case)
doc=nlp(u'I am flying to Angeltown')
for token in doc:
    print(token.text, token.lemma_)

trying to import the language model en by

python -m spacy download en

doesn't work:

As of spaCy v3.0, shortcuts like 'en' are deprecated. Please use the full pipeline package name 'en_core_web_sm' instead.

Not sure if

special_case = [{ORTH: "Angeltown", LEMMA: "Los Angeles"}]
nlp.tokenizer.add_special_case(u'Angeltown',special_case)

fails with Unable to set attribute 'LEMMA' in tokenizer exception for 'Angeltown'. Tokenizer exceptions are only allowed to specify ORTH and NORM because of that.

However this get's the job done:

import spacy
from spacy.symbols import ORTH, LEMMA, NORM
nlp=spacy.load('en_core_web_md')
special_case = [{ORTH: "Angeltown", NORM: "Los Angeles"}]
nlp.tokenizer.add_special_case(u'Angeltown',special_case)
doc=nlp(u'I am flying to Angeltown')
for token in doc:
    print(token.text, token.lemma_)

Thanks for the good book!

Code on GitHub

It seems that almost every chapter in the repository have missing code, is there any plans to update the repo with some notebooks with all the books's code?

Thank you, I'm loving the book.

Error: No such command 'init-model'

Hi Duygu, it's me again πŸ˜…, this time on page 155. It's for others that may have the same issue:

python -m spacy init-model en en_subwords_wiki_lg --vectors-loc wiki-news-300d-1M-subword.vec.zip

gave me:
Error: No such command 'init-model'

it seems changed after spaCy 3. This however got the job done:
python3 -m spacy init vectors en -n en_subwords_wiki_lg wiki-news-300d-1M-subword.vec en_subwords_wiki_lg

Good to close right away.

Emoji extraction Chapter

Hi in case you want to upload the emoji drill here is the code

import spacy
from spacy.matcher import Matcher
from spacymoji import Emoji
nlp = spacy.load("en_core_web_md")

pos_emoji = ["πŸ˜€", "πŸ˜ƒ", "πŸ˜‚", "😊", "😊", "😍"]  
neg_emoji = ["😞", "😠", "😩", "😒", "😭", "πŸ˜’"]
pos_patterns = [[{"ORTH": emoji}] for emoji in pos_emoji]
neg_patterns = [[{"ORTH": emoji}] for emoji in neg_emoji]
matcher = Matcher(nlp.vocab)
matcher.add("posEmoji", pos_patterns)
matcher.add("negEmoji", neg_patterns)
doc = nlp(" I love Zara 😍")
for mid, start, end in matcher(doc):
      print(start, end, doc[start:end])

Cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.