challenging-america-word-ga.../run.py

116 lines
3.6 KiB
Python
Raw Permalink Normal View History

2022-04-03 18:44:40 +02:00
from nltk.tokenize import word_tokenize
from nltk import trigrams
from collections import defaultdict, Counter
import pandas as pd
import csv
2022-04-10 21:17:55 +02:00
class GapPredictor:
def __init__(self, alpha):
self.model = defaultdict(lambda: defaultdict(lambda: 0))
self.alpha = alpha
self.vocab = set()
self.DEFAULT_PREDICTION = "the:0.2 be:0.2 to:0.2 of:0.1 and:0.1 a:0.1 :0.1"
@staticmethod
def preprocess_text(text):
text = text.lower().replace("-\\n", "").replace("\\n", " ")
return text
@staticmethod
def _prepare_train_data():
data = pd.read_csv(
"train/in.tsv.xz",
sep="\t",
error_bad_lines=False,
warn_bad_lines=False,
header=None,
quoting=csv.QUOTE_NONE,
nrows=90000,
)
train_labels = pd.read_csv(
"train/expected.tsv",
sep="\t",
error_bad_lines=False,
header=None,
quoting=csv.QUOTE_NONE,
nrows=90000,
)
train_data = data[[6, 7]]
train_data = pd.concat([train_data, train_labels], axis=1)
train_data["final"] = train_data[6] + train_data[0] + train_data[7]
return train_data
def train_model(self):
training_data = self._prepare_train_data()
for index, row in training_data.iterrows():
text = self.preprocess_text(str(row["final"]))
words = word_tokenize(text)
for w1, w2, w3 in trigrams(words, pad_right=True, pad_left=True):
if w1 and w2 and w3:
self.model[(w2, w3)][w1] += 1
self.model[(w1, w2)][w3] += 1
self.vocab.add(w1)
self.vocab.add(w2)
self.vocab.add(w3)
for word_pair in self.model:
num_n_grams = float(sum(self.model[word_pair].values()))
for word in self.model[word_pair]:
self.model[word_pair][word] = (
self.model[word_pair][word] + self.alpha
) / (num_n_grams + self.alpha * len(self.vocab))
def predict_probs(self, words):
if len(words) < 3:
return self.DEFAULT_PREDICTION
2022-04-03 19:28:02 +02:00
2022-04-10 21:17:55 +02:00
word1, word2 = words[0], words[1]
raw_prediction = dict(self.model[word1, word2])
prediction = dict(Counter(raw_prediction).most_common(6))
2022-04-03 18:44:40 +02:00
2022-04-10 21:17:55 +02:00
total_prob = 0.0
str_prediction = ""
2022-04-03 18:44:40 +02:00
2022-04-10 21:17:55 +02:00
for word, prob in prediction.items():
total_prob += prob
str_prediction += f"{word}:{prob} "
2022-04-03 19:36:26 +02:00
2022-04-10 21:17:55 +02:00
if total_prob == 0.0:
return self.DEFAULT_PREDICTION
2022-04-03 18:44:40 +02:00
2022-04-10 21:17:55 +02:00
remaining_prob = 1 - total_prob
2022-04-03 18:44:40 +02:00
2022-04-10 21:17:55 +02:00
if remaining_prob < 0.01:
remaining_prob = 0.01
2022-04-03 18:44:40 +02:00
2022-04-10 21:17:55 +02:00
str_prediction += f":{remaining_prob}"
2022-04-03 18:44:40 +02:00
2022-04-10 21:17:55 +02:00
return str_prediction
2022-04-03 18:44:40 +02:00
2022-04-10 21:17:55 +02:00
def prepare_output(self, input_file, output_file):
with open(output_file, "w") as file:
data = pd.read_csv(
input_file,
sep="\t",
error_bad_lines=False,
warn_bad_lines=False,
header=None,
quoting=csv.QUOTE_NONE,
)
for _, row in data.iterrows():
text = self.preprocess_text(str(row[7]))
words = word_tokenize(text)
prediction = self.predict_probs(words)
file.write(prediction + "\n")
2022-04-03 18:44:40 +02:00
2022-04-03 19:36:26 +02:00
2022-04-10 21:17:55 +02:00
predictor = GapPredictor(alpha=0.00002)
predictor.train_model()
2022-04-03 19:36:26 +02:00
2022-04-10 21:17:55 +02:00
predictor.prepare_output("dev-0/in.tsv.xz", "dev-0/out.tsv")
predictor.prepare_output("test-A/in.tsv.xz", "test-A/out.tsv")