GE-Lab commited on
Commit
c9d0005
·
verified ·
1 Parent(s): 42fe189

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +152 -3
README.md CHANGED
@@ -1,3 +1,152 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language: en
4
+ library_name: transformers
5
+ tags:
6
+ - sdgs
7
+ - sustainability
8
+ - multi-label-classification
9
+ - text-classification
10
+ - luke
11
+ datasets:
12
+ - osdg/osdg-community
13
+ - SDG-AI-Lab/sdgi_corpus
14
+ pipeline_tag: text-classification
15
+ ---
16
+
17
+ # SDG Classifier: A Fine-Tuned LUKE Model for Multi-Label SDG Classification
18
+
19
+ This repository contains the pre-trained model weights (`best_model.pt`) for the paper: **"Bridging the Sustainable Development Goals: A Multi-Label Text Classification Approach for Mapping and Visualizing Nexuses in Sustainability Research"**.
20
+
21
+ ➡️ **GitHub Repository (Code):** [Insert Link to your GitHub Repository Here]
22
+ ➡️ **Paper Link:** [Link to Published Paper will be added upon publication]
23
+
24
+ ## 📝 Model Description
25
+
26
+ This model is a fine-tuned version of `studio-ousia/luke-large-lite` for multi-label text classification of the 17 UN Sustainable Development Goals (SDGs). It has been trained on a uniquely diverse, multi-sectoral, and multilingual corpus designed to achieve high generalization performance across various domains (academic, policy, civil society, etc.).
27
+
28
+ The model takes a text input (up to 512 tokens) and outputs a probability score for each of the 17 SDGs, indicating the relevance of the text to each goal.
29
+
30
+ ## 🚀 How to Use
31
+
32
+ This model was trained with a custom classification head in PyTorch. To use it, you need to define the model architecture first and then load the downloaded weights (`best_model.pt`).
33
+
34
+ Below is a complete example of how to load the model and perform a prediction.
35
+
36
+ ```python
37
+ import torch
38
+ from torch import nn
39
+ from transformers import AutoTokenizer, AutoModel
40
+ from huggingface_hub import hf_hub_download
41
+ from pathlib import Path
42
+
43
+ # --- 1. Define the Model Architecture ---
44
+ # This class must match the architecture used during training.
45
+ # You can copy this class from the original training script.
46
+ class SDGClassifier(nn.Module):
47
+ def __init__(self, model_path, pooler_dropout, class_number):
48
+ super(SDGClassifier, self).__init__()
49
+ self.bert = AutoModel.from_pretrained(model_path)
50
+ self.dropout = nn.Dropout(pooler_dropout)
51
+ self.pooler = nn.Sequential(nn.Linear(in_features=self.bert.config.hidden_size, out_features=self.bert.config.hidden_size))
52
+ self.tanh = nn.Tanh()
53
+ self.cls = nn.Linear(in_features=self.bert.config.hidden_size, out_features=class_number)
54
+
55
+ def forward(self, input_ids, attention_mask, token_type_ids, position, labels):
56
+ # Note: 'position' and 'labels' are dummy inputs required by the forward signature,
57
+ # but are not used for inference if labels are not provided.
58
+ bert_output = self.bert(input_ids, attention_mask, token_type_ids=token_type_ids, output_attentions=True, output_hidden_states=True)
59
+ average_hidden_state = (bert_output.last_hidden_state * attention_mask.unsqueeze(-1)).sum(1) / attention_mask.sum(1, keepdim=True)
60
+ pooler_output = self.tanh(self.pooler(self.dropout(average_hidden_state)))
61
+ logits = self.cls(pooler_output)
62
+ return logits, average_hidden_state, bert_output.attentions
63
+
64
+ # --- 2. Setup and Load Model ---
65
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
66
+
67
+ # Model configuration
68
+ BASE_MODEL = 'studio-ousia/luke-large-lite'
69
+ NUM_CLASSES = 17
70
+ DROPOUT_RATE = 0.26 # This is the optimized dropout rate from the paper's training
71
+
72
+ # Instantiate the model
73
+ model = SDGClassifier(model_path=BASE_MODEL, pooler_dropout=DROPOUT_RATE, class_number=NUM_CLASSES).to(device)
74
+ model.eval() # Set to evaluation mode
75
+
76
+ # Download the fine-tuned weights from this Hub
77
+ model_weights_path = hf_hub_download(
78
+ repo_id="GE-Lab/SDGs-classifier",
79
+ filename="best_model.pt"
80
+ )
81
+
82
+ # Load the weights into the model
83
+ model.load_state_dict(torch.load(model_weights_path, map_location=device))
84
+
85
+ print("Model loaded successfully!")
86
+
87
+ # --- 3. Prepare Input ---
88
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
89
+ text = "Our research focuses on renewable energy solutions to combat climate change and ensure a sustainable future for all."
90
+
91
+ inputs = tokenizer.encode_plus(
92
+ text,
93
+ None,
94
+ add_special_tokens=True,
95
+ max_length=512,
96
+ padding='max_length',
97
+ return_token_type_ids=True,
98
+ truncation=True,
99
+ return_tensors='pt'
100
+ ).to(device)
101
+
102
+ # The model's forward pass requires these additional dummy inputs
103
+ inputs['position'] = torch.arange(0, inputs['input_ids'].shape[1]).unsqueeze(0).to(device)
104
+ inputs['labels'] = torch.zeros(1, NUM_CLASSES).to(device) # Dummy labels for inference
105
+
106
+ # --- 4. Get Predictions ---
107
+ with torch.no_grad():
108
+ logits, _, _ = model(**inputs)
109
+ probabilities = torch.sigmoid(logits).cpu().numpy()[0]
110
+ predictions = (probabilities > 0.5).astype(int)
111
+
112
+ # --- 5. Interpret the Results ---
113
+ goal_contents = ['Goal 1: No Poverty','Goal 2: Zero Hunger','Goal 3: Good Health and Well-being','Goal 4: Quality Education','Goal 5: Gender Equality','Goal 6: Clean Water and Sanitation','Goal 7: Affordable and Clean Energy','Goal 8: Decent Work and Economic Growth','Goal 9: Industry, Innovation and Infrastructure','Goal 10: Reduced Inequalities','Goal 11: Sustainable Cities and Communities','Goal 12: Responsible Consumption and Production','Goal 13: Climate Action','Goal 14: Life Below Water','Goal 15: Life on Land','Goal 16: Peace, Justice and Strong Institutions','Goal 17: Partnerships for the Goals']
114
+
115
+ print(f"\nText: '{text}'")
116
+ print("\n--- Predicted SDGs (Threshold > 0.5) ---")
117
+ predicted_goals = [goal_contents[i] for i, pred in enumerate(predictions) if pred == 1]
118
+ if predicted_goals:
119
+ for goal in predicted_goals:
120
+ print(goal)
121
+ else:
122
+ print("No SDGs detected with a probability > 0.5")
123
+
124
+ print("\n--- All SDG Probabilities ---")
125
+ for i, prob in enumerate(probabilities):
126
+ print(f"{goal_contents[i]:<55}: {prob:.2%}")
127
+
128
+ ```
129
+
130
+ ## 📈 Training and Evaluation
131
+
132
+ ### Training Data
133
+ The model was trained on a novel, heterogeneous corpus of 23,969 multi-labeled documents from 11 diverse sources, including government, academia, industry, and civil society, with some sources translated from Japanese. This approach was designed to address the "interpretive diversity" of SDG-related language.
134
+
135
+ For full details on reconstructing the training corpus, please refer to **Supplementary Information S4** in our paper.
136
+
137
+ ### Evaluation
138
+ This model was selected based on its superior generalization performance (especially recall) on external datasets like the OSDG Community Dataset and the SDGi Corpus. On a human-coded sample of scientific articles, the model achieved a macro-averaged **F1-score of 0.623**. For a full breakdown of performance metrics, please see the paper.
139
+
140
+ ## 📜 Citation
141
+
142
+ If you use this model in your research, please cite our paper:
143
+
144
+ ```bibtex
145
+ @article{Miyashita2025,
146
+ author = {Naoto Miyashita and Takanori Matsui and Chihiro Haga and Naoki Masuhara and Shun Kawakubo},
147
+ title = {Bridging the Sustainable Development Goals: A Multi-Label Text Classification Approach for Mapping and Visualizing Nexuses in Sustainability Research},
148
+ journal = {Sustainability Science},
149
+ year = {2025},
150
+ % TODO: Add Volume, Pages, DOI upon publication
151
+ }
152
+ ```