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

82 lines
2.3 KiB
Python

from nltk import trigram as tris
from nltk import word_tokenize
import pandas as pd
import csv
import regex as re
from collections import Counter, defaultdict
train = pd.read_csv(
'train/in.tsv.xz',
sep='\t',
on_bad_lines='skip',
header=None,
quoting=csv.QUOTE_NONE,
nrows=30000)
labels = pd.read_csv(
'train/expected.tsv',
sep='\t',
on_bad_lines='skip',
header=None,
quoting=csv.QUOTE_NONE,
nrows=30000)
def data_preprocessing(text):
return re.sub(r'\p{P}', '', text.lower().replace('-\\n', '').replace('\\n', ' '))
def predict(before, after):
prediction = dict(Counter(dict(tri[before, after])).most_common(5))
result = ''
prob = 0.0
for key, value in prediction.items():
prob += value
result += f'{key}:{value} '
if prob == 0.0:
return 'to:0.015 be:0.015 the:0.015 not:0.01 and:0.02 a:0.02 :0.9'
result += f':{max(1 - prob, 0.01)}'
return result
def make_prediction(file):
data = pd.read_csv(f'{file}/in.tsv.xz', sep='\t', on_bad_lines='skip', header=None, quoting=csv.QUOTE_NONE)
with open(f'{file}/out.tsv', 'w', encoding='utf-8') as file_out:
for _, row in data.iterrows():
before, after = word_tokenize(data_preprocessing(str(row[6]))), word_tokenize(data_preprocessing(str(row[7])))
if len(before) < 3 or len(after) < 3:
prediction = 'to:0.015 be:0.015 the:0.015 not:0.01 and:0.02 a:0.02 :0.9'
else:
prediction = predict(before[-1], after[0])
file_out.write(prediction + '\n')
train = train[[6, 7]]
train = pd.concat([train, labels], axis=1)
train['line'] = train[6] + train[0] + train[7]
tri = defaultdict(lambda: defaultdict(lambda: 0))
rows = train.iterrows()
rows_len = len(train)
for index, (_, row) in enumerate(rows):
text = data_preprocessing(str(row['line']))
words = word_tokenize(text)
for word_1, word_2, word_3 in tris(words, pad_right=True, pad_left=True):
if word_1 and word_2 and word_3:
tri[(word_1, word_3)][word_2] += 1
model_len = len(tri)
for index, words_1_3 in enumerate(tri):
count = sum(tri[words_1_3].values())
for word_2 in tri[words_1_3]:
tri[words_1_3][word_2] += 0.25
tri[words_1_3][word_2] /= float(count + 0.25 + len(word_2))
make_prediction('test-A')
make_prediction('dev-0')