Download module_toxicdetection/src/dataset.py from orcheflow/flow-moderation: direct link, hf CLI and curl.
- Browser
- Download file 1.56 kB
-
https://huggingface.co/orcheflow/flow-moderation/resolve/main/module_toxicdetection/src/dataset.py
- Command line
-
hf download hf://orcheflow/flow-moderation/module_toxicdetection/src/dataset.py
-
curl -L -o dataset.py https://huggingface.co/orcheflow/flow-moderation/resolve/main/module_toxicdetection/src/dataset.py
1.56 kB
| import torch | |
| from torch.utils.data import Dataset | |
| import pandas as pd | |
| class ToxicDataset(Dataset): | |
| def __init__(self, data_path, tokenizer, max_len=128, split=None, random_state=42): | |
| self.tokenizer = tokenizer | |
| self.max_len = max_len | |
| df = pd.read_csv(data_path, sep='\t') | |
| df = df.dropna(subset=['document', 'label']) | |
| if split: | |
| from sklearn.model_selection import train_test_split | |
| train_df, val_df = train_test_split(df, test_size=0.1, random_state=random_state, stratify=df['label']) | |
| if split == 'train': | |
| self.data = train_df.reset_index(drop=True) | |
| else: | |
| self.data = val_df.reset_index(drop=True) | |
| else: | |
| self.data = df.reset_index(drop=True) | |
| def __len__(self): | |
| return len(self.data) | |
| def __getitem__(self, idx): | |
| text = str(self.data.loc[idx, 'document']) | |
| label = int(self.data.loc[idx, 'label']) | |
| encoding = self.tokenizer.encode_plus( | |
| text, | |
| add_special_tokens=True, | |
| max_length=self.max_len, | |
| return_token_type_ids=False, | |
| padding='max_length', | |
| truncation=True, | |
| return_attention_mask=True, | |
| return_tensors='pt', | |
| ) | |
| return { | |
| 'input_ids': encoding['input_ids'].flatten(), | |
| 'attention_mask': encoding['attention_mask'].flatten(), | |
| 'labels': torch.tensor(label, dtype=torch.long) | |
| } |