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

81 lines
3.1 KiB
Python

from re import T
import pandas as pd
import csv
from collections import Counter, defaultdict
from nltk.tokenize import RegexpTokenizer
from nltk import trigrams
import regex as re
import lzma
class GapEssa:
def __init__(self):
self.alpha = 0.0001
self.vocab = set()
self.model = defaultdict(lambda: defaultdict(lambda: 0))
self.tokenizer = RegexpTokenizer(r"\w+")
def read_file(self, f, mode=0):
for line in f:
text = line.split("\t")
if(mode==0):
yield re.sub(r"[^\w\d'\s]+", '', re.sub(' +', ' ', ' '.join([text[6], text[7]]).replace("\\n"," ").replace("\n","").lower()))
else:
yield re.sub(r"[^\w\d'\s]+", '', re.sub(' +', ' ', text[7].replace("\\n"," ").replace("\n","").lower()))
def train(self, f):
with lzma.open(f, mode='rt') as file:
for index, text in enumerate(self.read_file(file)):
tokens = self.tokenizer.tokenize(text)
for w1, w2, w3 in trigrams(tokens, pad_right=True, pad_left=True):
if w1 and w2 and w3:
self.model[(w2, w3)][w1] += 1
self.vocab.add(w1)
self.vocab.add(w2)
self.vocab.add(w3)
if index == 40000:
break
for pair in self.model:
num_n_grams = float(sum(self.model[pair].values()))
for word in self.model[pair]:
self.model[pair][word] = (self.model[pair][word] + self.alpha) / (num_n_grams + self.alpha*len(self.vocab))
def out(self, input_f, output_f):
with open(output_f, 'w') as out_f:
with lzma.open(input_f, mode='rt') as in_f:
for _, text in enumerate(self.read_file(in_f, mode=1)):
t = self.tokenizer.tokenize(text)
if len(t) < 4:
# p = 'the:0.2 be:0.2 to:0.2 of:0.1 and:0.1 a:0.1 :0.1'
p = 'the:0.03 be:0.03 to:0.03 of:0.025 and:0.025 a:0.025 in:0.020 that:0.020 have:0.015 I:0.010 it:0.010 for:0.010 not:0.010 on:0.010 with:0.010 he:0.010 as:0.010 you:0.010 do:0.010 at:0.010 :0.77'
else:
p = self.pred(t[0], t[1])
out_f.write(p + '\n')
def pred(self, w1, w2):
total = 0.0
line = ''
p = dict(self.model[w1, w2])
m = dict(Counter(p).most_common(6))
for word, prob in m.items():
total += prob
line += f'{word}:{prob} '
if total == 0.0:
return 'the:0.03 be:0.03 to:0.03 of:0.025 and:0.025 a:0.025 in:0.020 that:0.020 have:0.015 I:0.010 it:0.010 for:0.010 not:0.010 on:0.010 with:0.010 he:0.010 as:0.010 you:0.010 do:0.010 at:0.010 :0.77'
if 1 - total >= 0.01:
line += f":{1-total}"
else:
line += f":0.01"
return line
wp = GapEssa()
wp.train('train/in.tsv.xz')
wp.out('dev-0/in.tsv.xz', 'dev-0/out.tsv')
wp.out('test-A/in.tsv.xz', 'test-A/out.tsv')