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

109 lines
3.8 KiB
Python
Raw Normal View History

2022-04-09 13:07:07 +02:00
import pandas as pd
import csv
2022-04-09 14:54:19 +02:00
import sys
2022-04-09 13:07:07 +02:00
import regex as re
from collections import Counter, defaultdict
from nltk import trigrams, word_tokenize
def clean_text(text):
text = text.lower().replace('-\\n', '').replace('\\n', ' ')
text = re.sub(r'\p{P}', '', text)
return text
class Model():
def __init__(self, alpha):
self.alpha = alpha
self.probs = defaultdict(lambda: defaultdict(lambda: 0))
self.vocab = set()
def train(self, data):
2022-04-09 14:54:19 +02:00
for index, row in data.iterrows():
2022-04-09 13:07:07 +02:00
text = clean_text(str(row['text']))
words = word_tokenize(text)
for w1, w2, w3 in trigrams(words, pad_right=True, pad_left=True):
if w1 and w2 and w3:
self.vocab.add(w1)
self.vocab.add(w2)
self.vocab.add(w3)
self.probs[(w1, w3)][w2] += 1
2022-04-09 14:54:19 +02:00
# limit number of data rows used for training
if index > 10000:
break
2022-04-09 13:07:07 +02:00
for w1_w3 in self.probs:
total_count = float(sum(self.probs[w1_w3].values()))
denominator = total_count + self.alpha * len(self.vocab)
for w2 in self.probs[w1_w3]:
nominator = self.probs[w1_w3][w2] + self.alpha
self.probs[w1_w3][w2] = nominator / denominator
def predict(self, w1, w3):
raw_prediction = dict(self.probs[w1, w3])
prediction = dict(Counter(raw_prediction).most_common(6))
total_prob = 0.0
str_prediction = ''
for word, prob in prediction.items():
total_prob += prob
str_prediction += f'{word}:{prob} '
remaining_prob = 1 - total_prob
str_prediction += f':{remaining_prob}'
return str_prediction
2022-04-09 14:54:19 +02:00
# check arguments
if len(sys.argv) != 2:
print('Wrong number of arguments. Expected 1 - alpha smoothing parameter.')
quit()
else:
alpha = sys.argv[1]
2022-04-09 13:07:07 +02:00
# load training data
train_data = pd.read_csv('train/in.tsv.xz', sep='\t', error_bad_lines=False, warn_bad_lines=False, header=None, quoting=csv.QUOTE_NONE)
train_labels = pd.read_csv('train/expected.tsv', sep='\t', error_bad_lines=False, warn_bad_lines=False, header=None, quoting=csv.QUOTE_NONE)
train_data = train_data[[6, 7]]
train_data = pd.concat([train_data, train_labels], axis=1)
2022-04-09 14:19:44 +02:00
train_data['text'] = train_data[6] + train_data[0] + train_data[7]
train_data = train_data[['text']]
2022-04-09 13:07:07 +02:00
# init model with given aplha
2022-04-09 14:54:19 +02:00
model = Model(alpha)
2022-04-09 13:07:07 +02:00
# train model probs
model.train(train_data)
# make predictions
dev_data = pd.read_csv('dev-0/in.tsv.xz', sep='\t', error_bad_lines=False, warn_bad_lines=False, header=None, quoting=csv.QUOTE_NONE)
test_data = pd.read_csv('test-A/in.tsv.xz', sep='\t', error_bad_lines=False, warn_bad_lines=False, header=None, quoting=csv.QUOTE_NONE)
with open('dev-0/out.tsv', 'w') as file:
for index, row in dev_data.iterrows():
left_text = clean_text(str(row[6]))
right_text = clean_text(str(row[7]))
left_words = word_tokenize(left_text)
right_words = word_tokenize(right_text)
if len(left_words) < 2 or len(right_words) < 2:
prediction = ':1.0'
else:
prediction = model.predict(left_words[len(left_words) - 1], right_words[0])
file.write(prediction + '\n')
with open('test-A/out.tsv', 'w') as file:
for index, row in test_data.iterrows():
left_text = clean_text(str(row[6]))
right_text = clean_text(str(row[7]))
left_words = word_tokenize(left_text)
right_words = word_tokenize(right_text)
if len(left_words) < 2 or len(right_words) < 2:
prediction = ':1.0'
else:
prediction = model.predict(left_words[len(left_words) - 1], right_words[0])
file.write(prediction + '\n')