Compare commits

...

4 Commits

Author SHA1 Message Date
wangobango
962ca45b2c final 2021-06-22 17:16:57 +02:00
wangobango
43dbf81d83 change 2021-06-22 14:03:36 +02:00
wangobango
023a4e4361 progress 2021-06-20 22:05:07 +02:00
wangobango
dbadedfc1c w123 2021-06-20 19:42:14 +02:00
4 changed files with 10606 additions and 0 deletions

5272
dev-0/out.tsv Normal file

File diff suppressed because it is too large Load Diff

92
generate.py Normal file
View File

@ -0,0 +1,92 @@
import pandas as pd
from transformers import BertTokenizer, AdamW, AutoModelForSequenceClassification
import torch
import matplotlib.pyplot as plt
from torch.utils.data import TensorDataset, DataLoader, RandomSampler
import torch.nn as nn
from sklearn.utils.class_weight import compute_class_weight
import numpy as np
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score, f1_score
from transformers import BertTokenizerFast, BertForSequenceClassification
from transformers import Trainer, TrainingArguments
import csv
class Dataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {k: torch.tensor(v[idx]) for k, v in self.encodings.items()}
item["labels"] = torch.tensor([self.labels[idx]])
return item
def __len__(self):
return len(self.labels)
def save_tsv_result(path, data):
with open(path, "w") as save:
writer = csv.writer(save, delimiter='\t', lineterminator='\n')
for value in [str(x) for x in data]:
writer.writerow([value])
def predictions_for_set(inputs, masks):
predictions = []
with torch.no_grad():
batch_size = 60
for i in range(0, len(inputs), batch_size):
preds = model(inputs[i: i + batch_size].to(device),
masks[i: i + batch_size].to(device))
preds = preds.logits.detach().cpu().numpy()
preds = np.argmax(preds, axis=1)
predictions += preds.tolist()
return predictions
device = torch.device('cuda')
# train_texts = \
# pd.read_csv('train/in.tsv.xz', compression='xz', sep='\t',
# header=None, error_bad_lines=False, quoting=3)[0].tolist()
# train_labels = pd.read_csv(
# 'train/expected.tsv', sep='\t', header=None, quoting=3)[0].tolist()
dev_texts = pd.read_csv('dev-0/in.tsv.xz', compression='xz',
sep='\t', header=None, quoting=3)[0].tolist()
dev_labels = pd.read_csv('dev-0/expected.tsv', sep='\t',
header=None, quoting=3)[0].tolist()
test_texts = pd.read_csv('test-A/in.tsv.xz', compression='xz', sep='\t',
header=None, error_bad_lines=False, quoting=3)[0].tolist()
model_name = "bert-base-uncased-pretrained"
model = BertForSequenceClassification.from_pretrained(
model_name, num_labels=len(pd.unique(dev_labels))).to(device)
max_length = 512
tokenizer = BertTokenizerFast.from_pretrained(model_name, do_lower_case=True)
# model.load_pretrained(model_path)
# tokenizer.load_pretrainded(model_path)
# train_encodings = tokenizer(
# train_texts, truncation=True, padding=True, max_length=max_length)
valid_encodings = tokenizer(
dev_texts, truncation=True, padding=True, max_length=max_length)
test_encodings = tokenizer(
test_texts, truncation=True, padding=True, max_length=max_length)
input_ids_val = torch.tensor(valid_encodings.data['input_ids'])
attention_mask_val = torch.tensor(valid_encodings.data['attention_mask'])
input_ids_test = torch.tensor(test_encodings.data['input_ids'])
attention_mask_test = torch.tensor(test_encodings.data['attention_mask'])
predictions = predictions_for_set(input_ids_val, attention_mask_val)
print("Predictions for dev set:")
print(classification_report(dev_labels, predictions))
print(accuracy_score(dev_labels, predictions))
print(f1_score(dev_labels, predictions))
save_tsv_result("dev-0/out.tsv", predictions)
predictions = predictions_for_set(input_ids_test, attention_mask_test)
save_tsv_result("test-A/out.tsv", predictions)

90
main.py Normal file
View File

@ -0,0 +1,90 @@
import torch
from transformers.file_utils import is_torch_available
from transformers import BertTokenizerFast, BertForSequenceClassification
from transformers import Trainer, TrainingArguments
import numpy as np
import random
from sklearn.metrics import accuracy_score
import pandas as pd
class Dataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {k: torch.tensor(v[idx]) for k, v in self.encodings.items()}
item["labels"] = torch.tensor([self.labels[idx]])
return item
def __len__(self):
return len(self.labels)
def set_seed(seed: int):
random.seed(seed)
np.random.seed(seed)
if is_torch_available():
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def compute_metrics(pred):
labels = pred.label_ids
preds = pred.predictions.argmax(-1)
acc = accuracy_score(labels, preds)
return {
'accuracy': acc,
}
set_seed(1)
train_texts = \
pd.read_csv('train/in.tsv.xz', compression='xz', sep='\t', header=None, error_bad_lines=False, quoting=3)[0].tolist()[:25000]
train_labels = pd.read_csv('train/expected.tsv', sep='\t', header=None, quoting=3)[0].tolist()[:25000]
dev_texts = pd.read_csv('dev-0/in.tsv.xz', compression='xz', sep='\t', header=None, quoting=3)[0].tolist()[:1000]
dev_labels = pd.read_csv('dev-0/expected.tsv', sep='\t', header=None, quoting=3)[0].tolist()[:1000]
# test_texts = pd.read_table('test-A/in.tsv.xz', compression='xz', sep='\t', header=None, quoting=3)
model_name = "bert-base-uncased"
max_length = 25
tokenizer = BertTokenizerFast.from_pretrained(model_name, do_lower_case=True)
train_encodings = tokenizer(train_texts, truncation=True, padding=True, max_length=max_length)
valid_encodings = tokenizer(dev_texts, truncation=True, padding=True, max_length=max_length)
train_dataset = Dataset(train_encodings, train_labels)
valid_dataset = Dataset(valid_encodings, dev_labels)
model = BertForSequenceClassification.from_pretrained(
model_name, num_labels=len(pd.unique(train_labels))).to("cuda")
training_args = TrainingArguments(
output_dir='./results', # output directory
num_train_epochs=1, # total number of training epochs
per_device_train_batch_size=60, # batch size per device during training
per_device_eval_batch_size=60, # batch size for evaluation
warmup_steps=100, # number of warmup steps for learning rate scheduler
weight_decay=0.01, # strength of weight decay
logging_dir='./logs', # directory for storing logs
load_best_model_at_end=True, # load the best model when finished training (default metric is loss)
# but you can specify `metric_for_best_model` argument to change to accuracy or other metric
logging_steps=200, # log & save weights each logging_steps
evaluation_strategy="steps", # evaluate each `logging_steps`
)
trainer = Trainer(
model=model, # the instantiated Transformers model to be trained
args=training_args, # training arguments, defined above
train_dataset=train_dataset, # training dataset
eval_dataset=valid_dataset, # evaluation dataset
compute_metrics=compute_metrics, # the callback that computes metrics of interest
)
trainer.train()
trainer.evaluate()
model_path = "bert-base-uncased-pretrained"
model.save_pretrained(model_path)
tokenizer.save_pretrained(model_path)

5152
test-A/out.tsv Normal file

File diff suppressed because it is too large Load Diff