challenging-america-word-ga.../testing.ipynb
Norbert Litkowski 86f2757aee 440054
2022-04-04 10:26:15 +02:00

5.3 KiB

import pandas as pd
import csv
import regex as re
import nltk
from collections import Counter, defaultdict
import string
import unicodedata

def clean_text(text): 
    return re.sub(r"\p{P}", "", str(text).lower().replace("-\\\\n", "").replace("\\\\n", " "))

def train_model(data, model):
    for _, row in data.iterrows():
        words = nltk.word_tokenize(clean_text(row["final"]))
        for w1, w2 in nltk.bigrams(words, pad_left=True, pad_right=True):
            if w1 and w2:
                model[w2][w1] += 1
    for w1 in model:
        total_count = float(sum(model[w1].values()))
        for w2 in model[w1]:
            model[w2][w1] /= total_count


def predict(word, model):
    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 "the:0.2 be:0.2 to:0.2 of:0.1 and:0.1 a:0.1 :0.1"

    if 1 - total_prob >= 0.01:
        str_prediction += f":{1-total_prob}"
    else:
        str_prediction += f":0.01"

    return str_prediction


def predict_data(read_path, save_path, model):
    data = pd.read_csv(
        read_path, sep="\t", error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE
    )
    with open(save_path, "w") as file:
        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[-1], model)
            file.write(prediction + "\n")
with open("in-header.tsv") as f:
    in_cols = f.read().strip().split("\t")

with open("out-header.tsv") as f:
    out_cols = f.read().strip().split("\t")
in_cols
['FileId', 'Year', 'LeftContext', 'RightContext']
out_cols
['Word']
data = pd.read_csv(
    "train/in.tsv.xz",
    sep="\t",
    on_bad_lines='skip',
    header=None,
    # names=in_cols,
    quoting=csv.QUOTE_NONE,
)

train_labels = pd.read_csv(
    "train/expected.tsv",
    sep="\t",
    on_bad_lines='skip',
    header=None,
    # names=out_cols,
    quoting=csv.QUOTE_NONE,
)

train_data = data[[7, 6]]
train_data = pd.concat([train_data, train_labels], axis=1)

train_data["final"] = train_data[7] + train_data[0] + train_data[6]
train_data

model = defaultdict(lambda: defaultdict(lambda: 0))

train_model(train_data, model)
predict_data("dev-0/in.tsv.xz", "dev-0/out.tsv", model)
predict_data("test-A/in.tsv.xz", "test-A/out.tsv", model)