Views
No views yet
1import torch
2import torch.nn as nn
3from huggingface_hub import PyTorchModelHubMixin
4
5
6class TextClassifier(nn.Module, PyTorchModelHubMixin):
7 def __init__(self, vocab_size=30522, embed_dim=128, num_classes=4):
8 super().__init__()
9 self.embedding = nn.Embedding(vocab_size, embed_dim)
10 self.fc1 = nn.Linear(embed_dim, 128)
11 self.relu = nn.ReLU()
12 self.fc2 = nn.Linear(128, num_classes)
13
14 def forward(self, input_ids, attention_mask=None):
15 x = self.embedding(input_ids)
16
17 if attention_mask is not None:
18 mask = attention_mask.unsqueeze(-1).float()
19 x = x * mask
20 x = x.sum(dim=1) / mask.sum(dim=1).clamp(min=1e-9)
21 else:
22 x = x.mean(dim=1)
23
24 x = self.fc1(x)
25 x = self.relu(x)
26 x = self.fc2(x)
27 return x
28
29model = TextClassifier.from_pretrained("pulkitchowdry/sample-agnews-classifer")
30model.eval()
311
2from transformers import AutoTokenizer
3
4tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
5text = "Messi scores a hatrick in the world cup"
6
7inputs = tokenizer(
8 text,
9 return_tensors="pt",
10 padding="max_length",
11 truncation=True,
12 max_length=128
13 )
141
2with torch.no_grad():
3 logits = model(
4 inputs["input_ids"],
5 attention_mask=inputs["attention_mask"]
6 )
7 prediction = logits.argmax(dim=1).item()
8
9print(f"{prediction}")
10categories = ["World", "Sports", "Business", "Science/Technology"]
11
12print("Predicted class: ", categories[prediction])
13@misc{pulkitchowdry_2026_sample_ag_news,
title = {Sample AG News Classifier},
author = {Pulkit Chowdry},
year = {2026},
}