Update README.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199---library_name: transformerstags: []---# Model Card for Model ID<!-- Provide a quick summary of what the model is/does. -->## Model Details### Model Description<!-- Provide a longer summary of what this model is. -->This is the model card of a π€ transformers model that has been pushed on the Hub. This model card has been automatically generated.- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]### Model Sources [optional]<!-- Provide the basic links for the model. -->- **Repository:** [More Information Needed]- **Paper [optional]:** [More Information Needed]- **Demo [optional]:** [More Information Needed]## Uses<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->### Direct Use<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->[More Information Needed]### Downstream Use [optional]<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->[More Information Needed]### Out-of-Scope Use<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->[More Information Needed]## Bias, Risks, and Limitations<!-- This section is meant to convey both technical and sociotechnical limitations. -->[More Information Needed]### Recommendations<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.## How to Get Started with the ModelUse the code below to get started with the model.[More Information Needed]## Training Details### Training Data<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->[More Information Needed]### Training Procedure<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->#### Preprocessing [optional][More Information Needed]#### Training Hyperparameters- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->#### Speeds, Sizes, Times [optional]<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->[More Information Needed]## Evaluation<!-- This section describes the evaluation protocols and provides the results. -->### Testing Data, Factors & Metrics#### Testing Data<!-- This should link to a Dataset Card if possible. -->[More Information Needed]#### Factors<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->[More Information Needed]#### Metrics<!-- These are the evaluation metrics being used, ideally with a description of why. -->[More Information Needed]### Results[More Information Needed]#### Summary## Model Examination [optional]<!-- Relevant interpretability work for the model goes here -->[More Information Needed]## Environmental Impact<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).- **Hardware Type:** [More Information Needed]- **Hours used:** [More Information Needed]- **Cloud Provider:** [More Information Needed]- **Compute Region:** [More Information Needed]- **Carbon Emitted:** [More Information Needed]## Technical Specifications [optional]### Model Architecture and Objective[More Information Needed]### Compute Infrastructure[More Information Needed]#### Hardware[More Information Needed]#### Software[More Information Needed]## Citation [optional]<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->**BibTeX:**[More Information Needed]**APA:**[More Information Needed]## Glossary [optional]<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->[More Information Needed]## More Information [optional][More Information Needed]## Model Card Authors [optional][More Information Needed]## Model Card Contact[More Information Needed]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286------language: enlicense: mittags:- text-classification- occupational-health-safety- bert- distilbert- severity-prediction- workplace-incidents- nlpdatasets:- osha-incident-reportsmetrics:- f1- accuracy- roc-auc---# OHS Severity ClassifierDistilBERT fine-tuned for workplace incident severity classification.Developed as part of MSc Computer Science research at Northumbria University (2024).**Research paper:** *Predicting Workplace Incident Severity Using BERT-Based NLP βProbabilistic Classification and SHAP Analysis for UK OHS Decision Support*arXiv: submission in progress β link will be added on publication**Code repository:** github.com/stuartclark-ml/incident-severity-bert---## Model DescriptionThis model classifies workplace incident descriptions into five severitycategories based on time-loss incapacitation, aligned with UK RIDDOR reportingthresholds and HSE guidance frameworks.The model takes a free-text incident narrative as input and outputs aprobability distribution across five severity classes. It is designed as a**decision-support tool in a human-in-the-loop workflow** β not a standaloneclassifier. The probability distribution and SHAP token attribution togetherallow a safety professional to assess confidence and inspect the model'sreasoning before acting on a prediction.---## Severity Classification Framework| Class | Label | Condition | UK OHS Alignment ||---|---|---|---|| 0 | None | 0 days lost | Below RIDDOR recording threshold || 1 | Minor | 1-2 days lost | Below mandatory internal recording threshold || 2 | Moderate | 3-7 days lost | Mandatory internal recording under RIDDOR || 3 | Severe | 8-28 days lost | Statutory reporting to HSE required || 4 | Major | 29+ days lost | Long-term incapacitation β triggers separate management and insurance obligations |Time-loss days used as severity proxy. This metric is compatible with bothUS OSHA and UK RIDDOR reporting frameworks β the primary justification forusing OSHA data to develop a UK-applicable tool.---## Intended Uses**Appropriate uses:**- Triage support for high-volume incident report queues in health and socialcare settings- Research into NLP-based severity prediction for occupational safety- Demonstration of BERT-based classification with SHAP explainability insafety-critical domains- Educational exploration of model bias in imbalanced safety datasets**Not appropriate for:**- Standalone severity determination without human review- UK RIDDOR reportability decisions β the model was not trained on RIDDOR data- Industries outside health and social care β trained on H&C sector data only- Definitive clinical or legal severity assessments---## Training Data**Dataset:** US OSHA Incident Reports (2024 release) β Health and Care sector subset**Size:** 181,586 records after preprocessing- Full OSHA dataset: 751,770 records- H&C sector subset: 193,512 records- COVID-19 records removed: 10,016 (to prevent rare global event bias)- Fatality records removed: 5 (statistically insignificant, severe class imbalance)**Features used:**- `new_nar_what_happened` β what happened during the incident- `new_nar_before_incident` β what the employee was doing beforehand- `new_nar_object_substance` β the object or substance causing harm- `size` β organisational size (1=<20, 2=20-249, 3=250+ employees)**Class distribution:** Heavily imbalanced β dominated by None class, reflectingreal-world incident distribution (Heinrich's Triangle). Weighted loss functionapplied during training (up to 4.05x penalty for Minor class).---## Performance### Overall Metrics| Metric | Random Forest (baseline) | DistilBERT | ModernBERT ||---|---|---|---|| Weighted Avg F1 | 0.55 | **0.58** | 0.58 || Macro ROC AUC | 0.77 | 0.77 | **0.78** || Overall Accuracy | 0.52 | **0.55** | 0.54 || Log Loss | 1.29 | **1.07** | 1.10 |DistilBERT selected as the deployment model: equal F1 to ModernBERT,highest accuracy, lowest log loss, and smaller model size.### Per-Class Metrics β DistilBERT| Class | Precision | Recall | F1 ||---|---|---|---|| None | 0.94 | 0.71 | 0.81 || Minor | 0.16 | 0.14 | 0.15 || Moderate | 0.19 | 0.25 | 0.22 || Severe | 0.21 | 0.20 | 0.20 || Major | 0.37 | **0.60** | 0.46 |**Key finding:** 0.60 recall on Major (highest-severity) incidents makes themodel useful for prioritisation β catching 60% of the most serious incidentsfor urgent human review β despite poor performance on the middle classes.---## Critical Findings from SHAP AnalysisSHAP token attribution was applied to DistilBERT to inspect the model'slearned logic. This revealed two significant issues that any user of thismodel must understand:### 1. Needlestick Blind Spot**99.25% of needlestick injuries in the training dataset are labelled None.**The model learned this spurious correlation and systematically classifiesneedlestick injuries as None severity β regardless of their actualconsequences. In clinical practice needlestick injuries can result inbloodborne pathogen exposure with serious long-term health consequences.**Mitigation:** Any incident narrative containing needle-related terms(`needle`, `needlestick`, `lancet`, `sharps`, `puncture`) should beflagged for mandatory human review and not relied upon for model output.### 2. Organisational Size BiasThe `size` feature introduced a spurious correlation: small organisations(size=1, <20 employees) are associated with None class at 50.8%.**Mitigation:** Model predictions for incidents from small organisationsshould be treated with additional caution. Future implementations shouldconsider removing the size feature unless a more balanced dataset is available.### Positive Finding β No Significant US Linguistic BiasSHAP global feature importance analysis found no significant US-centriclinguistic bias in the top predictive features. The model relied onuniversal medical and safety terminology rather than US-specific language,supporting its tentative use as a UK proxy tool. However, regulatory andoperational differences between US and UK health and social care systemsmean direct comparison with UK standards still requires caution.---## Limitations- **Jurisdiction:** Trained on US OSHA data. UK RIDDOR performance notcharacterised. Time-loss metric provides a compatibility bridge but doesnot eliminate cross-jurisdictional differences.- **Industry:** Health and social care only. Performance on other sectorsis unknown and likely poor.- **Minority classes:** Minor, Moderate, and Severe classes perform poorly(F1 0.15-0.22). Narratives for these classes are textually indistinct βa fundamental data limitation not resolvable by model architecture alone.- **Correlation not causation:** SHAP values reflect learned correlationsin the training data. They provide interpretations, not causal explanations.- **Static training data:** Model accuracy will degrade over time as incidentpatterns and safety language evolve. Continuous retraining would be requiredfor production deployment.- **Fatalities excluded:** Insufficient fatality cases in the dataset (5 records)for reliable modelling.---## How to Use```pythonfrom transformers import AutoTokenizer, AutoModelForSequenceClassificationimport torchmodel_name = "stuSterfc/ohs-severity-classifier"tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForSequenceClassification.from_pretrained(model_name)labels = ["None", "Minor", "Moderate", "Severe", "Major"]def predict_severity(narrative: str, org_size: str = "Large") -> dict:# Format input to match training structuretext = f"Organisation size: {org_size}. [SEP] {narrative}"inputs = tokenizer(text,return_tensors="pt",truncation=True,max_length=512,padding=True)with torch.no_grad():outputs = model(**inputs)probs = torch.softmax(outputs.logits, dim=1).squeeze().tolist()return {"probabilities": {label: round(prob, 4)for label, prob in zip(labels, probs)},"predicted_class": labels[probs.index(max(probs))],"confidence": round(max(probs), 4)}# Exampleresult = predict_severity("Employee was assisting patient transfer from bed to wheelchair. ""Felt sharp pain in lower back. Unable to complete shift.",org_size="Large")print(result)# IMPORTANT: Check for needlestick blind spotneedle_terms = ["needle", "needlestick", "lancet", "sharps", "puncture"]if any(term in narrative.lower() for term in needle_terms):print("WARNING: Needle-related incident detected. ""Model has known blind spot β refer for human review.")```---## Input FormatThe model was trained on concatenated narratives with an organisationalsize prefix, separated by `[SEP]` tokens:```Organisation size: {size}. [SEP] {what_happened} [SEP] {before_incident} [SEP] {object_substance}```At minimum, provide the `what_happened` narrative. Include org size if known.The `[SEP]` separator is important β it matches the training format.**Organisation size values:** Small (<20), Medium (20-249), Large (250+)---## Training Details- **Base model:** `distilbert-base-cased`- **Framework:** HuggingFace Transformers- **Fine-tuning:** HuggingFace Trainer API- **Hyperparameter optimisation:** Optuna- **Class imbalance handling:** Weighted loss function (inverse class frequency)- **Training data split:** Standard train/validation/test split- **Hardware:** [GPU details if you have them]---## Citation*Citation will be added when arXiv preprint is published.*---## About the AuthorStuart Clark β MSc Computer Science (Distinction), Northumbria University 2024.NEBOSH National Diploma. 14 years occupational health and safety consulting.GitHub: github.com/stuartclark-ml[More Information Needed]
README.md+221-134