79 lines
2.5 KiB
Python
79 lines
2.5 KiB
Python
import pandas as pd
|
|
import csv
|
|
import regex as re
|
|
from nltk import bigrams, word_tokenize
|
|
from collections import Counter, defaultdict
|
|
import string
|
|
import unicodedata
|
|
|
|
DEFAULT_PREDICTION = "the:0.2 be:0.2 to:0.2 of:0.1 and:0.1 a:0.1 :0.1"
|
|
|
|
data = pd.read_csv("train/in.tsv.xz", sep="\t", error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE)
|
|
train_labels = pd.read_csv("train/expected.tsv", sep="\t", error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE)
|
|
|
|
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]
|
|
|
|
model = defaultdict(lambda: defaultdict(lambda: 0))
|
|
|
|
|
|
def clean(text):
|
|
text = str(text).lower().replace("-\\n", "").replace("\\n", " ")
|
|
return re.sub(r"\p{P}", "", text)
|
|
|
|
for _, row in train_data.iterrows():
|
|
words = word_tokenize(clean(row["final"]))
|
|
for w1, w2 in bigrams(words, pad_left=True, pad_right=True):
|
|
if w1 and w2:
|
|
model[w1][w2] += 1
|
|
for w1 in model:
|
|
total_count = float(sum(model[w1].values()))
|
|
for w2 in model[w1]:
|
|
model[w1][w2] /= total_count
|
|
|
|
|
|
def predict(word):
|
|
predictions = dict(model[word])
|
|
most_common = dict(Counter(predictions).most_common(5))
|
|
|
|
total_prob = 0.0
|
|
str_prediction = ""
|
|
|
|
for word, prob in most_common.items():
|
|
total_prob += prob
|
|
str_prediction += f"{word}:{prob} "
|
|
|
|
if not total_prob:
|
|
return DEFAULT_PREDICTION
|
|
|
|
if 1 - total_prob >= 0.01:
|
|
str_prediction += f":{1-total_prob}"
|
|
else:
|
|
str_prediction += f":0.01"
|
|
|
|
return str_prediction
|
|
|
|
|
|
data = pd.read_csv("dev-0/in.tsv.xz", sep="\t", error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE)
|
|
with open("dev-0/out.tsv", "w", encoding="UTF-8") as file:
|
|
for _, row in data.iterrows():
|
|
words = word_tokenize(clean(row[6]))
|
|
if len(words) < 3:
|
|
prediction = DEFAULT_PREDICTION
|
|
else:
|
|
prediction = predict(words[-1])
|
|
file.write(prediction + "\n")
|
|
|
|
|
|
data = pd.read_csv("test-A/in.tsv.xz", sep="\t", error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE)
|
|
with open("test-A/out.tsv", "w", encoding="UTF-8") as file:
|
|
for _, row in data.iterrows():
|
|
words = word_tokenize(clean(row[6]))
|
|
if len(words) < 3:
|
|
prediction = DEFAULT_PREDICTION
|
|
else:
|
|
prediction = predict(words[-1])
|
|
file.write(prediction + "\n")
|