


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



import re import requests import pandas as pd import spacy from sklearn.metrics import precision_score, recall_score, f1_score
nlp = spacy.load("en_core_web_sm")
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"
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))
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
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
true=[] rule=[] spacy=[]
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])