This commit is contained in:
Norbert Litkowski 2022-04-04 10:26:15 +02:00
parent 61e88a9c8c
commit 86f2757aee
3 changed files with 319 additions and 0 deletions

2
.gitignore vendored
View File

@ -6,3 +6,5 @@
*.o
.DS_Store
.token
.vscode/*
.ipynb_c*

106
run.py Normal file
View File

@ -0,0 +1,106 @@
import pandas as pd
import csv
import regex as re
import nltk
from collections import Counter, defaultdict
import string
import unicodedata
def main():
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
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")
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]
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)
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[6]))
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")
if __name__ == "__main__":
main()

211
testing.ipynb Normal file
View File

@ -0,0 +1,211 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "21c9b695",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import csv\n",
"import regex as re\n",
"import nltk\n",
"from collections import Counter, defaultdict\n",
"import string\n",
"import unicodedata\n",
"\n",
"def clean_text(text): \n",
" return re.sub(r\"\\p{P}\", \"\", str(text).lower().replace(\"-\\\\n\", \"\").replace(\"\\\\n\", \" \"))\n",
"\n",
"def train_model(data, model):\n",
" for _, row in data.iterrows():\n",
" words = nltk.word_tokenize(clean_text(row[\"final\"]))\n",
" for w1, w2 in nltk.bigrams(words, pad_left=True, pad_right=True):\n",
" if w1 and w2:\n",
" model[w2][w1] += 1\n",
" for w1 in model:\n",
" total_count = float(sum(model[w1].values()))\n",
" for w2 in model[w1]:\n",
" model[w2][w1] /= total_count\n",
"\n",
"\n",
"def predict(word, model):\n",
" predictions = dict(model[word])\n",
" most_common = dict(Counter(predictions).most_common(5))\n",
"\n",
" total_prob = 0.0\n",
" str_prediction = \"\"\n",
"\n",
" for word, prob in most_common.items():\n",
" total_prob += prob\n",
" str_prediction += f\"{word}:{prob} \"\n",
"\n",
" if not total_prob:\n",
" return \"the:0.2 be:0.2 to:0.2 of:0.1 and:0.1 a:0.1 :0.1\"\n",
"\n",
" if 1 - total_prob >= 0.01:\n",
" str_prediction += f\":{1-total_prob}\"\n",
" else:\n",
" str_prediction += f\":0.01\"\n",
"\n",
" return str_prediction\n",
"\n",
"\n",
"def predict_data(read_path, save_path, model):\n",
" data = pd.read_csv(\n",
" read_path, sep=\"\\t\", error_bad_lines=False, header=None, quoting=csv.QUOTE_NONE\n",
" )\n",
" with open(save_path, \"w\") as file:\n",
" for _, row in data.iterrows():\n",
" words = nltk.word_tokenize(clean_text(row[7]))\n",
" if len(words) < 3:\n",
" prediction = \"the:0.2 be:0.2 to:0.2 of:0.1 and:0.1 a:0.1 :0.1\"\n",
" else:\n",
" prediction = predict(words[-1], model)\n",
" file.write(prediction + \"\\n\")\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "e39473e2",
"metadata": {},
"outputs": [],
"source": [
"with open(\"in-header.tsv\") as f:\n",
" in_cols = f.read().strip().split(\"\\t\")\n",
"\n",
"with open(\"out-header.tsv\") as f:\n",
" out_cols = f.read().strip().split(\"\\t\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "bde510c9",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['FileId', 'Year', 'LeftContext', 'RightContext']"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"in_cols"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "0e8b31dd",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Word']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"out_cols"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7662d802",
"metadata": {},
"outputs": [],
"source": [
"data = pd.read_csv(\n",
" \"train/in.tsv.xz\",\n",
" sep=\"\\t\",\n",
" on_bad_lines='skip',\n",
" header=None,\n",
" # names=in_cols,\n",
" quoting=csv.QUOTE_NONE,\n",
")\n",
"\n",
"train_labels = pd.read_csv(\n",
" \"train/expected.tsv\",\n",
" sep=\"\\t\",\n",
" on_bad_lines='skip',\n",
" header=None,\n",
" # names=out_cols,\n",
" quoting=csv.QUOTE_NONE,\n",
")\n",
"\n",
"train_data = data[[7, 6]]\n",
"train_data = pd.concat([train_data, train_labels], axis=1)\n",
"\n",
"train_data[\"final\"] = train_data[7] + train_data[0] + train_data[6]\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c3d2cfec",
"metadata": {},
"outputs": [],
"source": [
"train_data"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bd92ba07",
"metadata": {},
"outputs": [],
"source": [
"\n",
"model = defaultdict(lambda: defaultdict(lambda: 0))\n",
"\n",
"train_model(train_data, model)\n",
"predict_data(\"dev-0/in.tsv.xz\", \"dev-0/out.tsv\", model)\n",
"predict_data(\"test-A/in.tsv.xz\", \"test-A/out.tsv\", model)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad23240e",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}