import pandas as pd import csv import sys 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): for index, row in data.iterrows(): 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 # limit number of data rows used for training if index > 10000: break 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 # check arguments if len(sys.argv) != 2: print('Wrong number of arguments. Expected 1 - alpha smoothing parameter.') quit() else: alpha = sys.argv[1] # 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) train_data['text'] = train_data[6] + train_data[0] + train_data[7] train_data = train_data[['text']] # init model with given aplha model = Model(alpha) # 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')