Compare commits
1 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
8542482455 |
21038
dev-0/out.tsv
21038
dev-0/out.tsv
File diff suppressed because it is too large
Load Diff
137
run.py
137
run.py
@ -1,73 +1,118 @@
|
|||||||
from nltk import trigrams, word_tokenize
|
#!/usr/bin/env python
|
||||||
from collections import defaultdict, Counter
|
# coding: utf-8
|
||||||
|
|
||||||
|
# In[1]:
|
||||||
|
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import csv
|
import csv
|
||||||
import regex as re
|
import regex as re
|
||||||
|
import kenlm
|
||||||
|
from english_words import english_words_alpha_set
|
||||||
|
from math import log10
|
||||||
|
from nltk import trigrams, word_tokenize
|
||||||
|
|
||||||
|
|
||||||
|
# In[2]:
|
||||||
|
|
||||||
|
|
||||||
default_pred = 'to:0.02 be:0.02 the:0.02 or:0.01 not:0.01 and:0.01 a:0.01 :0.9'
|
default_pred = 'to:0.02 be:0.02 the:0.02 or:0.01 not:0.01 and:0.01 a:0.01 :0.9'
|
||||||
|
|
||||||
|
|
||||||
|
# In[3]:
|
||||||
|
|
||||||
|
|
||||||
def preprocess(text):
|
def preprocess(text):
|
||||||
text = text.lower().replace('-\\n', '').replace('\\n', ' ')
|
text = text.lower().replace('-\\n', '').replace('\\n', ' ')
|
||||||
return re.sub(r'\p{P}', '', text)
|
return re.sub(r'\p{P}', '', text)
|
||||||
|
|
||||||
|
|
||||||
class Model():
|
# In[4]:
|
||||||
def __init__(self, alpha, test_file_name):
|
|
||||||
|
|
||||||
train_data = pd.read_csv('train/in.tsv.xz', sep='\t', on_bad_lines='skip', header=None, quoting=csv.QUOTE_NONE,
|
train_data = pd.read_csv('train/in.tsv.xz', sep='\t', on_bad_lines='skip', header=None, quoting=csv.QUOTE_NONE,
|
||||||
nrows=20000)
|
nrows=20000)
|
||||||
train_labels = pd.read_csv('train/expected.tsv', sep='\t', on_bad_lines='skip', header=None,
|
train_labels = pd.read_csv('train/expected.tsv', sep='\t', on_bad_lines='skip', header=None,
|
||||||
quoting=csv.QUOTE_NONE, nrows=20000)
|
quoting=csv.QUOTE_NONE, nrows=20000)
|
||||||
train_data = train_data[[6, 7]]
|
data = pd.concat([train_data, train_labels], axis=1)
|
||||||
train_data = pd.concat([train_data, train_labels], axis=1)
|
data=train_data[6] + train_data[0] + train_data[7]
|
||||||
train_data['line'] = train_data[6] + train_data[0] + train_data[7]
|
data = data.apply(preprocess)
|
||||||
|
|
||||||
self.file = train_data[['line']]
|
with open("train_file.txt", "w+") as f:
|
||||||
self.test_file_name = test_file_name
|
for text in data:
|
||||||
self.alpha = alpha;
|
f.write(text + "\n")
|
||||||
self.model = defaultdict(lambda: defaultdict(lambda: 0))
|
|
||||||
|
|
||||||
def train(self):
|
|
||||||
rows = self.file.iterrows()
|
|
||||||
rows_len = len(self.file)
|
|
||||||
for index, (_, row) in enumerate(rows):
|
|
||||||
text = preprocess(str(row['line']))
|
|
||||||
words = word_tokenize(text)
|
|
||||||
for word_1, word_2, word_3 in trigrams(words, pad_right=True, pad_left=True):
|
|
||||||
if word_1 and word_2 and word_3:
|
|
||||||
self.model[(word_1, word_3)][word_2] += 1
|
|
||||||
model_len = len(self.model)
|
|
||||||
for index, words_1_3 in enumerate(self.model):
|
|
||||||
count = sum(self.model[words_1_3].values())
|
|
||||||
for word_2 in self.model[words_1_3]:
|
|
||||||
self.model[words_1_3][word_2] += self.alpha
|
|
||||||
self.model[words_1_3][word_2] /= float(count + self.alpha + len(word_2))
|
|
||||||
|
|
||||||
def predict(self, before, after):
|
# In[5]:
|
||||||
prediction = dict(Counter(dict(self.model[before, after])).most_common(5))
|
|
||||||
result = []
|
|
||||||
prob = 0.0
|
|
||||||
for key, value in prediction.items():
|
|
||||||
prob += value
|
|
||||||
result.append(f'{key}:{value} ')
|
|
||||||
if prob == 0.0:
|
|
||||||
return default_pred
|
|
||||||
result.append(f':{max(1 - prob, 0.01)}')
|
|
||||||
return ''.join(result)
|
|
||||||
|
|
||||||
def make_prediction(self):
|
|
||||||
data = pd.read_csv(f'{self.test_file_name}/in.tsv.xz', sep='\t', on_bad_lines='skip', header=None, quoting=csv.QUOTE_NONE)
|
KENLM_BUILD_PATH='../kenlm/kenlm/build'
|
||||||
with open(f'{self.test_file_name}/out.tsv', 'w', encoding='utf-8') as file_out:
|
get_ipython().system('$KENLM_BUILD_PATH/bin/lmplz -o 4 < train_file.txt > model.arpa')
|
||||||
|
get_ipython().system('rm train_file.txt')
|
||||||
|
|
||||||
|
|
||||||
|
# In[6]:
|
||||||
|
|
||||||
|
|
||||||
|
model = kenlm.Model("model.arpa")
|
||||||
|
|
||||||
|
|
||||||
|
# In[7]:
|
||||||
|
|
||||||
|
|
||||||
|
def predict(before, after):
|
||||||
|
best_scores = []
|
||||||
|
for word in english_words_alpha_set:
|
||||||
|
text = ' '.join([before, word, after])
|
||||||
|
text_score = model.score(text, bos=False, eos=False)
|
||||||
|
if len(best_scores) < 12:
|
||||||
|
best_scores.append((word, text_score))
|
||||||
|
else:
|
||||||
|
is_better = False
|
||||||
|
worst_score = None
|
||||||
|
for score in best_scores:
|
||||||
|
if not worst_score:
|
||||||
|
worst_score = score
|
||||||
|
else:
|
||||||
|
if worst_score[1] > score[1]:
|
||||||
|
worst_score = score
|
||||||
|
if worst_score[1] < text_score:
|
||||||
|
best_scores.remove(worst_score)
|
||||||
|
best_scores.append((word, text_score))
|
||||||
|
probs = sorted(best_scores, key=lambda tup: tup[1], reverse=True)
|
||||||
|
pred_str = ''
|
||||||
|
for word, prob in probs:
|
||||||
|
pred_str += f'{word}:{prob} '
|
||||||
|
pred_str += f':{log10(0.99)}'
|
||||||
|
return pred_str
|
||||||
|
|
||||||
|
|
||||||
|
# In[8]:
|
||||||
|
|
||||||
|
|
||||||
|
def make_prediction(path, result_path):
|
||||||
|
data = pd.read_csv(path, sep='\t', on_bad_lines='skip', header=None, quoting=csv.QUOTE_NONE)
|
||||||
|
with open(result_path, 'w', encoding='utf-8') as file_out:
|
||||||
for _, row in data.iterrows():
|
for _, row in data.iterrows():
|
||||||
before, after = word_tokenize(preprocess(str(row[6]))), word_tokenize(preprocess(str(row[7])))
|
before, after = word_tokenize(preprocess(str(row[6]))), word_tokenize(preprocess(str(row[7])))
|
||||||
if len(before) < 3 or len(after) < 3:
|
if len(before) < 2 or len(after) < 2:
|
||||||
prediction = default_pred
|
prediction = default_pred
|
||||||
else:
|
else:
|
||||||
prediction = self.predict(before[-1], after[0])
|
prediction = predict(before[-1], after[0])
|
||||||
file_out.write(prediction + '\n')
|
file_out.write(prediction + '\n')
|
||||||
|
|
||||||
|
|
||||||
alpha = 0.1
|
# In[9]:
|
||||||
model = Model(alpha, 'test-A')
|
|
||||||
model.train()
|
|
||||||
model.make_prediction()
|
make_prediction("dev-0/in.tsv.xz", "dev-0/out.tsv")
|
||||||
|
|
||||||
|
|
||||||
|
# In[10]:
|
||||||
|
|
||||||
|
|
||||||
|
make_prediction("test-A/in.tsv.xz", "test-A/out.tsv")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
14828
test-A/out.tsv
14828
test-A/out.tsv
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user