Bakalarska_praca/trainingscript.py

55 lines
1.7 KiB
Python
Raw Normal View History

2024-09-26 10:59:38 +00:00
from transformers import T5ForConditionalGeneration, T5Tokenizer, Trainer, TrainingArguments
2024-08-16 14:35:54 +00:00
from datasets import load_dataset
2024-09-26 10:59:38 +00:00
model_name = "t5-base"
2024-08-16 14:35:54 +00:00
tokenizer = T5Tokenizer.from_pretrained(model_name)
2024-09-26 10:59:38 +00:00
model = T5ForConditionalGeneration.from_pretrained(model_name)
2024-08-16 14:35:54 +00:00
def preprocess_function(examples):
2024-09-26 10:59:38 +00:00
before_list = []
after_list = []
for ex in examples["before after"]:
if ex is not None:
splits = ex.split(" before after ")
if len(splits) == 2:
before_list.append(splits[0])
after_list.append(splits[1])
else:
before_list.append(ex)
after_list.append('')
else:
before_list.append('')
after_list.append('')
model_inputs = tokenizer(before_list, padding="max_length", truncation=True)
labels = tokenizer(after_list, padding="max_length", truncation=True)
2024-08-16 14:35:54 +00:00
model_inputs["labels"] = labels["input_ids"]
return model_inputs
2024-09-26 10:59:38 +00:00
dataset = load_dataset("csv", data_files={"train": "converted.csv"}, delimiter=" ", column_names=["before after"])
tokenized_datasets = dataset.map(preprocess_function, batched=True)
2024-08-16 14:35:54 +00:00
training_args = TrainingArguments(
2024-09-26 10:59:38 +00:00
output_dir="./results1",
evaluation_strategy="epoch",
save_strategy="epoch",
2024-08-16 14:35:54 +00:00
learning_rate=2e-5,
2024-09-26 10:59:38 +00:00
per_device_train_batch_size=64,
per_device_eval_batch_size=64,
num_train_epochs=1,
2024-08-16 14:35:54 +00:00
weight_decay=0.01,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
2024-09-26 10:59:38 +00:00
tokenizer=tokenizer,
2024-08-16 14:35:54 +00:00
)
2024-09-26 10:59:38 +00:00
trainer.train()
model.save_pretrained("T5Autocorrection")
tokenizer.save_pretrained("T5TokenizerAutocorrection")