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

77 lines
2.0 KiB
Python
Raw Normal View History

2022-04-04 10:26:15 +02:00
import pandas as pd
import nltk
from collections import Counter, defaultdict
2022-04-04 15:07:07 +02:00
from utils import get_csv, check_prerequisites, ENCODING, clean_text
2022-04-04 10:26:15 +02:00
def main():
2022-04-04 15:07:07 +02:00
check_prerequisites()
data = get_csv("train/in.tsv.xz")
train_words = get_csv("train/expected.tsv")
2022-04-04 10:26:15 +02:00
2022-04-05 00:12:13 +02:00
train_data = data[[6, 7]]
2022-04-04 15:07:07 +02:00
train_data = pd.concat([train_data, train_words], axis=1)
2022-04-04 10:26:15 +02:00
2022-04-05 00:12:13 +02:00
train_data[607] = train_data[6] + train_data[0] + train_data[7]
2022-04-04 10:26:15 +02:00
model = defaultdict(lambda: defaultdict(lambda: 0))
train_model(train_data, model)
2022-04-04 15:07:07 +02:00
2022-04-04 10:26:15 +02:00
predict_data("dev-0/in.tsv.xz", "dev-0/out.tsv", model)
predict_data("test-A/in.tsv.xz", "test-A/out.tsv", model)
def train_model(data, model):
for _, row in data.iterrows():
2022-04-05 00:12:13 +02:00
words = nltk.word_tokenize(clean_text(row[607]))
2022-04-04 10:26:15 +02:00
for w1, w2 in nltk.bigrams(words, pad_left=True, pad_right=True):
if w1 and w2:
model[w2][w1] += 1
2022-04-04 15:07:07 +02:00
for w2 in model:
total_count = float(sum(model[w2].values()))
for w1 in model[w2]:
2022-04-04 10:26:15 +02:00
model[w2][w1] /= total_count
2022-04-05 19:08:22 +02:00
def predict_data(read_path, save_path, model):
data = get_csv(read_path)
with open(save_path, "w", encoding=ENCODING) as f:
for _, row in data.iterrows():
words = nltk.word_tokenize(clean_text(row[7]))
if len(words) < 3:
prediction = "the:0.2 be:0.2 to:0.2 of:0.1 and:0.1 a:0.1 :0.1"
else:
prediction = predict(words[0], model)
f.write(prediction + "\n")
2022-04-04 10:26:15 +02:00
def predict(word, model):
predictions = dict(model[word])
2022-04-05 19:08:22 +02:00
most_common = dict(Counter(predictions).most_common(6))
2022-04-04 10:26:15 +02:00
total_prob = 0.0
str_prediction = ""
for word, prob in most_common.items():
total_prob += prob
str_prediction += f"{word}:{prob} "
2022-04-05 19:08:22 +02:00
if total_prob == 0.0:
2022-04-04 10:26:15 +02:00
return "the:0.2 be:0.2 to:0.2 of:0.1 and:0.1 a:0.1 :0.1"
2022-04-05 19:08:22 +02:00
rem_prob = 1 - total_prob
if rem_prob < 0.01:
rem_prob = 0.01
2022-04-04 10:26:15 +02:00
2022-04-05 19:08:22 +02:00
str_prediction += f":{rem_prob}"
2022-04-04 10:26:15 +02:00
2022-04-05 19:08:22 +02:00
return str_prediction
2022-04-04 10:26:15 +02:00
if __name__ == "__main__":
main()