A fine-tuned
GPT-2 model for
3-class sentiment classification (negative / neutral / positive), trained on the
Tweet Sentiment Extraction dataset.
1import torch
2from transformers import GPT2ForSequenceClassification, GPT2Tokenizer
3
4model_name = "ayushArtesian/gpt2-sentiment-model"
5
6tokenizer = GPT2Tokenizer.from_pretrained(model_name)
7model = GPT2ForSequenceClassification.from_pretrained(model_name)
8
9# Required — GPT-2 has no native pad token
10tokenizer.pad_token = tokenizer.eos_token
11model.config.pad_token_id = tokenizer.pad_token_id
12
13device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14model.to(device)
15model.eval()
16
17label_map = {0: "negative", 1: "neutral", 2: "positive"}
18
19def predict_sentiment(text: str) -> str:
20 inputs = tokenizer(
21 text,
22 return_tensors="pt",
23 padding=True,
24 truncation=True,
25 max_length=512
26 )
27 inputs = {k: v.to(device) for k, v in inputs.items()}
28
29 with torch.no_grad():
30 outputs = model(**inputs)
31
32 predicted_class = torch.argmax(outputs.logits, dim=1).item()
33 return label_map[predicted_class]
34
35# Example
36print(predict_sentiment("I hope your day is as pleasant as you are"))
37# → positive
38
39print(predict_sentiment("This is the worst experience I've ever had"))
40# → negative
1from transformers import pipeline
2
3classifier = pipeline(
4 "text-classification",
5 model="ayushArtesian/gpt2-sentiment-model"
6)
7
8result = classifier("I absolutely love this!")
9print(result)
10# → [{'label': 'LABEL_2', 'score': 0.91}] (LABEL_2 = positive)
The model was trained on the
mteb/tweet_sentiment_extraction dataset, which contains tweets labelled with three sentiment classes:
Only a 1,000-sample subset of the training and test splits was used for this experiment.
1@article{radford2019language,
2 title={Language Models are Unsupervised Multitask Learners},
3 author={Radford, Alec and Wu, Jeff and Child, Rewon and Luan, David and Amodei, Dario and Sutskever, Ilya},
4 year={2019}
5}