Views
No views yet
0: negative1: neutral2: positiveelectra_classifier.py. You can download the file, or you can install the package from PyPI.pip install electra-classifier1# Install the package in a notebook
2import sys
3!{sys.executable} -m pip install electra-classifier
4
5# Import libraries
6import torch
7from transformers import AutoTokenizer
8from electra_classifier import ElectraClassifier
9
10# Load tokenizer and model
11model_name = "jbeno/electra-base-classifier-sentiment"
12tokenizer = AutoTokenizer.from_pretrained(model_name)
13model = ElectraClassifier.from_pretrained(model_name)
14
15# Set model to evaluation mode
16model.eval()
17
18# Run inference
19text = "I love this restaurant!"
20inputs = tokenizer(text, return_tensors="pt")
21
22with torch.no_grad():
23 logits = model(**inputs)
24 predicted_class_id = torch.argmax(logits, dim=1).item()
25 predicted_label = model.config.id2label[predicted_class_id]
26 print(f"Predicted label: {predicted_label}")google/electra-base-discriminator)ElectraClassifier(
(electra): ElectraModel(
(embeddings): ElectraEmbeddings(
(word_embeddings): Embedding(30522, 768, padding_idx=0)
(position_embeddings): Embedding(512, 768)
(token_type_embeddings): Embedding(2, 768)
(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
(encoder): ElectraEncoder(
(layer): ModuleList(
(0-11): 12 x ElectraLayer(
(attention): ElectraAttention(
(self): ElectraSelfAttention(
(query): Linear(in_features=768, out_features=768, bias=True)
(key): Linear(in_features=768, out_features=768, bias=True)
(value): Linear(in_features=768, out_features=768, bias=True)
(dropout): Dropout(p=0.1, inplace=False)
)
(output): ElectraSelfOutput(
(dense): Linear(in_features=768, out_features=768, bias=True)
(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
)
(intermediate): ElectraIntermediate(
(dense): Linear(in_features=768, out_features=3072, bias=True)
(intermediate_act_fn): GELUActivation()
)
(output): ElectraOutput(
(dense): Linear(in_features=3072, out_features=768, bias=True)
(LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
)
)
)
)
)
(pooling): PoolingLayer()
(classifier): Classifier(
(layers): Sequential(
(0): Linear(in_features=768, out_features=1024, bias=True)
(1): SwishGLU(
(projection): Linear(in_features=1024, out_features=2048, bias=True)
(activation): SiLU()
)
(2): Dropout(p=0.3, inplace=False)
(3): Linear(in_features=1024, out_features=1024, bias=True)
(4): SwishGLU(
(projection): Linear(in_features=1024, out_features=2048, bias=True)
(activation): SiLU()
)
(5): Dropout(p=0.3, inplace=False)
(6): Linear(in_features=1024, out_features=3, bias=True)
)
)
)1class SwishGLU(nn.Module):
2 def __init__(self, input_dim: int, output_dim: int):
3 super(SwishGLU, self).__init__()
4 self.projection = nn.Linear(input_dim, 2 * output_dim)
5 self.activation = nn.SiLU()
6
7 def forward(self, x):
8 x_proj_gate = self.projection(x)
9 projected, gate = x_proj_gate.tensor_split(2, dim=-1)
10 return projected * self.activation(gate)cls: Uses the representation of the [CLS] token.mean: Calculates the mean of the token embeddings.max: Takes the maximum value across token embeddings.1class PoolingLayer(nn.Module):
2 def __init__(self, pooling_type='cls'):
3 super().__init__()
4 self.pooling_type = pooling_type
5
6 def forward(self, last_hidden_state, attention_mask):
7 if self.pooling_type == 'cls':
8 return last_hidden_state[:, 0, :]
9 elif self.pooling_type == 'mean':
10 return (last_hidden_state * attention_mask.unsqueeze(-1)).sum(1) / attention_mask.sum(-1).unsqueeze(-1)
11 elif self.pooling_type == 'max':
12 return torch.max(last_hidden_state * attention_mask.unsqueeze(-1), dim=1)[0]
13 else:
14 raise ValueError(f"Unknown pooling method: {self.pooling_type}")input_dim: 768num_layers: 2hidden_dim: 1024hidden_activation: SwishGLUdropout_rate: 0.3n_classes: 31class Classifier(nn.Module):
2 def __init__(self, input_dim, hidden_dim, hidden_activation, num_layers, n_classes, dropout_rate=0.0):
3 super().__init__()
4 layers = []
5 layers.append(nn.Linear(input_dim, hidden_dim))
6 layers.append(hidden_activation)
7 if dropout_rate > 0:
8 layers.append(nn.Dropout(dropout_rate))
9
10 for _ in range(num_layers - 1):
11 layers.append(nn.Linear(hidden_dim, hidden_dim))
12 layers.append(hidden_activation)
13 if dropout_rate > 0:
14 layers.append(nn.Dropout(dropout_rate))
15
16 layers.append(nn.Linear(hidden_dim, n_classes))
17 self.layers = nn.Sequential(*layers)hidden_dim: Size of the hidden layers in the classifier.hidden_activation: Activation function used in the classifier ('SwishGLU').num_layers: Number of layers in the classifier.dropout_rate: Dropout rate used in the classifier.pooling: Pooling strategy used ('mean').Merged Dataset Classification Report
precision recall f1-score support
negative 0.847081 0.777211 0.810643 2352
neutral 0.704453 0.761072 0.731669 1829
positive 0.828047 0.844615 0.836249 2349
accuracy 0.796937 6530
macro avg 0.793194 0.794299 0.792854 6530
weighted avg 0.800285 0.796937 0.797734 6530
ROC AUC: 0.926344
Predicted negative neutral positive
Actual
negative 1828 331 193
neutral 218 1392 219
positive 112 253 1984
Macro F1 Score: 0.79DynaSent Round 1 Classification Report
precision recall f1-score support
negative 0.901222 0.737500 0.811182 1200
neutral 0.745957 0.922500 0.824888 1200
positive 0.850970 0.804167 0.826907 1200
accuracy 0.821389 3600
macro avg 0.832716 0.821389 0.820992 3600
weighted avg 0.832716 0.821389 0.820992 3600
ROC AUC: 0.945131
Predicted negative neutral positive
Actual
negative 885 201 114
neutral 38 1107 55
positive 59 176 965
Macro F1 Score: 0.82DynaSent Round 2 Classification Report
precision recall f1-score support
negative 0.696154 0.754167 0.724000 240
neutral 0.770408 0.629167 0.692661 240
positive 0.704545 0.775000 0.738095 240
accuracy 0.719444 720
macro avg 0.723702 0.719444 0.718252 720
weighted avg 0.723702 0.719444 0.718252 720
ROC AUC: 0.88842
Predicted negative neutral positive
Actual
negative 181 26 33
neutral 44 151 45
positive 35 19 186
Macro F1 Score: 0.72SST-3 Classification Report
precision recall f1-score support
negative 0.831878 0.835526 0.833698 912
neutral 0.452703 0.344473 0.391241 389
positive 0.834669 0.916392 0.873623 909
accuracy 0.782353 2210
macro avg 0.706417 0.698797 0.699521 2210
weighted avg 0.766284 0.782353 0.772239 2210
ROC AUC: 0.885009
Predicted negative neutral positive
Actual
negative 762 104 46
neutral 136 134 119
positive 18 58 833
Macro F1 Score: 0.701@article{beno-2024-electragpt,
2 title={ELECTRA and GPT-4o: Cost-Effective Partners for Sentiment Analysis},
3 author={James P. Beno},
4 journal={arXiv preprint arXiv:2501.00062},
5 year={2024},
6 eprint={2501.00062},
7 archivePrefix={arXiv},
8 primaryClass={cs.CL},
9 url={https://arxiv.org/abs/2501.00062},
10}