Views
No views yet



1from collections import OrderedDict
2from transformers import BertPreTrainedModel, BertModel, AutoTokenizer
3import torch
4
5# Mean Pooling - Take attention mask into account for correct averaging
6def mean_pooling(model_output, attention_mask):
7 token_embeddings = model_output #First element of model_output contains all token embeddings
8 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
9 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
10
11# Definition of ESGify class because of custom,sentence-transformers like, mean pooling function and classifier head
12class ESGify_ru(BertPreTrainedModel):
13 """Model for Classification ESG risks from russian language text."""
14
15 def __init__(self,config): #tuning only the head
16 """
17 """
18 super().__init__(config)
19 # Instantiate Parts of model
20 self.bert = BertModel(config,add_pooling_layer=False)
21 self.id2label = config.id2label
22 self.label2id = config.label2id
23 self.classifier = torch.nn.Sequential(OrderedDict([('norm',torch.nn.BatchNorm1d(768)),
24 ('linear',torch.nn.Linear(768,512)),
25 ('act',torch.nn.ReLU()),
26 ('batch_n',torch.nn.BatchNorm1d(512)),
27 ('drop_class', torch.nn.Dropout(0.2)),
28 ('class_l',torch.nn.Linear(512 ,48))]))
29
30
31 def forward(self, input_ids, attention_mask):
32 # Feed input to bert model
33 outputs = self.bert(input_ids=input_ids,
34 attention_mask=attention_mask)
35
36 # mean pooling dataset and eed input to classifier to compute logits
37 logits = self.classifier( mean_pooling(outputs['last_hidden_state'],attention_mask))
38
39 # apply sigmoid
40 logits = 1.0 / (1.0 + torch.exp(-logits))
41 return logits1model = ESGify_ru.from_pretrained('ai-lab/ESGify_ru')
2tokenizer = AutoTokenizer.from_pretrained('ai-lab/ESGify_ru')1texts = ['text1','text2']
2to_model = tokenizer.batch_encode_plus(
3 texts,
4 add_special_tokens=True,
5 max_length=512,
6 return_token_type_ids=False,
7 padding="max_length",
8 truncation=True,
9 return_attention_mask=True,
10 return_tensors='pt',
11 )
12results = model(**to_model)1for i in torch.topk(results, k=3).indices.tolist()[0]:
2 print(f"{model.id2label[i]}: {np.round(results.flatten()[i].item(), 3)}")Labor Relations Management
Employee Health and Safety
Retrenchmentai-forever/ruBert-base model.
Next, we do the domain-adaptation procedure by Mask Language Modeling with using texts of ESG reports.
Finally, we fine-tune our model on 2500 texts with manually annotation of ESG specialists.