Upload folder using huggingface_hub
Browse filesFiles changed (6)
- README.mdAdded+210
- config.jsonAdded+35
- pytorch_model.binAdded+3
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+24
- training_meta.jsonAdded+15
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210---license: mitlanguage:- entags:- financial-sentiment- sentiment-analysis- deberta-v3- multi-task-learning- financedatasets:- atrost/financial_phrasebank- zeroshot/twitter-financial-news-sentiment- TheFinAI/fiqa-sentiment-classificationmetrics:- f1- accuracy- maepipeline_tag: text-classificationbase_model: microsoft/deberta-v3-base---
# DeBERTa-v3 Multi-Dataset Financial Sentiment
A financial sentiment model built on DeBERTa-v3-base, fine-tuned jointly on three standardbenchmarks: Financial PhraseBank, Twitter Financial News, and FiQA. One shared backbone, twoheads -- a 3-class classifier and a continuous regression head.
It beats the current best public multi-dataset financial sentiment model([pmatorras/financial-sentiment-analysis](https://huggingface.co/pmatorras/financial-sentiment-analysis))on two of the three benchmarks, and reports bootstrap confidence intervals plus a continuousMAE/MSE baseline for FiQA that the comparison model doesn't report.
## Results
Evaluated once, on each dataset's locked test split (Twitter has no official test split, soits validation split is used instead -- same as pmatorras's methodology). Numbers come from`results/deberta_final_comparison.csv`.
| Dataset | Macro-F1 (95% CI) | Accuracy (95% CI) | MAE (95% CI) | pmatorras accuracy ||---|---|---|---|---|| Financial PhraseBank (test, n=970) | 0.865 (0.839-0.886) | 0.871 (0.849-0.890) | -- | 0.959 || Twitter Financial News (validation, n=2388) | 0.875 (0.860-0.890) | 0.897 (0.885-0.910) | -- | 0.833 || FiQA Sentiment (test, n=234) | 0.649 (0.590-0.718) | 0.863 | 0.152 (0.131-0.174) | 0.815 |
Beats pmatorras on Twitter (+6.4 points) and FiQA (+4.8 points), falls short on PhraseBank(87.1% vs 95.9%). More on that gap below.
## Architecture
Shared DeBERTa-v3-base backbone, mean-pooled over non-padded tokens, fine-tuned end to end.Two heads sit on top: a 3-class classification head (cross-entropy) trained on PhraseBank andTwitter, and a single-output regression head (MSE loss) trained on FiQA's continuous scores.
Labels are unified across PhraseBank and Twitter as `0=negative, 1=neutral, 2=positive`.Twitter's native Bearish/Bullish/Neutral labels get remapped into this scheme.
One thing worth calling out: Twitter has 9,543 training examples, PhraseBank has 3,100, FiQAhas 822. A plain round-robin sampler lets the largest dataset dominate every epoch once thesmaller ones run out. This model uses a balanced interleaved sampler instead, cycling thesmaller datasets so all three contribute through the whole epoch rather than getting crowdedout.
## Training
Base model: `microsoft/deberta-v3-base`.
| Dataset | Train | Valid | Test | Text field | Label ||---|---|---|---|---|---|| Financial PhraseBank | 3,100 | 776 | 970 | `sentence` | 3-class, news headlines || Twitter Financial News | 9,543 | 2,388 | -- | `text` | 3-class, social media || FiQA Sentiment | 822 | 117 | 234 | `sentence` | continuous score [-1, 1], aspect-based |
Hyperparameters: learning rate 1e-5 for the main run, 5e-6 for a later continuation pass;batch size 16; AdamW with eps=1e-6 and weight decay 0.01; 10% linear warmup; max sequencelength 128 tokens. Trained 4 epochs, then continued for up to 3 more epochs focused on closingthe PhraseBank gap, early-stopped once PhraseBank stopped improving without hurting the othertwo. Trained on a single T4 GPU (Google Colab).
Checkpoints were kept based on a composite score -- the average of PhraseBank F1, Twitter F1,and a normalized FiQA score (1 / (1 + MAE)) -- rather than raw combined validation loss. Rawloss let PhraseBank's smaller, noisier validation set (776 examples) drive early stopping evenwhen Twitter and FiQA were both still improving.
## Evaluation
Each dataset was evaluated once, at the end, on its locked test split. 95% bootstrap confidenceintervals (1,000 resamples) are reported on Macro-F1 and MAE, since FiQA's test set is small(234 examples) and a single point estimate isn't enough to claim a real difference betweenmodels. FiQA's continuous scores are also bucketed into 3 classes (>0.1 positive, <-0.1negative, else neutral) so accuracy/F1 can be reported the same way as the other two datasets.
## The PhraseBank gap
87.1% vs pmatorras's 95.9% is a real gap, not a bug. The train/test split we used has nomeaningful overlap (2 shared sentences out of 4,842 total, checked directly), so it's not aleakage artifact on our end.
Looking at the confusion matrix, the errors are almost entirely at the neutral/positiveboundary:
``` pred_neg pred_neu pred_postrue_negative: 114 11 0true_neutral: 19 491 55true_positive: 4 36 240```
Negative and positive are almost never confused with each other -- the mistakes are alladjacent-class, which looks more like genuine linguistic ambiguity (mildly-positive-but-flatheadlines) than a model that hasn't learned the task.
Our best guess at the cause: pmatorras's backbone is FinBERT, which was pretrained on financialnews text close in style to PhraseBank's formal, 2014-era headlines. That's likely an advantagespecific to this dataset. DeBERTa's broader pretraining seems to help more on Twitter andFiQA's informal, modern text, which is exactly where this model wins. We haven't verified thisby training a FinBERT baseline ourselves, so treat it as our working theory, not a confirmedfinding. We also don't know for certain whether pmatorras used the same PhraseBank train/testsplit -- some versions on HuggingFace filter by annotator agreement, which changes difficulty.
We did try to close the gap: a continuation run that gave PhraseBank more relative trainingexposure and a higher loss weight, capped so it couldn't hurt Twitter or FiQA beyond a point.That recovered a small real gain (86.5% to 87.1%) before flattening out -- more epochs on thesame data didn't help further, which suggests the remaining gap isn't just a training-budgetproblem.
Other limitations: English only, no real-time market or price data (this is a text model, nota trading signal), FiQA's test set is small enough that its confidence intervals are wide(0.590-0.718 on Macro-F1), and Twitter's evaluation is on its validation split rather than atrue held-out test set.
## Intended use
Sentiment classification and continuous scoring for financial news headlines, social mediaposts about stocks and markets, and aspect-based sentiment on financial statements.
Not intended for automated trading decisions or real-time market prediction, or any use whereaccuracy needs to exceed what the reported confidence intervals support.
## Usage
```pythonimport torchimport torch.nn as nnfrom transformers import AutoTokenizer, AutoModel
class MultiTaskDeberta(nn.Module): def __init__(self, model_name, num_classes=3): super().__init__() self.backbone = AutoModel.from_pretrained(model_name) hidden = self.backbone.config.hidden_size self.dropout = nn.Dropout(0.1) self.cls_head = nn.Linear(hidden, num_classes) self.reg_head = nn.Linear(hidden, 1)
def forward(self, input_ids, attention_mask): out = self.backbone(input_ids=input_ids, attention_mask=attention_mask) mask = attention_mask.unsqueeze(-1).float() pooled = (out.last_hidden_state * mask).sum(1) / mask.sum(1).clamp(min=1e-9) pooled = self.dropout(pooled) return self.cls_head(pooled), self.reg_head(pooled).squeeze(-1)
model_id = "ProPrak01/deberta-v3-financial-sentiment"tokenizer = AutoTokenizer.from_pretrained(model_id)model = MultiTaskDeberta("microsoft/deberta-v3-base")model.load_state_dict(torch.load(f"{model_id}/pytorch_model.bin", map_location="cpu"))model.eval()
texts = ["Company reports record profits and strong revenue growth"]enc = tokenizer(texts, padding=True, truncation=True, max_length=128, return_tensors="pt")with torch.no_grad(): cls_logits, reg_score = model(enc["input_ids"], enc["attention_mask"])
label_names = ["negative", "neutral", "positive"]pred_class = label_names[cls_logits.argmax(-1).item()]pred_score = reg_score.item()print(pred_class, pred_score)```
## Reproducibility
Training and eval code is available in the accompanying repository, including the balancedinterleaved sampler and the sanity checks that caught two real training bugs duringdevelopment (a learning-rate-scheduler ordering issue and an AdamW flag that silently corruptedweights on CUDA). Main scripts:
- `06_train_deberta.py` / `06_train_deberta_colab.py` -- multi-task training loop- `08_improve_phrasebank_colab.py` -- PhraseBank-focused continuation run- `07_eval_deberta.py` -- final locked-test-set evaluation with bootstrap CIs
Every number in this card comes from those scripts and is saved to`results/deberta_final_comparison.csv`.
## Comparison to pmatorras/financial-sentiment-analysis
| | This model | pmatorras ||---|---|---|| Backbone | DeBERTa-v3-base, 128K vocab, disentangled attention | FinBERT, BERT-base, 30K vocab, 2019 || PhraseBank accuracy | 87.1% | 95.9% || Twitter accuracy | 89.7% | 83.3% || FiQA accuracy | 86.3% | 81.5% || FiQA MAE / bootstrap CIs | 0.152 (0.131-0.174) | not reported || Regression head | yes | not reported |
## Citation
If you use this model, please cite the underlying datasets: Financial PhraseBank (Malo et al.,2014), Twitter Financial News Sentiment (`zeroshot/twitter-financial-news-sentiment`), and FiQASentiment (`TheFinAI/fiqa-sentiment-classification`), along with the base model, DeBERTa-v3(He et al., 2021).1234567891011121314151617181920212223242526272829303132333435{ "attention_probs_dropout_prob": 0.1, "bos_token_id": null, "dtype": "float32", "eos_token_id": null, "hidden_act": "gelu", "hidden_dropout_prob": 0.1, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-07, "legacy": true, "max_position_embeddings": 512, "max_relative_positions": -1, "model_type": "deberta-v2", "norm_rel_ebd": "layer_norm", "num_attention_heads": 12, "num_hidden_layers": 12, "pad_token_id": 0, "pooler_dropout": 0.0, "pooler_hidden_act": "gelu", "pooler_hidden_size": 768, "pos_att_type": [ "p2c", "c2p" ], "position_biased_input": false, "position_buckets": 256, "relative_attention": true, "share_att_key": true, "tie_word_embeddings": true, "transformers_version": "5.13.1", "type_vocab_size": 0, "vocab_size": 128100}123version https://git-lfs.github.com/spec/v1oid sha256:def1c32e7280e2b606fdb66af9f4004ab21750c2d3ec3c427f542f39c5a8024csize 735425035123456789101112131415161718192021222324{ "add_prefix_space": true, "backend": "tokenizers", "bos_token": "[CLS]", "cls_token": "[CLS]", "do_lower_case": false, "eos_token": "[SEP]", "extra_special_tokens": [ "[PAD]", "[CLS]", "[SEP]" ], "is_local": false, "local_files_only": false, "mask_token": "[MASK]", "model_max_length": 1000000000000000019884624838656, "pad_token": "[PAD]", "sep_token": "[SEP]", "split_by_punct": false, "tokenizer_class": "DebertaV2Tokenizer", "unk_id": 3, "unk_token": "[UNK]", "vocab_type": "spm"}123456789101112131415{ "model_name": "microsoft/deberta-v3-base", "base_checkpoint": "epoch-4 continuation (composite score 0.8664)", "phrasebank_focused_epochs_ran": 3, "starting_phrasebank_f1": 0.8638531284070651, "final_phrasebank_f1": 0.8683640340319556, "final_composite_score": 0.8677716444652193, "hyperparameters": { "learning_rate": 5e-06, "batch_size": 16, "alpha_phrasebank": 1.5, "alpha_twitter": 1.0, "phrasebank_cap_multiplier": 3 }}README.mdAdded+210
config.jsonAdded+35
pytorch_model.binAdded+3
tokenizer.jsonAdded
tokenizer_config.jsonAdded+24
training_meta.jsonAdded+15