paranormal-or-skeptic-ISI-p.../main.py

102 lines
2.9 KiB
Python
Raw Normal View History

2021-06-21 21:46:10 +02:00
import os
import sys
from transformers import AutoTokenizer, AutoModelForSequenceClassification, TrainingArguments, Trainer
import torch
2021-06-22 18:13:51 +02:00
import random
2021-06-21 21:46:10 +02:00
2021-06-22 20:27:03 +02:00
IN_FILE_NAME = "in.tsv"
2021-06-21 21:46:10 +02:00
OUT_FILE_NAME = "out.tsv"
TRAIN_PATH = "train"
EXP_FILE_NAME = "expected.tsv"
FILE_SEP = "\t"
2021-06-22 15:55:04 +02:00
# PT_MODEL_NAME = "bert-base-cased"
PT_MODEL_NAME = "roberta-base"
2021-06-22 20:27:03 +02:00
MODEL_OUT_NAME = "./model.tr"
2021-06-21 21:46:10 +02:00
class CustomDataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx])
for key, val in self.encodings.items()}
item['labels'] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
def main(dirnames):
print("Reading train data...")
train_set_features = get_tsv_data(os.path.join(
2021-06-22 18:13:51 +02:00
TRAIN_PATH, IN_FILE_NAME), compressed=True)
2021-06-21 21:46:10 +02:00
train_set_labels = get_tsv_data(os.path.join(
2021-06-22 18:13:51 +02:00
TRAIN_PATH, EXP_FILE_NAME), compressed=True)
2021-06-21 21:46:10 +02:00
print("Reading input data...")
in_sets = []
for d in dirnames:
print(f"\tReading dir: {d}...")
in_sets.append(get_tsv_data(
2021-06-22 18:13:51 +02:00
os.path.join(d, IN_FILE_NAME), compressed=True))
train_data = list(zip(train_set_features, train_set_labels))
train_data = random.sample(train_data, 15000)
2021-06-21 21:46:10 +02:00
2021-06-22 20:27:03 +02:00
mname = PT_MODEL_NAME
if os.path.exists(MODEL_OUT_NAME):
mname = MODEL_OUT_NAME
tokenizer = AutoTokenizer.from_pretrained(mname)
2021-06-21 21:46:10 +02:00
model = AutoModelForSequenceClassification.from_pretrained(
2021-06-22 20:27:03 +02:00
mname, num_labels=2)
2021-06-21 21:46:10 +02:00
train_set_enc = tokenizer(
2021-06-22 18:13:51 +02:00
[text[0] for text in train_data], truncation=True, padding=True)
ds = CustomDataset(
train_set_enc, [int(text[1]) for text in train_data])
2021-06-22 20:27:03 +02:00
device = torch.device(
'cuda') if torch.cuda.is_available() else torch.device('cpu')
2021-06-22 16:41:34 +02:00
model.to(device)
2021-06-22 18:13:51 +02:00
2021-06-21 21:46:10 +02:00
trainer = Trainer(
model=model,
2021-06-22 16:41:34 +02:00
args=TrainingArguments("model"),
2021-06-22 18:13:51 +02:00
train_dataset=ds
2021-06-21 21:46:10 +02:00
)
2021-06-22 18:13:51 +02:00
2021-06-22 16:41:34 +02:00
print("Starting training...")
2021-06-22 18:13:51 +02:00
2021-06-21 21:46:10 +02:00
trainer.train()
2021-06-22 20:27:03 +02:00
trainer.save_model(MODEL_OUT_NAME)
2021-06-22 18:13:51 +02:00
print("Predicting outputs...")
2021-06-21 21:46:10 +02:00
for i in range(len(in_sets)):
2021-06-22 18:13:51 +02:00
p_in = os.path.join(dirnames[i], IN_FILE_NAME)
p_out = os.path.join(dirnames[i], OUT_FILE_NAME)
with open(p_out, "w") as f:
2021-06-21 21:46:10 +02:00
print(
2021-06-22 18:13:51 +02:00
f"\tPredicting for: {p_in}...")
f.write('\n'.join(trainer.predict(in_sets[i])))
print(f"Saved predictions to file: {p_out}")
def get_tsv_data(filename: str, compressed=False):
2021-06-22 20:27:03 +02:00
check_path(filename=filename)
with open(filename) as f:
return f.readlines()
2021-06-21 21:46:10 +02:00
def check_path(filename: str):
if not os.path.exists(filename):
raise Exception(f"Path {filename} does not exist!")
if __name__ == "__main__":
if len(sys.argv) < 2:
raise Exception("Name of working dir not specified!")
main(sys.argv[1:])