Views
No views yet
1from transformers import AutoTokenizer, AutoModelForSequenceClassification
2import torch
3import numpy as np
4
5# choose GPU if available
6device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
8# select mode path here
9pretrained_LM_path = "kornosk/bert-election2020-twitter-stance-biden"
10
11# load model
12tokenizer = AutoTokenizer.from_pretrained(pretrained_LM_path)
13model = AutoModelForSequenceClassification.from_pretrained(pretrained_LM_path)
14
15id2label = {
16 0: "AGAINST",
17 1: "FAVOR",
18 2: "NONE"
19}
20
21##### Prediction Neutral #####
22sentence = "Hello World."
23inputs = tokenizer(sentence.lower(), return_tensors="pt")
24outputs = model(**inputs)
25predicted_probability = torch.softmax(outputs[0], dim=1)[0].tolist()
26
27print("Sentence:", sentence)
28print("Prediction:", id2label[np.argmax(predicted_probability)])
29print("Against:", predicted_probability[0])
30print("Favor:", predicted_probability[1])
31print("Neutral:", predicted_probability[2])
32
33##### Prediction Favor #####
34sentence = "Go Go Biden!!!"
35inputs = tokenizer(sentence.lower(), return_tensors="pt")
36outputs = model(**inputs)
37predicted_probability = torch.softmax(outputs[0], dim=1)[0].tolist()
38
39print("Sentence:", sentence)
40print("Prediction:", id2label[np.argmax(predicted_probability)])
41print("Against:", predicted_probability[0])
42print("Favor:", predicted_probability[1])
43print("Neutral:", predicted_probability[2])
44
45##### Prediction Against #####
46sentence = "Biden is the worst."
47inputs = tokenizer(sentence.lower(), return_tensors="pt")
48outputs = model(**inputs)
49predicted_probability = torch.softmax(outputs[0], dim=1)[0].tolist()
50
51print("Sentence:", sentence)
52print("Prediction:", id2label[np.argmax(predicted_probability)])
53print("Against:", predicted_probability[0])
54print("Favor:", predicted_probability[1])
55print("Neutral:", predicted_probability[2])
56
57# please consider citing our paper if you feel this is useful :)1@inproceedings{kawintiranon2021knowledge,
2 title={Knowledge Enhanced Masked Language Model for Stance Detection},
3 author={Kawintiranon, Kornraphop and Singh, Lisa},
4 booktitle={Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies},
5 year={2021},
6 publisher={Association for Computational Linguistics},
7 url={https://www.aclweb.org/anthology/2021.naacl-main.376}
8}