jbeno commited on
Commit
d45d6f8
·
1 Parent(s): 22eaf1d

Initial model files and config for custom ELECTRA Base classifier for sentiment

Browse files
README.md CHANGED
@@ -1,3 +1,208 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ tags:
4
+ - sentiment-analysis
5
+ - text-classification
6
+ - electra
7
+ - pytorch
8
+ - transformers
9
  ---
10
+
11
+ # Electra Base Classifier for Sentiment Analysis
12
+
13
+ This model is a fine-tuned [ELECTRA base model](https://huggingface.co/google/electra-base-discriminator) for sentiment analysis, enhanced with custom pooling and a SwishGLU activation function. It classifies text into three sentiment categories: negative, neutral, and positive.
14
+
15
+ ## Model Architecture
16
+
17
+ - **Base Model**: ELECTRA base (`google/electra-base-discriminator`)
18
+ - **Custom Components**:
19
+ - **Pooling Layer**: Custom pooling layer supporting 'cls', 'mean', and 'max' pooling types.
20
+ - **Activation Function**: Custom SwishGLU activation function.
21
+ - **Classifier**: Custom classifier with configurable hidden dimensions, number of layers, and dropout rate.
22
+
23
+ ## Labels
24
+
25
+ The model predicts the following labels:
26
+
27
+ - `0`: negative
28
+ - `1`: neutral
29
+ - `2`: positive
30
+
31
+ ## How to Use
32
+
33
+ To use this model, you need to download the `electra_base_classifier_sentiment.py` file from this repository and place it in your working directory. This file contains the custom classes required to load and use the model.
34
+
35
+ ```python
36
+ import torch
37
+ from transformers import AutoTokenizer
38
+ from electra_base_classifier_sentiment import ElectraBaseClassifierSentiment # Ensure this file is in your working directory
39
+
40
+ model_name = "jbeno/electra-base-classifier-sentiment"
41
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
42
+ model = ElectraBaseClassifierSentiment.from_pretrained(model_name)
43
+ model.eval()
44
+
45
+ # Example usage
46
+ text = "I love this product!"
47
+ inputs = tokenizer(text, return_tensors="pt")
48
+ with torch.no_grad():
49
+ logits = model(**inputs)
50
+ predicted_class_id = torch.argmax(logits, dim=1).item()
51
+ predicted_label = model.config.id2label[str(predicted_class_id)]
52
+ print(f"Predicted label: {predicted_label}")
53
+ ```
54
+
55
+ ## Requirements
56
+ - Python 3.7+
57
+ - PyTorch
58
+ - Transformers library
59
+ - Additional Files:
60
+ - Download **electra_base_classifier_sentiment.py** from this repository and place it in your working directory.
61
+
62
+ ## Custom Model Components
63
+
64
+ ### SwishGLU Activation Function
65
+
66
+ The SwishGLU activation function combines the Swish activation with a Gated Linear Unit (GLU). It enhances the model's ability to capture complex patterns in the data.
67
+
68
+ ```python
69
+ class SwishGLU(nn.Module):
70
+ def __init__(self, input_dim: int, output_dim: int):
71
+ super(SwishGLU, self).__init__()
72
+ self.projection = nn.Linear(input_dim, 2 * output_dim)
73
+ self.activation = nn.SiLU()
74
+
75
+ def forward(self, x):
76
+ x_proj_gate = self.projection(x)
77
+ projected, gate = x_proj_gate.tensor_split(2, dim=-1)
78
+ return projected * self.activation(gate)
79
+ ```
80
+
81
+ ### PoolingLayer
82
+
83
+ The PoolingLayer class allows you to choose between different pooling strategies:
84
+
85
+ - `cls`: Uses the representation of the \[CLS\] token.
86
+ - `mean`: Calculates the mean of the token embeddings.
87
+ - `max`: Takes the maximum value across token embeddings.
88
+
89
+ **'mean'** pooling was used in the fine-tuned model.
90
+
91
+ ```python
92
+ class PoolingLayer(nn.Module):
93
+ def __init__(self, pooling_type='cls'):
94
+ super().__init__()
95
+ self.pooling_type = pooling_type
96
+
97
+ def forward(self, last_hidden_state, attention_mask):
98
+ if self.pooling_type == 'cls':
99
+ return last_hidden_state[:, 0, :]
100
+ elif self.pooling_type == 'mean':
101
+ return (last_hidden_state * attention_mask.unsqueeze(-1)).sum(1) / attention_mask.sum(-1).unsqueeze(-1)
102
+ elif self.pooling_type == 'max':
103
+ return torch.max(last_hidden_state * attention_mask.unsqueeze(-1), dim=1)[0]
104
+ else:
105
+ raise ValueError(f"Unknown pooling method: {self.pooling_type}")
106
+ ```
107
+
108
+ ### Classifier
109
+
110
+ The Classifier class is a customizable feed-forward neural network used for the final classification.
111
+
112
+ The fine-tuned model had:
113
+
114
+ - `input_dim`: 768
115
+ - `num_layers`: 2
116
+ - `hidden_dim`: 1024
117
+ - `hidden_activation`: SwishGLU
118
+ - `dropout_rate`: 0.3
119
+ - `n_classes`: 3
120
+
121
+ ```python
122
+ class Classifier(nn.Module):
123
+ def __init__(self, input_dim, hidden_dim, hidden_activation, num_layers, n_classes, dropout_rate=0.0):
124
+ super().__init__()
125
+ layers = []
126
+ layers.append(nn.Linear(input_dim, hidden_dim))
127
+ layers.append(hidden_activation)
128
+ if dropout_rate > 0:
129
+ layers.append(nn.Dropout(dropout_rate))
130
+
131
+ for _ in range(num_layers - 1):
132
+ layers.append(nn.Linear(hidden_dim, hidden_dim))
133
+ layers.append(hidden_activation)
134
+ if dropout_rate > 0:
135
+ layers.append(nn.Dropout(dropout_rate))
136
+
137
+ layers.append(nn.Linear(hidden_dim, n_classes))
138
+ self.layers = nn.Sequential(*layers)
139
+ ```
140
+
141
+ ## Model Configuration
142
+
143
+ The model's configuration (config.json) includes custom parameters:
144
+
145
+ - `hidden_dim`: Size of the hidden layers in the classifier.
146
+ - `hidden_activation`: Activation function used in the classifier ('SwishGLU').
147
+ - `num_layers`: Number of layers in the classifier.
148
+ - `dropout_rate`: Dropout rate used in the classifier.
149
+ - `pooling`: Pooling strategy used ('mean').
150
+
151
+ ## Training Details
152
+
153
+ ### Dataset
154
+
155
+ The model was trained on the [Sentiment Merged](https://huggingface.co/datasets/jbeno/sentiment_merged) dataset, which is a mix of Stanford Sentiment Treebank (SST-3), DynaSent Round 1, and DynaSent Round 2.
156
+
157
+ ### Code
158
+
159
+ The code used to train the model can be found on GitHub: [jbeno/sentiment](https://github.com/jbeno/sentiment)
160
+
161
+ ### Research Paper
162
+
163
+ The research paper can be found here: [ELECTRA and GPT-4o: Cost-Effective Partners for Sentiment Analysis](https://github.com/jbeno/sentiment/research_paper.pdf)
164
+
165
+ ### Performance
166
+
167
+ - **Merged Dataset**
168
+ - Macro Average F1: **79.29**
169
+ - Accuracy: **79.69**
170
+ - **DynaSent R1**
171
+ - Macro Average F1: **82.10**
172
+ - Accuracy: **82.14**
173
+ - **DynaSent R2**
174
+ - Macro Average F1: **71.83**
175
+ - Accuracy: **71.94**
176
+ - **SST-3**
177
+ - Macro Average F1: **69.95**
178
+ - Accuracy: **78.24**
179
+
180
+ ## License
181
+
182
+ This model is licensed under the MIT License.
183
+
184
+ ## Citation
185
+
186
+ If you use this model in your work, please consider citing it:
187
+
188
+ ```bibtex
189
+ @misc{beno-2024-electra_base_classifier_sentiment,
190
+ title={Electra Base Classifier for Sentiment Analysis},
191
+ author={Jim Beno},
192
+ year={2024},
193
+ publisher={Hugging Face},
194
+ howpublished={\url{https://huggingface.co/jbeno/electra-base-classifier-sentiment}},
195
+ }
196
+ ```
197
+
198
+ ## Contact
199
+
200
+ For questions or comments, please open an issue on the repository or contact [Jim Beno](https://huggingface.co/jbeno).
201
+
202
+ ## Acknowledgments
203
+
204
+ - The [Hugging Face Transformers library](https://github.com/huggingface/transformers) for providing powerful tools for model development.
205
+ - The creators of the [ELECTRA model](https://arxiv.org/abs/2003.10555) for their foundational work.
206
+ - The authors of the datasets used: [Stanford Sentiment Treebank](https://huggingface.co/datasets/stanfordnlp/sst), [DynaSent](https://huggingface.co/datasets/dynabench/dynasent).
207
+ - [Stanford Engineering CGOE](https://cgoe.stanford.edu), [Chris Potts](https://stanford.edu/~cgpotts/), and the Course Facilitators of [XCS224U](https://online.stanford.edu/courses/xcs224u-natural-language-understanding)
208
+
__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .electra_base_classifier_sentiment import ElectraBaseClassifierSentiment
config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "ElectraBaseClassifierSentiment"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "classifier_dropout": null,
7
+ "dropout_rate": 0.3,
8
+ "embedding_size": 768,
9
+ "hidden_act": "gelu",
10
+ "hidden_activation": "SwishGLU",
11
+ "hidden_dim": 1024,
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 768,
14
+ "id2label": {
15
+ "0": "negative",
16
+ "1": "neutral",
17
+ "2": "positive"
18
+ },
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 3072,
21
+ "label2id": {
22
+ "negative": 0,
23
+ "neutral": 1,
24
+ "positive": 2
25
+ },
26
+ "layer_norm_eps": 1e-12,
27
+ "max_position_embeddings": 512,
28
+ "model_type": "electra",
29
+ "num_attention_heads": 12,
30
+ "num_hidden_layers": 12,
31
+ "num_layers": 2,
32
+ "pad_token_id": 0,
33
+ "pooling": "mean",
34
+ "position_embedding_type": "absolute",
35
+ "summary_activation": "gelu",
36
+ "summary_last_dropout": 0.1,
37
+ "summary_type": "first",
38
+ "summary_use_proj": true,
39
+ "torch_dtype": "float32",
40
+ "transformers_version": "4.37.1",
41
+ "type_vocab_size": 2,
42
+ "use_cache": true,
43
+ "vocab_size": 30522
44
+ }
electra_base_classifier_sentiment.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from transformers import ElectraPreTrainedModel, ElectraModel
4
+
5
+ class SwishGLU(nn.Module):
6
+ def __init__(self, input_dim: int, output_dim: int):
7
+ super(SwishGLU, self).__init__()
8
+ # Linear projection to 2 * output_dim to split for gate and projection
9
+ self.projection = nn.Linear(input_dim, 2 * output_dim)
10
+ self.activation = nn.SiLU() # Swish activation
11
+
12
+ def forward(self, x):
13
+ # Apply linear projection
14
+ x_proj_gate = self.projection(x)
15
+ # Split the projection into two parts
16
+ projected, gate = x_proj_gate.tensor_split(2, dim=-1)
17
+ # Apply Swish activation and multiply
18
+ return projected * self.activation(gate)
19
+
20
+
21
+ class PoolingLayer(nn.Module):
22
+ def __init__(self, pooling_type='cls'):
23
+ super().__init__()
24
+ self.pooling_type = pooling_type
25
+
26
+ def forward(self, last_hidden_state, attention_mask):
27
+ if self.pooling_type == 'cls':
28
+ return last_hidden_state[:, 0, :]
29
+ elif self.pooling_type == 'mean':
30
+ # Mean pooling over the token embeddings
31
+ return (last_hidden_state * attention_mask.unsqueeze(-1)).sum(1) / attention_mask.sum(-1).unsqueeze(-1)
32
+ elif self.pooling_type == 'max':
33
+ # Max pooling over the token embeddings
34
+ return torch.max(last_hidden_state * attention_mask.unsqueeze(-1), dim=1)[0]
35
+ else:
36
+ raise ValueError(f"Unknown pooling method: {self.pooling_type}")
37
+
38
+ class Classifier(nn.Module):
39
+ def __init__(self, input_dim, hidden_dim, hidden_activation, num_layers, n_classes, dropout_rate=0.0):
40
+ super().__init__()
41
+ layers = []
42
+ layers.append(nn.Linear(input_dim, hidden_dim))
43
+ layers.append(hidden_activation)
44
+ if dropout_rate > 0:
45
+ layers.append(nn.Dropout(dropout_rate))
46
+
47
+ for _ in range(num_layers - 1):
48
+ layers.append(nn.Linear(hidden_dim, hidden_dim))
49
+ layers.append(hidden_activation)
50
+ if dropout_rate > 0:
51
+ layers.append(nn.Dropout(dropout_rate))
52
+
53
+ layers.append(nn.Linear(hidden_dim, n_classes))
54
+ self.layers = nn.Sequential(*layers)
55
+
56
+ def forward(self, x):
57
+ return self.layers(x)
58
+
59
+ class ElectraBaseClassifierSentiment(ElectraPreTrainedModel):
60
+ def __init__(self, config):
61
+ super().__init__(config)
62
+ self.electra = ElectraModel(config)
63
+
64
+ if hasattr(self.electra, 'pooler'):
65
+ self.electra.pooler = None
66
+
67
+ self.pooling = PoolingLayer(pooling_type=config.pooling)
68
+
69
+ # Handle custom activation functions
70
+ activation_name = config.hidden_activation
71
+ if activation_name == 'SwishGLU':
72
+ hidden_activation = SwishGLU(
73
+ input_dim=config.hidden_dim,
74
+ output_dim=config.hidden_dim
75
+ )
76
+ else:
77
+ activation_class = getattr(nn, activation_name)
78
+ hidden_activation = activation_class()
79
+
80
+ self.classifier = Classifier(
81
+ input_dim=config.hidden_size,
82
+ hidden_dim=config.hidden_dim,
83
+ hidden_activation=hidden_activation,
84
+ num_layers=config.num_layers,
85
+ n_classes=config.num_labels,
86
+ dropout_rate=config.dropout_rate
87
+ )
88
+ self.init_weights()
89
+
90
+
91
+ def forward(self, input_ids=None, attention_mask=None, **kwargs):
92
+ outputs = self.electra(input_ids, attention_mask=attention_mask, **kwargs)
93
+ pooled_output = self.pooling(outputs.last_hidden_state, attention_mask)
94
+ logits = self.classifier(pooled_output)
95
+ return logits
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:777d8bf4e1c5f72c736ac5adc523639c22caf43cf2ba274245a69b2fd0f7e2ca
3
+ size 451348484
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf240ff1218ce49a92f220aa4964c8723729c74734db31a56a92d5d52d8aeb82
3
+ size 451391998
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "mask_token": "[MASK]",
48
+ "model_max_length": 512,
49
+ "pad_token": "[PAD]",
50
+ "sep_token": "[SEP]",
51
+ "strip_accents": null,
52
+ "tokenize_chinese_chars": true,
53
+ "tokenizer_class": "ElectraTokenizer",
54
+ "unk_token": "[UNK]"
55
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff