Views
No views yet
pip install torch transformers1import torch
2from transformers import BertTokenizer, BertModel
3import torch.nn as nn
4
5# Load the tokenizer
6tokenizer = BertTokenizer.from_pretrained('bert-base-german-cased')
7
8# Define the Multi-Task Model
9class MultiTaskModel(nn.Module):
10 def __init__(self):
11 super(MultiTaskModel, self).__init__()
12 self.bert = BertModel.from_pretrained('bert-base-german-cased')
13 self.dropout = nn.Dropout(0.3)
14 self.fc_fake_news = nn.Linear(self.bert.config.hidden_size, 1)
15 self.fc_hate_speech = nn.Linear(self.bert.config.hidden_size, 1)
16 self.fc_toxicity = nn.Linear(self.bert.config.hidden_size, 1)
17
18 def forward(self, input_ids, attention_mask):
19 outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask)
20 pooled_output = outputs[1] # Get the pooled output
21 pooled_output = self.dropout(pooled_output)
22 fake_news_output = self.fc_fake_news(pooled_output)
23 hate_speech_output = self.fc_hate_speech(pooled_output)
24 toxicity_output = self.fc_toxicity(pooled_output)
25 return fake_news_output, hate_speech_output, toxicity_output
26
27# Function to load the model
28def load_model(device):
29 model = MultiTaskModel().to(device)
30 model.load_state_dict(torch.load('path_to_your_model.pt'))
31 model.eval()
32 return model
33
34# Example Usage
35device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
36model = load_model(device)
37
38text_input = "Mir fallen nur Steuervorteile durch Gender Pay gap ein."
39encoding = tokenizer(text_input, return_tensors='pt', padding='max_length', truncation=True, max_length=128)
40
41input_ids = encoding['input_ids'].to(device)
42attention_mask = encoding['attention_mask'].to(device)
43
44# Predict
45with torch.no_grad():
46 outputs_fake_news, outputs_hate_speech, outputs_toxicity = model(input_ids, attention_mask)
47 preds_fake_news = torch.sigmoid(outputs_fake_news).squeeze().round().cpu().numpy()
48 preds_hate_speech = torch.sigmoid(outputs_hate_speech).squeeze().round().cpu().numpy()
49 preds_toxicity = torch.sigmoid(outputs_toxicity).squeeze().round().cpu().numpy()
50
51print(f"Fake News Prediction: {preds_fake_news}")
52print(f"Hate Speech Prediction: {preds_hate_speech}")
53print(f"Toxicity Prediction: {preds_toxicity}")1@article{example2025,
2 title={Multi-Task BERT Model for Fake News, Hate Speech, and Toxicity Detection},
3 author={Shivang Sinha},
4 year={2025}
5}