#!pip install torchtext==0.8.0 torch==1.7.1 pytorch-lightning==1.2.2 from typing import…
- User
#!pip install torchtext==0.8.0 torch==1.7.1 pytorch-lightning==1.2.2
from typing import List, Dict import torch from pandas import DataFrame from torch.utils.data import Dataset from torch.utils.data.dataset import T_co from transformers import PreTrainedTokenizer import pandas as pd import numpy as np from sklearn import preprocessing def collate_batch(featurized_samples: List[Dict]): input_ids = torch.nn.utils.rnn.pad_sequence( [torch.tensor(x['input_ids']) for x in featurized_samples], batch_first=True)
attention_masks = torch.nn.utils.rnn.pad_sequence( [torch.tensor(x['attention_mask']) for x in featurized_samples], batch_first=True)
batch = {"input_ids": input_ids, "attention_masks": attention_masks, "tokens": [x['tokens'] for x in featurized_samples], "targets": np.array([x['target'] for x in featurized_samples]), "ad_ids": [x['ad_id'] for x in featurized_samples]}
if 'token_type_ids' in featurized_samples[0]: token_type_ids = torch.nn.utils.rnn.pad_sequence( [torch.tensor(x['token_type_ids']) for x in featurized_samples], batch_first=True) batch["token_type_ids"] = token_type_ids
return batch def sample_to_features(sample: pd.Series, tokenizer: PreTrainedTokenizer, label_column: str, max_length=512) -> Dict:
input_text = sample["jobTitle"] + " " + sample["description"]
input_text = sample["description"]
tokenized = tokenizer.encode_plus(input_text, padding=True, max_length=max_length)
featurized_sample = {"input_ids": tokenized["input_ids"], "attention_mask": tokenized["attention_mask"], "tokens": tokenized.encodings[0].tokens, "target": sample[label_column].astype(int), "ad_id": sample["ad_id"]}
if "token_type_ids" in tokenized: featurized_sample["token_type_ids"] = tokenized["token_type_ids"]
return featurized_sample class DKZDataset(Dataset):
def __init__(self, file_path, tokenizer: PreTrainedTokenizer, max_length=512): self.tokenizer: PreTrainedTokenizer = tokenizer self.max_length = max_length
self.data: DataFrame = pd.read_parquet(file_path, engine="pyarrow")[:100].dropna()
label_encoder = preprocessing.LabelEncoder() label_encoder.fit(self.data.dkz) self.data.dkz = label_encoder.transform(self.data.dkz) self.id2label = label_encoder.classes_
def __len__(self): return len(self.data)
def __getitem__(self, index) -> T_co: featurized_sample = sample_to_features(sample=self.data.iloc[index], tokenizer=self.tokenizer, label_column="dkz", max_length=self.max_length) return featurized_sample
def get_num_classes(self): return len(self.data["dkz"].unique()) change this code to consider whole text which contains more than 512 tokens
- Assistant
One approach to handle text with length greater than 512 tokens is to split the text into chunks of a maximum length of 512 tokens and convert each chunk into features separately. Then, concatenate the features of each chunk to form the final features of the text. The following code implements this approach:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.