Docsity

NLP Lab Experiment/Assignment 6 Group B 4 Program Code SPPU TE AIDS 2024 Pattern, Papers of Natural Language Processing (NLP)

Toggle sidebar
bg1
import re
import requests
import pandas as pd
import spacy
from sklearn.metrics import precision_score, recall_score, f1_score
# Load spaCy model
nlp = spacy.load("en_core_web_sm")
# URLs
train_url = "https://raw.githubusercontent.com/synalp/NER/refs/heads/master/corpus/CoNLL-
2003/eng.train"
news_url = "https://raw.githubusercontent.com/tomasonjo/blog-
datasets/refs/heads/main/news_articles.csv"
# LOAD CoNLL DATASET
response = requests.get(train_url)
lines = response.text.split("\n")
sentences = []
tokens = []
labels = []
for line in lines:
if line.strip()=="":
if tokens:
sentences.append((tokens,labels))
tokens=[]
labels=[]
continue
if line.startswith("-DOCSTART-"):
continue
parts=line.split()
if len(parts)>=4:
tokens.append(parts[0])
labels.append(parts[-1])
print("Total Sentences :",len(sentences))
# Rule Based NER
def rule_predict(tokens):
pred=[]
org_words=["Inc","Ltd","Corporation","Company","Bank","University","Agency"]
loc_words=["India","China","France","Germany","London","Paris","Tokyo"]
for w in tokens:
if w.istitle():
pred.append("B-PER")
elif w in org_words:
pred.append("B-ORG")
elif w in loc_words:
pred.append("B-LOC")
else:
pred.append("O")
return pred
# spaCy Prediction
def spacy_predict(tokens):
text=" ".join(tokens)
pf3
pf4

Partial preview of the text

Download NLP Lab Experiment/Assignment 6 Group B 4 Program Code SPPU TE AIDS 2024 Pattern and more Papers Natural Language Processing (NLP) in PDF only on Docsity!

import re import requests import pandas as pd import spacy from sklearn.metrics import precision_score, recall_score, f1_score

Load spaCy model

nlp = spacy.load("en_core_web_sm")

URLs

train_url = "https://raw.githubusercontent.com/synalp/NER/refs/heads/master/corpus/CoNLL- 2003/eng.train" news_url = "https://raw.githubusercontent.com/tomasonjo/blog- datasets/refs/heads/main/news_articles.csv"

LOAD CoNLL DATASET

response = requests.get(train_url) lines = response.text.split("\n") sentences = [] tokens = [] labels = [] for line in lines: if line.strip()=="": if tokens: sentences.append((tokens,labels)) tokens=[] labels=[] continue if line.startswith("-DOCSTART-"): continue parts=line.split() if len(parts)>=4: tokens.append(parts[0]) labels.append(parts[-1]) print("Total Sentences :",len(sentences))

Rule Based NER

def rule_predict(tokens): pred=[] org_words=["Inc","Ltd","Corporation","Company","Bank","University","Agency"] loc_words=["India","China","France","Germany","London","Paris","Tokyo"] for w in tokens: if w.istitle(): pred.append("B-PER") elif w in org_words: pred.append("B-ORG") elif w in loc_words: pred.append("B-LOC") else: pred.append("O") return pred

spaCy Prediction

def spacy_predict(tokens): text=" ".join(tokens)

doc=nlp(text) pred=["O"]*len(tokens) token_map={} for i,t in enumerate(tokens): token_map.setdefault(t,[]).append(i) used=[] for ent in doc.ents: label=None if ent.label_=="PERSON": label="B-PER" elif ent.label_=="ORG": label="B-ORG" elif ent.label_ in ["GPE","LOC"]: label="B-LOC" else: continue for word in ent.text.split(): if word in token_map: for idx in token_map[word]: if idx not in used: pred[idx]=label used.append(idx) break return pred

Evaluation

true=[] rule=[] spacy=[]

use first 400 sentences

for tokens,labels in sentences[:400]: gt=[] for x in labels: if "PER" in x: gt.append("PER") elif "ORG" in x: gt.append("ORG") elif "LOC" in x: gt.append("LOC") else: gt.append("O") r=[] for x in rule_predict(tokens): if "PER" in x: r.append("PER") elif "ORG" in x: r.append("ORG") elif "LOC" in x: r.append("LOC") else: r.append("O")

if w.istitle(): entities.append((w,"PERSON")) print(entities[:20])

OUTPUT: