Views
No views yet
1from transformers import AutoTokenizer, AutoModelForTokenClassification
2from nltk.tokenize import word_tokenize
3import torch
4import spacy
5
6# You might want to use it to remove enteties in the text (the model usually predicts them as scientific)
7nlp = spacy.load("en_core_web_sm")
8# doc = nlp(text)
9# names = [ent.text for ent in doc.ents]
10
11tokenizer = AutoTokenizer.from_pretrained("JonyC/scibert-science-word-classifier")
12model = AutoModelForTokenClassification.from_pretrained("JonyC/scibert-science-word-classifier")
13
14# define max_len as needed.
15def classify_term(term, max_len=12):
16 term = term.lower()
17 tokens = tokenizer(term, return_tensors="pt", truncation=True, padding=True, max_length=max_len).to(device)
18 output = model(**tokens).logits
19 pred = torch.argmax(output).item()
20
21 return "Scientific" if pred == 1 else "Non-Scientific"
22
23# For single term:
24print(classify_term("quantum mechanics"))
25print(classify_term("table"))
26print(classify_term("photosynthesis"))
27
28# For sentences:
29words = word_tokenize("some sentence") # you can also use sentence.split()
30results = []
31for w in words:
32 res = classify_term(w)
33 results.append(res)
34
35for w, p in zip(words, results):
36 print(f"Word: {w}, Predicted Label: {p}")['Quantum', 'computing', 'field', 'complex', 'quantum', 'qubits', 'property', 'superposition', 'entanglement', 'matter', 'factor', 'state', 'scale']