s437622 kenlm
This commit is contained in:
parent
27856836a3
commit
8542482455
21038
dev-0/out.tsv
21038
dev-0/out.tsv
File diff suppressed because it is too large
Load Diff
153
run.py
153
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,
|
|
||||||
nrows=20000)
|
|
||||||
train_labels = pd.read_csv('train/expected.tsv', sep='\t', on_bad_lines='skip', header=None,
|
|
||||||
quoting=csv.QUOTE_NONE, nrows=20000)
|
|
||||||
train_data = train_data[[6, 7]]
|
|
||||||
train_data = pd.concat([train_data, train_labels], axis=1)
|
|
||||||
train_data['line'] = train_data[6] + train_data[0] + train_data[7]
|
|
||||||
|
|
||||||
self.file = train_data[['line']]
|
|
||||||
self.test_file_name = test_file_name
|
|
||||||
self.alpha = alpha;
|
|
||||||
self.model = defaultdict(lambda: defaultdict(lambda: 0))
|
|
||||||
|
|
||||||
def train(self):
|
train_data = pd.read_csv('train/in.tsv.xz', sep='\t', on_bad_lines='skip', header=None, quoting=csv.QUOTE_NONE,
|
||||||
rows = self.file.iterrows()
|
nrows=20000)
|
||||||
rows_len = len(self.file)
|
train_labels = pd.read_csv('train/expected.tsv', sep='\t', on_bad_lines='skip', header=None,
|
||||||
for index, (_, row) in enumerate(rows):
|
quoting=csv.QUOTE_NONE, nrows=20000)
|
||||||
text = preprocess(str(row['line']))
|
data = pd.concat([train_data, train_labels], axis=1)
|
||||||
words = word_tokenize(text)
|
data=train_data[6] + train_data[0] + train_data[7]
|
||||||
for word_1, word_2, word_3 in trigrams(words, pad_right=True, pad_left=True):
|
data = data.apply(preprocess)
|
||||||
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):
|
with open("train_file.txt", "w+") as f:
|
||||||
prediction = dict(Counter(dict(self.model[before, after])).most_common(5))
|
for text in data:
|
||||||
result = []
|
f.write(text + "\n")
|
||||||
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)
|
# In[5]:
|
||||||
with open(f'{self.test_file_name}/out.tsv', 'w', encoding='utf-8') as file_out:
|
|
||||||
for _, row in data.iterrows():
|
|
||||||
before, after = word_tokenize(preprocess(str(row[6]))), word_tokenize(preprocess(str(row[7])))
|
KENLM_BUILD_PATH='../kenlm/kenlm/build'
|
||||||
if len(before) < 3 or len(after) < 3:
|
get_ipython().system('$KENLM_BUILD_PATH/bin/lmplz -o 4 < train_file.txt > model.arpa')
|
||||||
prediction = default_pred
|
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:
|
else:
|
||||||
prediction = self.predict(before[-1], after[0])
|
if worst_score[1] > score[1]:
|
||||||
file_out.write(prediction + '\n')
|
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():
|
||||||
|
before, after = word_tokenize(preprocess(str(row[6]))), word_tokenize(preprocess(str(row[7])))
|
||||||
|
if len(before) < 2 or len(after) < 2:
|
||||||
|
prediction = default_pred
|
||||||
|
else:
|
||||||
|
prediction = predict(before[-1], after[0])
|
||||||
|
file_out.write(prediction + '\n')
|
||||||
|
|
||||||
|
|
||||||
|
# In[9]:
|
||||||
|
|
||||||
|
|
||||||
|
make_prediction("dev-0/in.tsv.xz", "dev-0/out.tsv")
|
||||||
|
|
||||||
|
|
||||||
|
# In[10]:
|
||||||
|
|
||||||
|
|
||||||
|
make_prediction("test-A/in.tsv.xz", "test-A/out.tsv")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
alpha = 0.1
|
|
||||||
model = Model(alpha, 'test-A')
|
|
||||||
model.train()
|
|
||||||
model.make_prediction()
|
|
||||||
|
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