a-v-bely commited on
Commit
386f0e3
·
1 Parent(s): 4679722

Rule-based approach

Browse files
app.py CHANGED
@@ -1,23 +1,106 @@
1
- import streamlit as st
2
  import pandas as pd
3
- from rnc_morphemer.NeuralMorphemeSegmentation.neural_morph_segm import load_cls
4
 
5
- path = 'rnc_morphemer/models/morphodict_10_07_2023.json'
6
- def predict(lemma):
7
- model = load_cls(path)
8
 
9
- labels, _ = model._predict_probs([lemma])[0]
10
- morphemes, morpheme_types = model.labels_to_morphemes(
11
- lemma, labels, return_probs=False, return_types=True
12
- )
13
 
14
- parsing = [
15
- {"morpheme": morpheme, "type": morpheme_type}
16
- for morpheme, morpheme_type in zip(morphemes, morpheme_types)
17
- ]
18
 
19
- return parsing
20
- st.header('Слово на морфемы онлайн')
21
- input = st.text_input(label='Морфемный разбор слова:')
22
- st.write(pd.DataFrame(predict(input)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pandas as pd
2
+ import streamlit as st
3
 
4
+ with open('suffixes.txt', encoding='utf-8') as f:
5
+ suffixes = [l.strip() for l in f]
 
6
 
7
+ with open('prefixes.txt', encoding='utf-8') as f:
8
+ prefixes = [l.strip() for l in f]
 
 
9
 
10
+ def annotate_morphemes(word, prefixes=prefixes, suffixes=suffixes):
11
+ interfixes = ('а', 'ар', 'е', 'ей', 'и', 'ич', 'л', 'о', 'у', 'ш')
 
 
12
 
13
+ stack = ''
14
+ annotation = []
15
+ word = list(word)
16
+ had_ending = False
17
+ for i in range(len(word)):
18
+ char = word.pop()
19
+ if char == '-':
20
+ if stack == '':
21
+ had_ending = True
22
+ continue
23
+ annotation.append({stack[::-1]: 'ending'})
24
+ stack = ''
25
+ elif char == '=':
26
+ if stack[::-1] in prefixes and annotation and (list(annotation[-1].values())[0] == 'root' or list(annotation[-1].values())[0] == 'prefix'):
27
+ # print(1, stack[::-1])
28
+ annotation.append({stack[::-1]: 'prefix'})
29
+ elif stack[::-1] in suffixes and annotation and list(annotation[-1].values())[0] not in ('root', 'prefix'):
30
+ # print(2, stack[::-1])
31
+ annotation.append({stack[::-1]: 'suffix'})
32
+ elif stack[::-1] in ('адьj', 'амт', 'ачей'):
33
+ # print(3, stack[::-1])
34
+ annotation.append({stack[::-1]: 'unifix'})
35
+ elif stack[::-1] in ('же', 'либо', 'нибудь', 'с', 'сь', 'ся', 'то', 'те') and not annotation:
36
+ # print(4, stack[::-1])
37
+ annotation.append({stack[::-1]: 'postfix'})
38
+ else:
39
+ if annotation:
40
+ if list(annotation[-1].values())[0] == 'ending':
41
+ # print(5, stack[::-1])
42
+ annotation.append({stack[::-1]: 'root'})
43
+ elif list(annotation[-1].values())[0] == 'suffix':
44
+ # print(6, stack[::-1])
45
+ annotation.append({stack[::-1]: 'root'})
46
+ elif len(annotation) >=2 and list(annotation[-2].values())[0] == 'root' and list(annotation[-1].values())[0] in ('prefix', 'interfix'):
47
+ if stack[::-1] in interfixes and list(annotation[-1].keys())[0] in interfixes:
48
+ # print('68', stack[::-1], annotation)
49
+ annotation.append({stack[::-1]: 'interfix'})
50
+ elif list(annotation[-1].keys())[0] in interfixes:
51
+ # print('69', stack[::-1], annotation)
52
+ annotation[-1] = {list(annotation[-1].keys())[0]: 'interfix'}
53
+ elif stack[::-1] in interfixes:
54
+ # print(70, stack[::-1])
55
+ annotation.append({stack[::-1]: 'interfix'})
56
+ elif stack[::-1] in suffixes:
57
+ # print(71, stack[::-1])
58
+ annotation.append({stack[::-1]: 'suffix'})
59
+ else:
60
+ # print(72, stack[::-1])
61
+ annotation.append({stack[::-1]: 'root'})
62
+ elif list(annotation[-1].values())[0] == 'interfix':
63
+ # print(73, stack[::-1])
64
+ annotation.append({stack[::-1]: 'root'})
65
+ else:
66
+ # print('1111111111', stack[::-1], annotation[::-1], annotation)
67
+ annotation.append({stack[::-1]: 'unk'})
68
+ else:
69
+ if stack[::-1] in suffixes:
70
+ # print(8, stack[::-1])
71
+ annotation.append({stack[::-1]: 'suffix'})
72
+ elif had_ending:
73
+ # print(9, stack[::-1])
74
+ annotation.append({stack[::-1]: 'root'})
75
+ else:
76
+ # print('3333333', stack[::-1])
77
+ annotation.append({stack[::-1]: 'root'})
78
+ stack = ''
79
+ else:
80
+ stack += char
81
+ # print('time', stack[::-1])
82
+ if stack[::-1] in prefixes:
83
+ annotation.append({stack[::-1]: 'prefix'})
84
+ elif stack[::-1] in suffixes:
85
+ annotation.append({stack[::-1]: 'suffix'})
86
+ else:
87
+ if len(annotation) >=2 and list(annotation[-2].values())[0] == 'root' and list(annotation[-1].values())[0] == 'prefix':
88
+ annotation[-1] = {list(annotation[-1].keys())[0]: 'interfix'}
89
+ annotation.append({stack[::-1]: 'root'})
90
+ elif list(annotation[-1].values())[0] in ('interfix', 'suffix', 'root'):
91
+ annotation.append({stack[::-1]: 'root'})
92
+ else:
93
+ annotation.append({stack[::-1]: 'unk'})
94
+ return [list(x.items())[0] for x in annotation[::-1]]
95
 
96
+ st.header('Аннотирование морфемого разбора')
97
+ st.write('Введите морфемный разбор слова или слов (разделитель - пробел) в формате словаря.')
98
+ st.write('Например: пере=двиг=а-ть=ся быстр=о .')
99
+ inpt = st.text_input(label='Разметить морфемы в слове(-ах): ')
100
+ if inpt == '':
101
+ pass
102
+ elif ' ' in inpt:
103
+ for i, tk in enumerate(inpt.split()):
104
+ st.dataframe(pd.DataFrame(annotate_morphemes(tk), columns=['Морфема', 'Тег']).set_index(['Морфема']), key=f'dataframe_{i}')
105
+ else:
106
+ st.dataframe(pd.DataFrame(annotate_morphemes(inpt), columns=['Морфема', 'Тег']).set_index(['Морфема']))
prefixes.txt ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ а
2
+ агит
3
+ ан
4
+ англо
5
+ анти
6
+ архи
7
+ атто
8
+ без
9
+ бес
10
+ брам
11
+ в
12
+ вз
13
+ вне
14
+ военно
15
+ воз
16
+ вос
17
+ вы
18
+ гекса
19
+ гексаконта
20
+ гекта
21
+ гекто
22
+ гепта
23
+ гептаконта
24
+ гига
25
+ гипер
26
+ гор
27
+ гос
28
+ де
29
+ дез
30
+ дека
31
+ деци
32
+ дикта
33
+ до
34
+ додека
35
+ за
36
+ зепто
37
+ зетта
38
+ из
39
+ изо
40
+ ил
41
+ им
42
+ ин
43
+ интер
44
+ интервики
45
+ интра
46
+ инфра
47
+ ир
48
+ ис
49
+ йокто
50
+ йотта
51
+ к
52
+ квадра
53
+ квази
54
+ кила
55
+ кило
56
+ ко
57
+ кое
58
+ кой
59
+ контр
60
+ лейб
61
+ мега
62
+ меж
63
+ междо
64
+ между
65
+ микро
66
+ милли
67
+ мини
68
+ мириа
69
+ моно
70
+ на
71
+ над
72
+ наи
73
+ нано
74
+ не
75
+ небез
76
+ небес
77
+ недо
78
+ ни
79
+ низ
80
+ низо
81
+ нис
82
+ нона
83
+ о
84
+ обез
85
+ обес
86
+ около
87
+ окта
88
+ октаконта
89
+ от
90
+ па
91
+ пара
92
+ пентаконта
93
+ пере
94
+ перед
95
+ пета
96
+ пико
97
+ по
98
+ под
99
+ подъ
100
+ поза
101
+ после
102
+ пост
103
+ пра
104
+ пре
105
+ пред
106
+ преди
107
+ при
108
+ про
109
+ противо
110
+ прото
111
+ раз
112
+ рас
113
+ ре
114
+ роз
115
+ рос
116
+ с
117
+ санти
118
+ сверх
119
+ со
120
+ среди
121
+ су
122
+ суб
123
+ супер
124
+ супра
125
+ сюр
126
+ тера
127
+ тетра
128
+ тетраконта
129
+ транс
130
+ тре
131
+ три
132
+ триаконта
133
+ тридека
134
+ трикта
135
+ у
136
+ ультра
137
+ ундека
138
+ фемто
139
+ черес
140
+ эйкоза
141
+ экзо
142
+ экс
143
+ экса
144
+ экстра
145
+ эннеаконта
requirements.txt CHANGED
@@ -1,4 +1,2 @@
1
  numpy
2
- pandas
3
- keras==2.12.0
4
- tensorflow==2.12.0
 
1
  numpy
2
+ pandas
 
 
rnc_morphemer/NeuralMorphemeSegmentation/neural_morph_segm.py DELETED
@@ -1,956 +0,0 @@
1
- import sys
2
- import os
3
- import inspect
4
- import bisect
5
- from itertools import chain
6
- from collections import defaultdict
7
- import numpy as np
8
-
9
- import json
10
- # import ujson as json
11
-
12
- import keras.layers as kl
13
- import keras.backend as kb
14
- from keras.models import Model
15
- from keras.optimizers import Adam
16
- from keras.callbacks import ModelCheckpoint, EarlyStopping
17
-
18
- from .read import extract_morpheme_type, read_BMES, read_splitted
19
- from .tabled_trie import make_trie
20
-
21
-
22
- def read_config(infile):
23
- with open(infile, "r", encoding="utf8") as fin:
24
- config = json.load(fin)
25
- if "use_morpheme_types" not in config:
26
- config["use_morpheme_types"] = True
27
- return config
28
-
29
- # вспомогательные фунцкии
30
-
31
- def to_one_hot(data, classes_number):
32
- answer = np.eye(classes_number, dtype=np.uint8)
33
- return answer[data]
34
-
35
- def make_model_file(name, i):
36
- pos = name.rfind(".")
37
- if pos != -1:
38
- return "{}-{}.{}".format(name[:pos], i, name[pos+1:])
39
- else:
40
- return "{}-{}".format(name, i)
41
-
42
-
43
- AUXILIARY_CODES = PAD, BEGIN, END, UNKNOWN = 0, 1, 2, 3
44
- AUXILIARY = ['PAD', 'BEGIN', 'END', 'UNKNOWN']
45
-
46
-
47
- def _make_vocabulary(source):
48
- """
49
- Создаёт словарь символов.
50
- """
51
- symbols = {a for word in source for a in word}
52
- symbols = AUXILIARY + sorted(symbols)
53
- symbol_codes = {a: i for i, a in enumerate(symbols)}
54
- return symbols, symbol_codes
55
-
56
- def make_bucket_lengths(lengths, buckets_number):
57
- """
58
- Вычисляет максимальные длины элементов в корзинах. Каждая корзина состоит из элементов примерно одинаковой длины
59
- """
60
- m = len(lengths)
61
- lengths = sorted(lengths)
62
- last_bucket_length, bucket_lengths = 0, []
63
- for i in range(buckets_number):
64
- # могут быть проблемы с выбросами большой длины
65
- level = (m * (i + 1) // buckets_number) - 1
66
- curr_length = lengths[level]
67
- if curr_length > last_bucket_length:
68
- bucket_lengths.append(curr_length)
69
- last_bucket_length = curr_length
70
- return bucket_lengths
71
-
72
- def collect_buckets(lengths, buckets_number, max_bucket_size=-1):
73
- """
74
- Распределяет элементы по корзинам
75
- """
76
- bucket_lengths = make_bucket_lengths(lengths, buckets_number)
77
- indexes = [[] for _ in bucket_lengths]
78
- for i, length in enumerate(lengths):
79
- index = bisect.bisect_left(bucket_lengths, length)
80
- indexes[index].append(i)
81
- if max_bucket_size != -1:
82
- bucket_lengths = list(chain.from_iterable(
83
- ([L] * ((len(curr_indexes)-1) // max_bucket_size + 1))
84
- for L, curr_indexes in zip(bucket_lengths, indexes)
85
- if len(curr_indexes) > 0))
86
- indexes = [curr_indexes[start:start+max_bucket_size]
87
- for curr_indexes in indexes
88
- for start in range(0, len(curr_indexes), max_bucket_size)]
89
- return [(L, curr_indexes) for L, curr_indexes
90
- in zip(bucket_lengths, indexes) if len(curr_indexes) > 0]
91
-
92
- def load_cls(infile):
93
- with open(infile, "r", encoding="utf8") as fin:
94
- json_data = json.load(fin)
95
- args = {key: value for key, value in json_data.items()
96
- if not (key.endswith("_") or key.endswith("callback") or key == "model_files")}
97
- args['callbacks'] = []
98
- # создаём классификатор
99
- inflector = Partitioner(**args)
100
- # обучаемые параметры
101
- args = {key: value for key, value in json_data.items() if key[-1] == "_"}
102
- for key, value in args.items():
103
- setattr(inflector, key, value)
104
- if hasattr(inflector, "morphemes_"):
105
- inflector._make_morpheme_tries()
106
- # модель
107
- inflector.build() # не работает сохранение/загрузка модели, приходится перекомпилировать
108
- for i, (model, model_file) in enumerate(
109
- zip(inflector.models_, json_data['model_files'])):
110
- model.load_weights(model_file)
111
- return inflector
112
-
113
-
114
- MORPHEME_TYPES = ["PREF", "ROOT", "LINK", "END", "POST", "HYPN"]
115
- PREF, ROOT, LINK, SUFF, ENDING, POST, HYPN, FINAL = 0, 1, 2, 3, 4, 5, 6, 7
116
-
117
-
118
- def get_next_morpheme_types(morpheme_type):
119
- """
120
- Определяет, какие морфемы могут идти за текущей.
121
- """
122
- if morpheme_type == "None":
123
- return ["None"]
124
- MORPHEMES = ["SUFF", "END", "LINK", "POST", "PREF", "ROOT"]
125
- if morpheme_type in ["ROOT", "SUFF", "HYPN"]:
126
- start = 0
127
- elif morpheme_type == "END":
128
- start = 2
129
- elif morpheme_type in ["PREF", "LINK", "BEGIN"]:
130
- start = 4
131
- else:
132
- start = 6
133
- answer = MORPHEMES[start:6]
134
- if len(answer) > 0 and morpheme_type != "HYPN":
135
- answer.append("HYPN")
136
- if morpheme_type == "BEGIN":
137
- answer.append("None")
138
- return answer
139
-
140
- def get_next_morpheme(morpheme):
141
- """
142
- Строит список меток, которые могут идти за текущей
143
- """
144
- if morpheme == "BEGIN":
145
- morpheme = "S-BEGIN"
146
- morpheme_label, morpheme_type = morpheme.split("-")
147
- if morpheme_label in "BM":
148
- new_morpheme_labels = "ME"
149
- new_morpheme_types = [morpheme_type]
150
- else:
151
- new_morpheme_labels = "BS"
152
- new_morpheme_types = get_next_morpheme_types(morpheme_type)
153
- answer = ["{}-{}".format(x, y) for x in new_morpheme_labels for y in new_morpheme_types]
154
- return answer
155
-
156
-
157
- def is_correct_morpheme_sequence(morphemes):
158
- """
159
- Проверяет список морфемных меток на корректность
160
- """
161
- if morphemes == []:
162
- return False
163
- if any("-" not in morpheme for morpheme in morphemes):
164
- return False
165
- morpheme_label, morpheme_type = morphemes[0].split("-")
166
- if morpheme_label not in "BS" or morpheme_type not in ["PREF", "ROOT", "None"]:
167
- return False
168
- morpheme_label, morpheme_type = morphemes[-1].split("-")
169
- if morpheme_label not in "ES" or morpheme_type not in ["ROOT", "SUFF", "ENDING", "POST", "None"]:
170
- return False
171
- for i, morpheme in enumerate(morphemes[:-1]):
172
- if morphemes[i+1] not in get_next_morpheme(morpheme):
173
- return False
174
- return True
175
-
176
-
177
- class Partitioner:
178
-
179
- """
180
- models_number: int, default=1, число моделей
181
- to_memorize_morphemes: bool, default=False,
182
- производится ли запоминание морфемных энграмм
183
- min_morpheme_count: int, default=2,
184
- минимальное количество раз, которое должна встречаться запоминаемая морфема
185
- to_memorize_ngram_counts: bool, default=False,
186
- используются ли частоты энграмм как морфем при вычислении признаков
187
- min_relative_ngram_count: float, default=0.1,
188
- минимальное отношение частоты энграммы как морфемы к её общей частоте,
189
- необходимое для её запоминания
190
- use_embeddings: bool, default=False,
191
- используется ли дополнительный слой векторных представлений символов
192
- embeddings_size: int, default=32, размер символьного представления
193
- conv_layers: int, default=1, число свёрточных слоёв
194
- window_size: int or list of ints, список размеров окна в свёрточном слое
195
- filters_number: int or list of ints or list of list of ints,
196
- число фильтров в свёрточных слоях,
197
- filters_number[i,j] --- число фильтров для i-го окна j-го слоя,
198
- если задан список, то filters_number[j] --- число фильтров в окнах j-го слоя,
199
- если число --- то одно и то же число фильтров для всех слоёв и окон
200
- dense_output_units: int, default=0,
201
- число нейронов на дополнительном слое перед вычислением выходных вероятностей.
202
- если 0, то этот слой отсутствует
203
- use_lstm: bool, default=False,
204
- используется ли дополнительный выходной слой LSTM (ухудшает качество)
205
- lstm_units: int, default=64, число нейронов в LSTM-слое
206
- dropout: float, default=0.0
207
- доля выкидываемых нейронов в dropout-слое, помогает бороться с переобучением
208
- context_dropout: float, default=0.0,
209
- вероятность маскировки векторного представления контекста
210
- buckets_number: int, default=10,
211
- число корзин, в одну корзину попадают данные примерно одинаковой длины
212
- nepochs: int, default=10, число эпох в обучении
213
- validation_split: float, default=0.2, доля элементов в развивающей выборке
214
- batch_size: int, default=32, число элементов в одном батче
215
- callbacks: list of keras.callbacks or None, default=None,
216
- коллбэки для управления процессом обучения,
217
- early_stopping: int, default=None,
218
- число эпох, в течение которого не должно улучшаться качество
219
- на валидационной выборке, чтобы обучение остановилось,
220
- если None, то в любом случае модель обучается nepochs эпох
221
- """
222
-
223
- LEFT_MORPHEME_TYPES = ["pref", "root"]
224
- RIGHT_MORPHEME_TYPES = ["root", "suff", "end", "post"]
225
-
226
- def __init__(self, models_number=1, use_morpheme_types=True,
227
- to_memorize_morphemes=False, min_morpheme_count=2,
228
- to_memorize_ngram_counts=False, min_relative_ngram_count=0.1,
229
- use_embeddings=False, embeddings_size=32,
230
- conv_layers=1, window_size=5, filters_number=64,
231
- dense_output_units=0, use_lstm=False, lstm_units=64,
232
- dropout=0.0, context_dropout=0.0,
233
- buckets_number=10, nepochs=10,
234
- validation_split=0.2, batch_size=32,
235
- callbacks=None, early_stopping=None):
236
- self.models_number = models_number
237
- self.use_morpheme_types = use_morpheme_types
238
- self.to_memorize_morphemes = to_memorize_morphemes
239
- self.min_morpheme_count = min_morpheme_count
240
- self.to_memorize_ngram_counts = to_memorize_ngram_counts
241
- self.min_relative_ngram_count = min_relative_ngram_count
242
- self.use_embeddings = use_embeddings
243
- self.embeddings_size = embeddings_size
244
- self.conv_layers = conv_layers
245
- self.window_size = window_size
246
- self.filters_number = filters_number
247
- self.dense_output_units = dense_output_units
248
- self.use_lstm = use_lstm
249
- self.lstm_units = lstm_units
250
- self.dropout = dropout
251
- self.context_dropout = context_dropout
252
- self.buckets_number = buckets_number
253
- self.nepochs = nepochs
254
- self.validation_split = validation_split
255
- self.batch_size = batch_size
256
- self.callbacks = callbacks
257
- self.early_stopping = early_stopping
258
- self.check_params()
259
-
260
- def check_params(self):
261
- if isinstance(self.window_size, int):
262
- # если было только одно окно в свёрточных слоях
263
- self.window_size = [self.window_size]
264
- # приводим фильтры к двумерному виду
265
- self.filters_number = np.atleast_2d(self.filters_number)
266
- if self.filters_number.shape[0] == 1:
267
- self.filters_number = np.repeat(self.filters_number, len(self.window_size), axis=0)
268
- if self.filters_number.shape[0] != len(self.window_size):
269
- raise ValueError("Filters array should have shape (len(window_size), conv_layers)")
270
- if self.filters_number.shape[1] == 1:
271
- self.filters_number = np.repeat(self.filters_number, self.conv_layers, axis=1)
272
- if self.filters_number.shape[1] != self.conv_layers:
273
- raise ValueError("Filters array should have shape (len(window_size), conv_layers)")
274
- # переводим в список из int, а не np.int32, чтобы не было проблем при сохранении
275
- self.filters_number = list([list(map(int, x)) for x in self.filters_number])
276
- if self.callbacks is None:
277
- self.callbacks = []
278
- if (self.early_stopping is not None and
279
- not any(isinstance(x, EarlyStopping) for x in self.callbacks)):
280
- self.callbacks.append(EarlyStopping(patience=self.early_stopping, monitor="val_acc"))
281
- if self.use_morpheme_types:
282
- self._morpheme_memo_func = self._make_morpheme_data
283
- else:
284
- self._morpheme_memo_func = self._make_morpheme_data_simple
285
-
286
- def to_json(self, outfile, model_file=None):
287
- info = dict()
288
- if model_file is None:
289
- pos = outfile.rfind(".")
290
- model_file = outfile[:pos] + ("-model.hdf5" if pos != -1 else "-model")
291
- model_files = [make_model_file(model_file, i+1) for i in range(self.models_number)]
292
- for i in range(self.models_number):
293
- # при сохранении нужен абсолютный путь, а не от текущей директории
294
- model_files[i] = os.path.abspath(model_files[i])
295
- for (attr, val) in inspect.getmembers(self):
296
- # перебираем поля класса и сохраняем только задаваемые при инициализации
297
- if not (attr.startswith("__") or inspect.ismethod(val) or
298
- isinstance(getattr(Partitioner, attr, None), property) or
299
- attr.isupper() or attr in [
300
- "callbacks", "models_", "left_morphemes_", "right_morphemes_", "morpheme_trie_"]):
301
- info[attr] = val
302
- elif attr == "models_":
303
- # для каждой модели сохраняем веса
304
- info["model_files"] = model_files
305
- for model, curr_model_file in zip(self.models_, model_files):
306
- model.save_weights(curr_model_file)
307
- with open(outfile, "w", encoding="utf8") as fout:
308
- json.dump(info, fout)
309
-
310
- # property --- функция, прикидывающаяся переменной; декоратор метода (превращает метод класса в атрибут класса)
311
- @property
312
- def symbols_number_(self):
313
- return len(self.symbols_)
314
-
315
- @property
316
- def target_symbols_number_(self):
317
- return len(self.target_symbols_)
318
-
319
- @property
320
- def memory_dim(self):
321
- return 15 if self.use_morpheme_types else 3
322
-
323
- def _preprocess(self, data, targets=None):
324
- # к каждому слову добавляются символы начала и конца строки
325
- lengths = [len(x) + 2 for x in data]
326
- # разбиваем данные на корзины
327
- buckets_with_indexes = collect_buckets(lengths, self.buckets_number)
328
- # преобразуем данные в матрицы в каждой корзине
329
- data_by_buckets = [self._make_bucket_data(data, length, indexes)
330
- for length, indexes in buckets_with_indexes]
331
- # targets=None --- предсказание, иначе --- обучение
332
- if targets is not None:
333
- targets_by_buckets = [self._make_bucket_data(targets, length, indexes, is_target=True)
334
- for length, indexes in buckets_with_indexes]
335
- return data_by_buckets, targets_by_buckets, buckets_with_indexes
336
- else:
337
- return data_by_buckets, buckets_with_indexes
338
-
339
- def _make_bucket_data(self, data, bucket_length, bucket_indexes, is_target=False):
340
- """
341
- data: list of lists, исходные данные
342
- bucket_length: int, максимальная длина элемента в корзине
343
- bucket_indexes: list of ints, индексы элементов в корзине
344
- is_target: boolean, default=False,
345
- являются ли данные исходными или ответами
346
-
347
- answer = [symbols, (classes)],
348
- symbols: array of shape (len(data), bucket_length)
349
- элементы data, дополненные символом PAD справа до bucket_length
350
- classes: array of shape (len(data), classes_number)
351
- """
352
- bucket_data = [data[i] for i in bucket_indexes]
353
- if is_target:
354
- return self._recode_bucket_data(bucket_data, bucket_length, self.target_symbol_codes_)
355
- else:
356
- answer = [self._recode_bucket_data(bucket_data, bucket_length, self.symbol_codes_)]
357
- if self.to_memorize_morphemes:
358
- print("Processing morphemes for bucket length", bucket_length)
359
- answer.append(self._morpheme_memo_func(bucket_data, bucket_length))
360
- print("Processing morphemes for bucket length", bucket_length, "finished")
361
- return answer
362
-
363
- def _recode_bucket_data(self, data, bucket_length, encoding):
364
- answer = np.full(shape=(len(data), bucket_length), fill_value=PAD, dtype=int)
365
- answer[:,0] = BEGIN
366
- for j, word in enumerate(data):
367
- answer[j,1:1+len(word)] = [encoding.get(x, UNKNOWN) for x in word]
368
- answer[j,1+len(word)] = END
369
- return answer
370
-
371
- def _make_morpheme_data(self, data, bucket_length):
372
- """
373
- строит для каждой позиции во входных словах вектор, кодирующий энграммы в контексте
374
-
375
- data: list of strs, список исходных слов
376
- bucket_length: int, максимальная длина слова в корзине
377
-
378
- answer: np.array[float] of shape (len(data), bucket_length, 15)
379
- """
380
- answer = np.zeros(shape=(len(data), bucket_length, 15), dtype=float)
381
- for j, word in enumerate(data):
382
- m = len(word)
383
- curr_answer = np.zeros(shape=(bucket_length, 15), dtype=int)
384
- root_starts = [0]
385
- ending_ends = [m]
386
- prefixes = self.left_morphemes_["pref"].descend_by_prefixes(word[:-1])
387
- for end in prefixes:
388
- score = self._get_ngram_score(word[:end], "pref")
389
- if end == 1:
390
- curr_answer[1,10] = max(score, curr_answer[1,10])
391
- else:
392
- curr_answer[1,0] = max(score, curr_answer[1,0])
393
- curr_answer[end, 5] = max(score, curr_answer[end, 5])
394
- root_starts += prefixes
395
- postfix_lengths = self.right_morphemes_["post"].descend_by_prefixes(word[:0:-1])
396
- for k in postfix_lengths:
397
- score = self._get_ngram_score(word[-k:], "post")
398
- if k == 1:
399
- curr_answer[m, 14] = max(score, curr_answer[m, 14])
400
- else:
401
- curr_answer[m, 9] = max(score, curr_answer[m, 9])
402
- curr_answer[m-k+1,4] = max(score, curr_answer[m-k+1,4])
403
- ending_ends.append(m-k)
404
- suffix_ends = set(ending_ends)
405
- for end in ending_ends[::-1]:
406
- ending_lengths = self.right_morphemes_["end"].descend_by_prefixes(word[end-1:0:-1])
407
- for k in ending_lengths:
408
- score = self._get_ngram_score(word[end-k:end], "end")
409
- if k == 1:
410
- curr_answer[end, 13] = max(score, curr_answer[end, 13])
411
- else:
412
- curr_answer[end-k+1, 3] = max(score, curr_answer[end-k+1, 3])
413
- curr_answer[end, 8] = max(score, curr_answer[end, 8])
414
- suffix_ends.add(end-k)
415
- suffixes = self.right_morphemes_["suff"].descend_by_prefixes(
416
- word[::-1], start_pos=[m-k for k in suffix_ends], max_count=3, return_pairs=True)
417
- suffix_starts = suffix_ends
418
- for first, last in suffixes:
419
- score = self._get_ngram_score(word[m-last:m-first], "suff")
420
- if last == first + 1:
421
- curr_answer[m-first, 12] = max(score, curr_answer[m-first, 12])
422
- else:
423
- curr_answer[m-last+1, 2] = max(score, curr_answer[m-last+1, 2])
424
- curr_answer[m-first, 7] = max(score, curr_answer[m-first, 7])
425
- suffix_starts.add(m-last)
426
- for start in root_starts:
427
- root_ends = self.left_morphemes_["root"].descend_by_prefixes(word[start:])
428
- for end in root_ends:
429
- score = self._get_ngram_score(word[start:end], "root")
430
- if end == start+1:
431
- curr_answer[start + 1, 11] = max(score, curr_answer[start + 1, 11])
432
- else:
433
- curr_answer[start + 1, 1] = max(score, curr_answer[start + 1, 1])
434
- curr_answer[end, 6] = max(score, curr_answer[end, 6])
435
- for end in suffix_starts:
436
- root_lengths = self.right_morphemes_["root"].descend_by_prefixes(word[end-1:-1:-1])
437
- for k in root_lengths:
438
- score = self._get_ngram_score(word[end-k:end], 'root')
439
- if k == 1:
440
- curr_answer[end, 11] = max(curr_answer[end, 11], score)
441
- else:
442
- curr_answer[end-k+1, 1] = max(curr_answer[end-k+1, 1], score)
443
- curr_answer[end, 6] = max(curr_answer[end, 6], score)
444
- answer[j] = curr_answer
445
- return answer
446
-
447
- def _make_morpheme_data_simple(self, data, bucket_length):
448
- answer = np.zeros(shape=(len(data), bucket_length, 3), dtype=float)
449
- for j, word in enumerate(data):
450
- m = len(word)
451
- curr_answer = np.zeros(shape=(bucket_length, 3), dtype=int)
452
- positions = self.morpheme_trie_.find_substrings(word, return_positions=True)
453
- for starts, end in positions:
454
- for start in starts:
455
- score = self._get_ngram_score(word[start:end])
456
- if end == start+1:
457
- curr_answer[start+1, 2] = max(curr_answer[start+1, 2], score)
458
- else:
459
- curr_answer[start+1, 0] = max(curr_answer[start+0, 2], score)
460
- curr_answer[end, 1] = max(curr_answer[end, 1], score)
461
- answer[j] = curr_answer
462
- return answer
463
-
464
- def _get_ngram_score(self, ngram, mode="None"):
465
- if self.to_memorize_ngram_counts:
466
- return self.morpheme_counts_[mode].get(ngram, 0)
467
- else:
468
- return 1.0
469
-
470
- def train(self, source, targets, dev=None, dev_targets=None, model_file=None):
471
- """
472
-
473
- source: list of strs, список слов для морфемоделения
474
- targets: list of strs, метки морфемоделения в формате BMES
475
- model_file: str or None, default=None, файл для сохранения моделей
476
-
477
- Возвращает:
478
- -------------
479
- self, обученный морфемоделитель
480
- """
481
- self.symbols_, self.symbol_codes_ = _make_vocabulary(source)
482
- self.target_symbols_, self.target_symbol_codes_ = _make_vocabulary(targets)
483
- if self.to_memorize_morphemes:
484
- self._memorize_morphemes(source, targets)
485
-
486
- data_by_buckets, targets_by_buckets, _ = self._preprocess(source, targets)
487
- if dev is not None:
488
- dev_data_by_buckets, dev_targets_by_buckets, _ = self._preprocess(dev, dev_targets)
489
- else:
490
- dev_data_by_buckets, dev_targets_by_buckets = None, None
491
- self.build()
492
- self._train_models(data_by_buckets, targets_by_buckets, dev_data_by_buckets,
493
- dev_targets_by_buckets, model_file=model_file)
494
- return self
495
-
496
- def build(self):
497
- """
498
- Создаёт нейронные модели
499
- """
500
- self.models_ = [self.build_model() for _ in range(self.models_number)]
501
- print(self.models_[0].summary())
502
- return self
503
-
504
- def build_model(self):
505
- """
506
- Функция, задающая архитектуру нейронной сети
507
- """
508
- # symbol_inputs: array, 1D-массив длины m
509
- symbol_inputs = kl.Input(shape=(None,), dtype='uint8', name="symbol_inputs")
510
- # symbol_embeddings: array, 2D-массив размера m*self.symbols_number
511
- if self.use_embeddings:
512
- symbol_embeddings = kl.Embedding(self.symbols_number_, self.embeddings_size,
513
- name="symbol_embeddings")(symbol_inputs)
514
- else:
515
- symbol_embeddings = kl.Lambda(kb.one_hot, output_shape=(None, self.symbols_number_),
516
- arguments={"num_classes": self.symbols_number_},
517
- name="symbol_embeddings")(symbol_inputs)
518
- inputs = [symbol_inputs]
519
- if self.to_memorize_morphemes:
520
- # context_inputs: array, 2D-массив размера m*15
521
- context_inputs = kl.Input(shape=(None, self.memory_dim), dtype='float32', name="context_inputs")
522
- inputs.append(context_inputs)
523
- if self.context_dropout > 0.0:
524
- context_inputs = kl.Dropout(self.context_dropout)(context_inputs)
525
- # представление контекста подклеивается к представлению символа
526
- symbol_embeddings = kl.Concatenate()([symbol_embeddings, context_inputs])
527
- conv_inputs = symbol_embeddings
528
- conv_outputs = []
529
- for window_size, curr_filters_numbers in zip(self.window_size, self.filters_number):
530
- # свёрточный слой отдельно для каждой ширины окна
531
- curr_conv_input = conv_inputs
532
- for j, filters_number in enumerate(curr_filters_numbers[:-1]):
533
- # все слои свёртки, кроме финального (после них возможен dropout)
534
- curr_conv_input = kl.Conv1D(filters_number, window_size,
535
- activation="relu", padding="same")(curr_conv_input)
536
- if self.dropout > 0.0:
537
- # между однотипными слоями рекомендуется вставить dropout
538
- curr_conv_input = kl.Dropout(self.dropout)(curr_conv_input)
539
- if not self.use_lstm:
540
- curr_conv_output = kl.Conv1D(curr_filters_numbers[-1], window_size,
541
- activation="relu", padding="same")(curr_conv_input)
542
- else:
543
- curr_conv_output = curr_conv_input
544
- conv_outputs.append(curr_conv_output)
545
- # соединяем выходы всех свёрточных слоёв в один вектор
546
- if len(conv_outputs) == 1:
547
- conv_output = conv_outputs[0]
548
- else:
549
- conv_output = kl.Concatenate(name="conv_output")(conv_outputs)
550
- if self.use_lstm:
551
- conv_output = kl.Bidirectional(
552
- kl.LSTM(self.lstm_units, return_sequences=True))(conv_output)
553
- if self.dense_output_units:
554
- pre_last_output = kl.TimeDistributed(
555
- kl.Dense(self.dense_output_units, activation="relu"),
556
- name="pre_output")(conv_output)
557
- else:
558
- pre_last_output = conv_output
559
- # финальный слой с softmax-активацией, чтобы получить распределение вероятностей
560
- output = kl.TimeDistributed(
561
- kl.Dense(self.target_symbols_number_, activation="softmax"), name="output")(pre_last_output)
562
- model = Model(inputs, [output])
563
- model.compile(optimizer=Adam(clipnorm=5.0),
564
- loss="categorical_crossentropy", metrics=["accuracy"])
565
- return model
566
-
567
- def _train_models(self, data_by_buckets, targets_by_buckets,
568
- dev_data_by_buckets=None, dev_targets_by_buckets=None, model_file=None):
569
- """
570
- data_by_buckets: list of lists of np.arrays,
571
- data_by_buckets[i] = [..., bucket_i, ...],
572
- bucket = [input_1, ..., input_k],
573
- input_j --- j-ый вход нейронной сети, вычисленный для текущей корзины
574
- targets_by_buckets: list of np.arrays,
575
- targets_by_buckets[i] --- закодированные ответы для i-ой корзины
576
- model_file: str or None, путь к файлу для сохранения модели
577
- """
578
- train_indexes_by_buckets, dev_indexes_by_buckets = [], []
579
- if dev_data_by_buckets is not None:
580
- train_indexes_by_buckets = [list(range(len(bucket[0]))) for bucket in data_by_buckets]
581
- for elem in train_indexes_by_buckets:
582
- np.random.shuffle(elem)
583
- dev_indexes_by_buckets = [list(range(len(bucket[0]))) for bucket in dev_data_by_buckets]
584
- train_data, dev_data = data_by_buckets, dev_data_by_buckets
585
- train_targets, dev_targets = targets_by_buckets, dev_targets_by_buckets
586
- else:
587
- for bucket in data_by_buckets:
588
- # разбиваем каждую корзину на обучающую и валидационную выборку
589
- L = len(bucket[0])
590
- indexes_for_bucket = list(range(L))
591
- np.random.shuffle(indexes_for_bucket)
592
- train_bucket_length = int(L*(1.0 - self.validation_split))
593
- train_indexes_by_buckets.append(indexes_for_bucket[:train_bucket_length])
594
- dev_indexes_by_buckets.append(indexes_for_bucket[train_bucket_length:])
595
- train_data, dev_data = data_by_buckets, data_by_buckets
596
- train_targets, dev_targets = targets_by_buckets, targets_by_buckets
597
- # разбиваем на батчи обучающую и валидационную выборку
598
- # (для валидационной этого можно не делать, а подавать сразу корзины)
599
- train_batches_indexes = list(chain.from_iterable(
600
- [[(i, elem[j:j+self.batch_size]) for j in range(0, len(elem), self.batch_size)]
601
- for i, elem in enumerate(train_indexes_by_buckets)]))
602
- dev_batches_indexes = list(chain.from_iterable(
603
- [[(i, elem[j:j+self.batch_size]) for j in range(0, len(elem), self.batch_size)]
604
- for i, elem in enumerate(dev_indexes_by_buckets)]))
605
- # поскольку функции fit_generator нужен генератор, порождающий batch за batch'ем,
606
- # то приходится заводить генераторы для обеих выборок
607
- train_gen = generate_data(train_data, train_targets, train_batches_indexes,
608
- classes_number=self.target_symbols_number_, shuffle=True)
609
- val_gen = generate_data(dev_data, dev_targets, dev_batches_indexes,
610
- classes_number=self.target_symbols_number_, shuffle=False)
611
- for i, model in enumerate(self.models_):
612
- if model_file is not None:
613
- curr_model_file = make_model_file(model_file, i+1)
614
- # для сохранения модели с наилучшим результатом на валидационной выборке
615
- save_callback = ModelCheckpoint(curr_model_file, save_weights_only=True, save_best_only=True)
616
- curr_callbacks = self.callbacks + [save_callback]
617
- else:
618
- curr_callbacks = self.callbacks
619
- model.fit_generator(train_gen, len(train_batches_indexes),
620
- epochs=self.nepochs, callbacks=curr_callbacks,
621
- validation_data=val_gen, validation_steps=len(dev_batches_indexes))
622
- if model_file is not None:
623
- model.load_weights(curr_model_file)
624
- return self
625
-
626
- def _memorize_morphemes(self, words, targets):
627
- """
628
- запоминает морфемы. встречающиеся в словах обучающей выборки
629
- """
630
- morphemes = defaultdict(lambda: defaultdict(int))
631
- for word, target in zip(words, targets):
632
- start = None
633
- for i, (symbol, label) in enumerate(zip(word, target)):
634
- if label.startswith("B-"):
635
- start = i
636
- elif label.startswith("E-"):
637
- dest = extract_morpheme_type(label)
638
- morphemes[dest][word[start:i+1]] += 1
639
- elif label.startswith("S-"):
640
- dest = extract_morpheme_type(label)
641
- morphemes[dest][word[i]] += 1
642
- elif label == END:
643
- break
644
- self.morphemes_ = dict()
645
- for key, counts in morphemes.items():
646
- self.morphemes_[key] = [x for x, count in counts.items() if count >= self.min_morpheme_count]
647
- self._make_morpheme_tries()
648
- if self.to_memorize_ngram_counts:
649
- self._memorize_ngram_counts(words, morphemes)
650
- return self
651
-
652
- def _memorize_ngram_counts(self, words, counts):
653
- """
654
- запоминает частоты морфем, встречающихся в словах обучающей выборки
655
- """
656
- prefix_counts, suffix_counts, ngram_counts = defaultdict(int), defaultdict(int), defaultdict(int)
657
- for i, word in enumerate(words, 1):
658
- if i % 5000 == 0:
659
- print("{} words processed".format(i))
660
- positions = self.morpheme_trie_.find_substrings(word, return_positions=True)
661
- for starts, end in positions:
662
- for start in starts:
663
- segment = word[start:end]
664
- ngram_counts[segment] += 1
665
- if start == 0:
666
- prefix_counts[segment] += 1
667
- if end == len(word):
668
- suffix_counts[segment] += 1
669
- self.morpheme_counts_ = dict()
670
- for key, curr_counts in counts.items():
671
- curr_relative_counts = dict()
672
- curr_ngram_counts = (prefix_counts if key == "pref" else
673
- suffix_counts if key in ["end", "post"] else ngram_counts)
674
- for ngram, count in curr_counts.items():
675
- if count < self.min_morpheme_count or ngram not in curr_ngram_counts:
676
- continue
677
- relative_count = min(count / curr_ngram_counts[ngram], 1.0)
678
- if relative_count >= self.min_relative_ngram_count:
679
- curr_relative_counts[ngram] = relative_count
680
- self.morpheme_counts_[key] = curr_relative_counts
681
- return self
682
-
683
- def _make_morpheme_tries(self):
684
- """
685
- строит префиксный бор для морфем для более быстрого их поиска
686
- """
687
- self.left_morphemes_, self.right_morphemes_ = dict(), dict()
688
- if self.use_morpheme_types:
689
- for key in self.LEFT_MORPHEME_TYPES:
690
- self.left_morphemes_[key] = make_trie(list(self.morphemes_[key]))
691
- for key in self.RIGHT_MORPHEME_TYPES:
692
- self.right_morphemes_[key] = make_trie([x[::-1] for x in self.morphemes_[key]])
693
- if not self.use_morpheme_types or self.to_memorize_ngram_counts:
694
- morphemes = {x for elem in self.morphemes_.values() for x in elem}
695
- self.morpheme_trie_ = make_trie(list(morphemes))
696
- return self
697
-
698
- def _predict_probs(self, words):
699
- """
700
- data = [word_1, ..., word_m]
701
-
702
- Возвращает:
703
- -------------
704
- answer = [probs_1, ..., probs_m]
705
- probs_i = [p_1, ..., p_k], k = len(word_i)
706
- p_j = [p_j1, ..., p_jr], r --- число классов
707
- (len(AUXILIARY) + 4 * 4 (BMES; PREF, ROOT, SUFF, END) + 3 (BME; POSTFIX) + 2 * 1 (S; LINK, HYPHEN) = 23)
708
- """
709
- data_by_buckets, indexes_by_buckets = self._preprocess(words)
710
- word_probs = [None] * len(words)
711
- for r, (bucket_data, (_, bucket_indexes)) in\
712
- enumerate(zip(data_by_buckets, indexes_by_buckets), 1):
713
- print("Bucket {} predicting".format(r))
714
- bucket_probs = np.mean([model.predict(bucket_data) for model in self.models_], axis=0)
715
- for i, elem in zip(bucket_indexes, bucket_probs):
716
- word_probs[i] = elem
717
- answer = [None] * len(words)
718
- for i, (elem, word) in enumerate(zip(word_probs, words)):
719
- if i % 1000 == 0 and i > 0:
720
- print("{} words decoded".format(i))
721
- answer[i] = self._decode_best(elem, len(word))
722
- return answer
723
-
724
- def labels_to_morphemes(self, word, labels, probs=None, return_probs=False, return_types=False):
725
- """
726
-
727
- Преобразует ответ из формата BMES в список морфем
728
- Дополнительно может возвращать список вероятностей морфем
729
-
730
- word: str, текущее слово,
731
- labels: list of strs, предсказанные метки в формате BMES,
732
- probs: list of floats or None, предсказанные вероятности меток
733
-
734
- answer = [morphemes, (morpheme_probs), (morpheme_types)]
735
- morphemes: list of strs, список морфем
736
- morpheme_probs: list of floats, список вероятностей морфем
737
- morpheme_types: list of strs, список типов морфем
738
- """
739
- morphemes, curr_morpheme, morpheme_types = [], "", []
740
- if self.use_morpheme_types:
741
- end_labels = ['E-ROOT', 'E-PREF', 'E-SUFF', 'E-END', 'E-POST', 'S-ROOT',
742
- 'S-PREF', 'S-SUFF', 'S-END', 'S-LINK', 'S-HYPN']
743
- else:
744
- end_labels = ['E-None', 'S-None']
745
- for letter, label in zip(word, labels):
746
- curr_morpheme += letter
747
- if label in end_labels:
748
- morphemes.append(curr_morpheme)
749
- curr_morpheme = ""
750
- morpheme_types.append(label.split("-")[-1])
751
- if return_probs:
752
- if probs is None:
753
- Warning("Для вычисления вероятностей морфем нужно передать вероятности меток")
754
- return_probs = False
755
- if return_probs:
756
- morpheme_probs, curr_morpheme_prob = [], 1.0
757
- for label, prob in zip(labels, probs):
758
- curr_morpheme_prob *= prob[self.target_symbol_codes_[label]]
759
- if label in end_labels:
760
- morpheme_probs.append(curr_morpheme_prob)
761
- curr_morpheme_prob = 1.0
762
- answer = [morphemes, morpheme_probs]
763
- else:
764
- answer = [morphemes]
765
- if return_types:
766
- answer.append(morpheme_types)
767
- return answer
768
-
769
- def predict(self, words, return_probs=False):
770
- labels_with_probs = self._predict_probs(words)
771
- return [self.labels_to_morphemes(word, elem[0], elem[1], return_probs=return_probs)
772
- for elem, word in zip(labels_with_probs, words)]
773
-
774
- def _decode_best(self, probs, length):
775
- """
776
- Поддерживаем в каждой позиции наилучшие гипотезы для каждого состояния
777
- Состояние --- последняя предсказанняя метка
778
- """
779
- # вначале нужно проверить заведомо наилучший вариант на корректность
780
- best_states = np.argmax(probs[:1+length], axis=1)
781
- best_labels = [self.target_symbols_[state_index] for state_index in best_states]
782
- if not is_correct_morpheme_sequence(best_labels[1:]):
783
- # наилучший вариант оказался некорректным
784
- initial_costs = [np.inf] * self.target_symbols_number_
785
- initial_states = [None] * self.target_symbols_number_
786
- initial_costs[BEGIN], initial_states[BEGIN] = -np.log(probs[0, BEGIN]), BEGIN
787
- costs, states = [initial_costs], [initial_states]
788
- for i in range(length):
789
- # состояний мало, поэтому можно сортировать на каждом шаге
790
- state_order = np.argsort(costs[-1])
791
- curr_costs = [np.inf] * self.target_symbols_number_
792
- prev_states = [None] * self.target_symbols_number_
793
- inf_count = self.target_symbols_number_
794
- for prev_state in state_order:
795
- if np.isinf(costs[-1][prev_state]):
796
- break
797
- elif prev_state in AUXILIARY_CODES and i != 0:
798
- continue
799
- possible_states = self.get_possible_next_states(prev_state)
800
- for state in possible_states:
801
- if np.isinf(curr_costs[state]):
802
- # поскольку новая вероятность не зависит от state,
803
- # а старые перебираются по возрастанию штрафа,
804
- # то оптимальное значение будет при первом обновлении
805
- curr_costs[state] = costs[-1][prev_state] - np.log(probs[i+1,state])
806
- prev_states[state] = prev_state
807
- inf_count -= 1
808
- if inf_count == len(AUXILIARY_CODES):
809
- # все вероятности уже посчитаны
810
- break
811
- costs.append(curr_costs)
812
- states.append(prev_states)
813
- # последнее состояние --- обязательно конец морфемы
814
- possible_states = [self.target_symbol_codes_["{}-{}".format(x, y)]
815
- for x in "ES" for y in ["ROOT", "SUFF", "END", "POST", "None"]
816
- if "{}-{}".format(x, y) in self.target_symbol_codes_]
817
- best_states = [min(possible_states, key=(lambda x: costs[-1][x]))]
818
- for j in range(length, 0, -1):
819
- # предыдущее состояние
820
- best_states.append(states[j][best_states[-1]])
821
- best_states = best_states[::-1]
822
- probs_to_return = np.zeros(shape=(length, self.target_symbols_number_), dtype=np.float32)
823
- # убираем невозможные состояния
824
- for j, state in enumerate(best_states[:-1]):
825
- possible_states = self.get_possible_next_states(state)
826
- # оставляем только возможные состояния.
827
- probs_to_return[j,possible_states] = probs[j+1,possible_states]
828
- return [self.target_symbols_[i] for i in best_states[1:]], probs_to_return
829
-
830
- def get_possible_next_states(self, state_index):
831
- state = self.target_symbols_[state_index]
832
- next_states = get_next_morpheme(state)
833
- return [self.target_symbol_codes_[x] for x in next_states if x in self.target_symbol_codes_]
834
-
835
-
836
- def generate_data(data, targets, indexes, classes_number, shuffle=False, nepochs=None):
837
- """
838
-
839
- data: list of lists of arrays,
840
- data = [bucket_1, ..., bucket_m],
841
- bucket = [input_1, ..., input_k], k --- число входов в графе вычислений
842
- targets: list of arrays,
843
- targets[i,j] --- код j-ой метки при морфемоделении i-го слова
844
- indexes: list of pairs,
845
- indexes = [(i_1, bucket_indexes_1), ...]
846
- i_j --- номер корзины, откуда берутся элементы j-го батча
847
- bucket_indexes_j --- номера элементов j-го батча в соответствующей корзине
848
- shuffle: boolean, default=False, нужно ли перемешивать по��ядок батчей
849
- nepochs: int or None, default=None,
850
- число эпох, в течение которых генератор выдаёт батчи, в случае None генератор бесконечен
851
- :return:
852
- """
853
- nsteps = 0
854
- while nepochs is None or nsteps < nepochs:
855
- if shuffle:
856
- np.random.shuffle(indexes)
857
- for i, bucket_indexes in indexes:
858
- curr_bucket, curr_targets = data[i], targets[i]
859
- data_to_yield = [elem[bucket_indexes] for elem in curr_bucket]
860
- targets_to_yield = to_one_hot(curr_targets[bucket_indexes], classes_number)
861
- yield data_to_yield, targets_to_yield
862
- nsteps += 1
863
-
864
-
865
- def measure_quality(targets, predicted_targets, english_metrics=False, measure_last=True):
866
- """
867
-
868
- targets: метки корректных ответов
869
- predicted_targets: метки предсказанных ответов
870
-
871
- Возвращает словарь со значениями основных метрик
872
- """
873
- TP, FP, FN, equal, total = 0, 0, 0, 0, 0
874
- SE = ['{}-{}'.format(x, y) for x in "SE" for y in ["ROOT", "PREF", "SUFF", "END", "LINK", "None"]]
875
- # SE = ['S-ROOT', 'S-PREF', 'S-SUFF', 'S-END', 'S-LINK', 'E-ROOT', 'E-PREF', 'E-SUFF', 'E-END']
876
- corr_words = 0
877
- for corr, pred in zip(targets, predicted_targets):
878
- corr_len = len(corr) + int(measure_last) - 1
879
- pred_len = len(pred) + int(measure_last) - 1
880
- boundaries = [i for i in range(corr_len) if corr[i] in SE]
881
- pred_boundaries = [i for i in range(pred_len) if pred[i] in SE]
882
- common = [x for x in boundaries if x in pred_boundaries]
883
- TP += len(common)
884
- FN += len(boundaries) - len(common)
885
- FP += len(pred_boundaries) - len(common)
886
- equal += sum(int(x==y) for x, y in zip(corr, pred))
887
- total += len(corr)
888
- corr_words += (corr == pred)
889
- metrics = ["Точность", "Полнота", "F1-мера", "Корректность", "Точность по словам"]
890
- if english_metrics:
891
- metrics = ["Precision", "Recall", "F1", "Accuracy", "Word accuracy"]
892
- results = [TP / (TP+FP), TP / (TP+FN), TP / (TP + 0.5*(FP+FN)),
893
- equal / total, corr_words / len(targets)]
894
- answer = list(zip(metrics, results))
895
- return answer
896
-
897
-
898
- SHORT_ARGS = "a:"
899
-
900
- if __name__ == "__main__":
901
- np.random.seed(261) # для воспроизводимости
902
- if len(sys.argv) < 2:
903
- sys.exit("Pass config file")
904
- config_file = sys.argv[1]
905
- params = read_config(config_file)
906
- use_morpheme_types = params["use_morpheme_types"]
907
- read_func = read_BMES if use_morpheme_types else read_splitted
908
- if "train_file" in params:
909
- n = params.get("n_train") # число слов в обучающей+развивающей выборке
910
- inputs, targets = read_func(params["train_file"], n=n)
911
- if "dev_file" in params:
912
- n = params.get("n_dev") # число слов в обучающей+развивающей выборке
913
- dev_inputs, dev_targets = read_func(params["dev_file"], n=n)
914
- else:
915
- dev_inputs, dev_targets = None, None
916
- # inputs, targets = read_input(params["train_file"], n=n)
917
- else:
918
- inputs, targets, dev_inputs, dev_targets = None, None, None, None
919
- if not "load_file" in params:
920
- partitioner_params = params.get("model_params", dict())
921
- partitioner_params["use_morpheme_types"] = use_morpheme_types
922
- cls = Partitioner(**partitioner_params)
923
- else:
924
- cls = load_cls(params["load_file"])
925
- if inputs is not None:
926
- cls.train(inputs, targets, dev_inputs, dev_targets, model_file=params.get("model_file"))
927
- if "save_file" in params:
928
- model_file = params.get("model_file")
929
- cls.to_json(params["save_file"], model_file)
930
- if "test_file" in params:
931
- inputs, targets = read_func(params["test_file"], shuffle=False)
932
- # inputs, targets = read_input(params["test_file"])
933
- predicted_targets = cls._predict_probs(inputs)
934
- measure_last = params.get("measure_last", use_morpheme_types)
935
- quality = measure_quality(targets, [elem[0] for elem in predicted_targets],
936
- english_metrics=params.get("english_metrics", False),
937
- measure_last=measure_last)
938
- for key, value in sorted(quality):
939
- print("{}={:.2f}".format(key, 100*value))
940
- if "outfile" in params:
941
- outfile = params["outfile"]
942
- output_probs = params.get("output_probs", True)
943
- format_string = "{}\t{}\t{}\n" if output_probs else "{}\t{}\n"
944
- output_morpheme_types = params.get("output_morpheme_types", True)
945
- morph_format_string = "{}\t{}" if output_morpheme_types else "{}"
946
- with open(outfile, "w", encoding="utf8") as fout:
947
- for word, (labels, probs) in zip(inputs, predicted_targets):
948
- morphemes, morpheme_probs, morpheme_types = cls.labels_to_morphemes(
949
- word, labels, probs, return_probs=True, return_types=True)
950
- fout.write(format_string.format(
951
- word, "/".join(morph_format_string.format(*elem)
952
- for elem in zip(morphemes, morpheme_types)),
953
- " ".join("{:.2f}".format(100*x) for x in morpheme_probs)))
954
- # fout.write(format_string.format(
955
- # word, "#".join(morphemes), "-".join(
956
- # "{:.2f}/{}".format(100*x, y) for x, y in zip(morpheme_probs, morpheme_types))))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
rnc_morphemer/NeuralMorphemeSegmentation/read.py DELETED
@@ -1,155 +0,0 @@
1
- # чтение и разметка данных
2
- import numpy as np
3
-
4
-
5
- def generate_BMES(morphs, morph_types):
6
- answer = []
7
- for morph, morph_type in zip(morphs, morph_types):
8
- if len(morph) == 1:
9
- answer.append("S-" + morph_type)
10
- else:
11
- answer.append("B-" + morph_type)
12
- answer.extend(["M-" + morph_type] * (len(morph) - 2))
13
- answer.append("E-" + morph_type)
14
- return answer
15
-
16
-
17
- def read_splitted(infile, transform_to_BMES=True, n=None, morph_sep="/", shuffle=True):
18
- source, targets = [], []
19
- with open(infile, "r", encoding="utf8") as fin:
20
- for line in fin:
21
- line = line.strip()
22
- if line == "":
23
- break
24
- word, analysis = line.split("\t")
25
- morphs = analysis.split(morph_sep)
26
- morph_types = ["None"] * len(morphs)
27
- if transform_to_BMES:
28
- target = generate_BMES(morphs, morph_types)
29
- else:
30
- target = morph_types
31
- source.append(word)
32
- targets.append(target)
33
- indexes = list(range(len(source)))
34
- if shuffle:
35
- np.random.shuffle(indexes)
36
- if n is not None:
37
- indexes = indexes[:n]
38
- source = [source[i] for i in indexes]
39
- targets = [targets[i] for i in indexes]
40
- return source, targets
41
-
42
-
43
- def read_BMES(infile, transform_to_BMES=True, n=None,
44
- morph_sep="/" ,sep=":", shuffle=True):
45
- source, targets = [], []
46
- with open(infile, "r", encoding="utf8") as fin:
47
- for line in fin:
48
- line = line.strip()
49
- if line == "":
50
- break
51
- word, analysis = line.split("\t")
52
- analysis = [x.split(sep) for x in analysis.split(morph_sep)]
53
- morphs, morph_types = [elem[0] for elem in analysis], [elem[1] for elem in analysis]
54
- target = generate_BMES(morphs, morph_types) if transform_to_BMES else morphs
55
- source.append(word)
56
- targets.append(target)
57
- indexes = list(range(len(source)))
58
- if shuffle:
59
- np.random.shuffle(indexes)
60
- if n is not None:
61
- indexes = indexes[:n]
62
- source = [source[i] for i in indexes]
63
- targets = [targets[i] for i in indexes]
64
- return source, targets
65
-
66
-
67
- def partition_to_BMES(s1, s2):
68
- morphemes = s1.split("/")
69
- labels = s2.split(" , ")
70
- answer = []
71
- for l, m in zip(labels, morphemes):
72
- length = len(m)
73
- if l.startswith("Корень"):
74
- if m.startswith("-"):
75
- answer.append("S-HYPH")
76
- length -= 1
77
- if length == 1:
78
- answer.append("S-ROOT")
79
- else:
80
- answer.append("B-ROOT")
81
- for i in range(length-2):
82
- answer.append("M-ROOT")
83
- answer.append("E-ROOT")
84
-
85
- elif l.startswith("Приставка"):
86
- if m.startswith("-"):
87
- answer.append("S-HYPH")
88
- length -= 1
89
- if length == 1:
90
- answer.append("S-PREF")
91
- else:
92
- answer.append("B-PREF")
93
- for i in range(length-2):
94
- answer.append("M-PREF")
95
- answer.append("E-PREF")
96
-
97
- elif l.startswith("Суффикс"):
98
- if length == 1:
99
- answer.append("S-SUFF")
100
- else:
101
- answer.append("B-SUFF")
102
- for i in range(length-2):
103
- answer.append("M-SUFF")
104
- answer.append("E-SUFF")
105
-
106
- elif l.startswith("Соединительная гласная") is True:
107
- answer.append("S-LINK")
108
-
109
- elif l.startswith("Окончание") is True:
110
- if length == 1:
111
- answer.append("S-END")
112
- else:
113
- answer.append("B-END")
114
- for i in range(length-2):
115
- answer.append("M-END")
116
- answer.append("E-END")
117
-
118
- #elif l.startswith("Нулевое окончание") is True:
119
- #answer.append("S-NULL_END")
120
-
121
- elif l.startswith("Постфикс") is True:
122
- if m.startswith("-") is True:
123
- answer.append("HYPH")
124
- length -= 1
125
- answer.append("B-POSTFIX")
126
- for i in range(length-2):
127
- answer.append("M-POSTFIX")
128
- answer.append("E-POSTFIX")
129
-
130
- return answer
131
-
132
-
133
- def extract_morpheme_type(x):
134
- return x[2:].lower()
135
-
136
-
137
- def read_input(infile, transform_to_BMES=True, n=None, shuffle=True):
138
- source, targets = [], []
139
- with open(infile, "r", encoding="utf8") as fin:
140
- for line in fin:
141
- line = line.strip()
142
- if line == "":
143
- break
144
- word, morphs, analysis = line.split(" | ")
145
- target = partition_to_BMES(morphs, analysis) if transform_to_BMES else morphs
146
- source.append(word)
147
- targets.append(target)
148
- if n is not None:
149
- indexes = list(range(len(source)))
150
- if shuffle:
151
- np.random.shuffle(indexes)
152
- indexes = indexes[:n]
153
- source = [source[i] for i in indexes]
154
- targets = [targets[i] for i in indexes]
155
- return source, targets
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
rnc_morphemer/NeuralMorphemeSegmentation/tabled_trie.py DELETED
@@ -1,694 +0,0 @@
1
- '''
2
- Classes for trie manipulations
3
- '''
4
- import copy
5
- import time
6
- from collections import defaultdict
7
-
8
- import numpy as np
9
-
10
-
11
- class Trie:
12
- '''
13
- Реализация префиксного бора (точнее, корневого направленного ациклического графа)
14
-
15
- Атрибуты
16
- --------
17
- alphabet: list, алфавит
18
- alphabet_codes: dict, словарь символ:код
19
- compressed: bool, индикатор сжатия
20
- cashed: bool, индикатор кэширования запросов к функции descend
21
- root: int, индекс корня
22
- graph: array, type=int, shape=(число вершин, размер алфавита), матрица потомков
23
- graph[i][j] = k <-> вершина k --- потомок вершины i по ребру, помеченному символом alphabet[j]
24
- data: array, type=object, shape=(число вершин), массив с данными, хранящямися в вершинах
25
- final: array, type=bool, shape=(число вершин), массив индикаторов
26
- final[i] = True <-> i --- финальная вершина
27
- '''
28
- NO_NODE = -1
29
- SPACE_CODE = -1
30
-
31
- ATTRS = ['is_numpied', 'precompute_symbols', 'allow_spaces',
32
- 'is_terminated', 'to_make_cashed']
33
-
34
- def __init__(self, alphabet, make_sorted=True, make_alphabet_codes=True,
35
- is_numpied=False, to_make_cashed=False,
36
- precompute_symbols=None, allow_spaces=False, dict_storage=False):
37
- self.alphabet = sorted(alphabet) if make_sorted else alphabet
38
- self.alphabet_codes = ({a: i for i, a in enumerate(self.alphabet)}
39
- if make_alphabet_codes else self.alphabet)
40
- self.alphabet_codes[" "] = Trie.SPACE_CODE
41
- self.is_numpied = is_numpied
42
- self.to_make_cashed = to_make_cashed
43
- self.dict_storage = dict_storage
44
- self.precompute_symbols = precompute_symbols
45
- self.allow_spaces = allow_spaces
46
- self.initialize()
47
-
48
- def initialize(self):
49
- self.root = 0
50
- self.graph = [self._make_default_node()]
51
- self.data, self.final = [None], [False]
52
- self.nodes_number = 1
53
- self.descend = self._descend_simple
54
- self.is_terminated = False
55
-
56
- def _make_default_node(self):
57
- if self.dict_storage:
58
- return defaultdict(lambda: -1)
59
- elif self.is_numpied:
60
- return np.full(shape=(len(self.alphabet),),
61
- fill_value=Trie.NO_NODE, dtype=int)
62
- else:
63
- return [Trie.NO_NODE] * len(self.alphabet)
64
-
65
- def save(self, outfile):
66
- """
67
- Сохраняет дерево для дальнейшего использования
68
- """
69
- with open(outfile, "w", encoding="utf8") as fout:
70
- attr_values = [getattr(self, attr) for attr in Trie.ATTRS]
71
- attr_values.append(any(x is not None for x in self.data))
72
- fout.write("{}\n{}\t{}\n".format(
73
- " ".join("T" if x else "F" for x in attr_values),
74
- self.nodes_number, self.root))
75
- fout.write(" ".join(str(a) for a in self.alphabet) + "\n")
76
- for index, label in enumerate(self.final):
77
- letters = self._get_letters(index, return_indexes=True)
78
- children = self._get_children(index)
79
- fout.write("{}\t{}\n".format(
80
- "T" if label else "F", " ".join("{}:{}".format(*elem)
81
- for elem in zip(letters, children))))
82
- if self.precompute_symbols is not None:
83
- for elem in self.data:
84
- fout.write(":".join(",".join(
85
- map(str, symbols)) for symbols in elem) + "\n")
86
- return
87
-
88
- def make_cashed(self):
89
- '''
90
- Включает кэширование запросов к descend
91
- '''
92
- self._descendance_cash = [dict() for _ in self.graph]
93
- self.descend = self._descend_cashed
94
-
95
- def make_numpied(self):
96
- self.graph = np.array(self.graph)
97
- self.final = np.asarray(self.final, dtype=bool)
98
- self.is_numpied = True
99
-
100
- def add(self, s):
101
- '''
102
- Добавление строки s в префиксный бор
103
- '''
104
- if self.is_terminated:
105
- raise TypeError("Impossible to add string to fitted trie")
106
- if s == "":
107
- self._set_final(self.root)
108
- return
109
- curr = self.root
110
- for i, a in enumerate(s):
111
- code = self.alphabet_codes[a]
112
- next = self.graph[curr][code]
113
- if next == Trie.NO_NODE:
114
- curr = self._add_descendant(curr, s[i:])
115
- break
116
- else:
117
- curr = next
118
- self._set_final(curr)
119
- return self
120
-
121
- def fit(self, words):
122
- for s in words:
123
- self.add(s)
124
- self.terminate()
125
-
126
- def terminate(self):
127
- if self.is_numpied:
128
- self.make_numpied()
129
- self.terminated = True
130
- if self.precompute_symbols is not None:
131
- precompute_future_symbols(self, self.precompute_symbols,
132
- allow_spaces=self.allow_spaces)
133
- if self.to_make_cashed:
134
- self.make_cashed()
135
-
136
- def __contains__(self, s):
137
- if any(a not in self.alphabet for a in s):
138
- return False
139
- # word = tuple(self.alphabet_codes[a] for a in s)
140
- node = self.descend(self.root, s)
141
- return (node != Trie.NO_NODE) and self.is_final(node)
142
-
143
- def words(self):
144
- """
145
- Возвращает итератор по словам, содержащимся в боре
146
- """
147
- branch, word, indexes = [self.root], [], [0]
148
- letters_with_children = [self._get_children_and_letters(self.root)]
149
- while len(branch) > 0:
150
- if self.is_final(branch[-1]):
151
- yield "".join(word)
152
- while indexes[-1] == len(letters_with_children[-1]):
153
- indexes.pop()
154
- letters_with_children.pop()
155
- branch.pop()
156
- if len(indexes) == 0:
157
- raise StopIteration()
158
- word.pop()
159
- next_letter, next_child = letters_with_children[-1][indexes[-1]]
160
- indexes[-1] += 1
161
- indexes.append(0)
162
- word.append(next_letter)
163
- branch.append(next_child)
164
- letters_with_children.append(self._get_children_and_letters(branch[-1]))
165
-
166
- def is_final(self, index):
167
- '''
168
- Аргументы
169
- ---------
170
- index: int, номер вершины
171
-
172
- Возвращает
173
- ----------
174
- True: если index --- номер финальной вершины
175
- '''
176
- return self.final[index]
177
-
178
- def find_substrings(self, s, return_positions=False, return_compressed=True):
179
- """
180
- Finds all nonempty substrings of s in the trie
181
- """
182
- curr_agenda = {self.root: {0}}
183
- answer = [[] for _ in s]
184
- for i, a in enumerate(s, 1):
185
- next_agenda = defaultdict(set)
186
- for curr, starts in curr_agenda.items():
187
- if a in self.alphabet:
188
- child = self.graph[curr][self.alphabet_codes[a]]
189
- if child == Trie.NO_NODE:
190
- continue
191
- next_agenda[child] |= starts
192
- next_agenda[self.root].add(i)
193
- for curr, starts in next_agenda.items():
194
- if self.is_final(curr):
195
- answer[i-1].extend(starts)
196
- curr_agenda = next_agenda
197
- answer = [(x, i) for i, x in enumerate(answer, 1)]
198
- if not return_positions or not return_compressed:
199
- answer = [(i, j) for starts, j in answer for i in starts]
200
- if not return_positions:
201
- answer = [s[i:j] for i, j in answer]
202
- return answer
203
- def find_partitions(self, s, max_count=1):
204
- """
205
- Находит все разбиения s = s_1 ... s_m на словарные слова s_1, ..., s_m
206
- для m <= max_count
207
- """
208
- curr_agenda = [(self.root, [], 0)]
209
- for i, a in enumerate(s):
210
- next_agenda = []
211
- for curr, borders, cost in curr_agenda:
212
- if cost >= max_count:
213
- continue
214
- child = self.graph[curr][self.alphabet_codes[a]]
215
- # child = self.graph[curr][a]
216
- if child == Trie.NO_NODE:
217
- continue
218
- next_agenda.append((child, borders, cost))
219
- if self.is_final(child):
220
- next_agenda.append((self.root, borders + [i+1], cost+1))
221
- curr_agenda = next_agenda
222
- answer = []
223
- for curr, borders, cost in curr_agenda:
224
- if curr == self.root:
225
- borders = [0] + borders
226
- answer.append([s[left:borders[i+1]] for i, left in enumerate(borders[:-1])])
227
- return answer
228
-
229
- def _get_accepting_prefixes_lengths(self, s, start=None):
230
- if start is None:
231
- start = self.root
232
- answer = []
233
- for i, symbol in enumerate(s, 1):
234
- code = self.alphabet_codes.get(symbol)
235
- if code is None:
236
- break
237
- start = self.graph[start][code]
238
- if start == self.NO_NODE:
239
- break
240
- if self.is_final(start):
241
- answer.append(i)
242
- return answer
243
-
244
- def descend_by_prefixes(self, s, max_count=1, start_pos=0, start_node=None, return_pairs=False):
245
- if start_node is None:
246
- start_node = self.root
247
- if isinstance(start_pos, int):
248
- start_pos = [start_pos]
249
- start_pos = sorted(start_pos)
250
- start = start_pos[0]
251
- if max_count == 1 and len(start_pos) == 1:
252
- answer = self._get_accepting_prefixes_lengths(s[start:], start=start_node)
253
- if return_pairs:
254
- answer = [(start, start+k) for k in answer]
255
- else:
256
- answer = [start+k for k in answer]
257
- return answer
258
- answer = set()
259
- curr_agenda = {start_node: {start: 1}}
260
- for i, symbol in enumerate(s[start:], start):
261
- code = self.alphabet_codes.get(symbol)
262
- if code is None:
263
- break
264
- if i in start_pos[1:]:
265
- curr_agenda[start_node][i] = 1
266
- new_agenda = defaultdict(dict)
267
- for curr, starts_with_ranks in curr_agenda.items():
268
- curr = self.graph[curr][code]
269
- if curr == self.NO_NODE:
270
- continue
271
- is_final = self.is_final(curr)
272
- for start, rank in starts_with_ranks.items():
273
- if start not in new_agenda[curr] or rank < new_agenda[curr][start]:
274
- new_agenda[curr][start] = rank
275
- if is_final:
276
- answer.add((start, i+1))
277
- if rank < max_count:
278
- if i+1 not in new_agenda[self.root] or rank + 1 < new_agenda[self.root][i+1]:
279
- new_agenda[self.root][i + 1] = rank + 1
280
- curr_agenda = new_agenda
281
- if not return_pairs:
282
- answer = {elem[1] for elem in answer}
283
- return sorted(answer)
284
-
285
- def __len__(self):
286
- return self.nodes_number
287
-
288
- def __repr__(self):
289
- answer = ""
290
- for i, (final, data) in enumerate(zip(self.final, self.data)):
291
- letters, children = self._get_letters(i), self._get_children(i)
292
- answer += "{0}".format(i)
293
- if final:
294
- answer += "F"
295
- for a, index in zip(letters, children):
296
- answer += " {0}:{1}".format(a, index)
297
- answer += "\n"
298
- if data is not None:
299
- answer += "data:{0} {1}\n".format(len(data), " ".join(str(elem) for elem in data))
300
- return answer
301
-
302
- def _add_descendant(self, parent, s, final=False):
303
- for a in s:
304
- code = self.alphabet_codes[a]
305
- parent = self._add_empty_child(parent, code, final)
306
- return parent
307
-
308
- def _add_empty_child(self, parent, code, final=False):
309
- '''
310
- Добавление ребёнка к вершине parent по символу с кодом code
311
- '''
312
- self.graph[parent][code] = self.nodes_number
313
- self.graph.append(self._make_default_node())
314
- self.data.append(None)
315
- self.final.append(final)
316
- self.nodes_number += 1
317
- return (self.nodes_number - 1)
318
-
319
- def _descend_simple(self, curr, s):
320
- '''
321
- Спуск из вершины curr по строке s
322
- '''
323
- for a in s:
324
- curr = self.graph[curr][self.alphabet_codes[a]]
325
- if curr == Trie.NO_NODE:
326
- break
327
- return curr
328
-
329
- def _descend_cashed(self, curr, s):
330
- '''
331
- Спуск из вершины curr по строке s с кэшированием
332
- '''
333
- if s == "":
334
- return curr
335
- curr_cash = self._descendance_cash[curr]
336
- answer = curr_cash.get(s, None)
337
- if answer is not None:
338
- return answer
339
- # для оптимизации дублируем код
340
- res = curr
341
- for a in s:
342
- res = self.graph[res][self.alphabet_codes[a]]
343
- # res = self.graph[res][a]
344
- if res == Trie.NO_NODE:
345
- break
346
- curr_cash[s] = res
347
- return res
348
-
349
- def _set_final(self, curr):
350
- '''
351
- Делает состояние curr завершающим
352
- '''
353
- self.final[curr] = True
354
-
355
- def _get_letters(self, index, return_indexes=False):
356
- """
357
- Извлекает все метки выходных рёбер вершины с номером index
358
- """
359
- if self.dict_storage:
360
- answer = list(self.graph[index].keys())
361
- else:
362
- answer = [i for i, elem in enumerate(self.graph[index])
363
- if elem != Trie.NO_NODE]
364
- if not return_indexes:
365
- answer = [(self.alphabet[i] if i >= 0 else " ") for i in answer]
366
- return answer
367
-
368
- def _get_children_and_letters(self, index, return_indexes=False):
369
- if self.dict_storage:
370
- answer = list(self.graph[index].items())
371
- else:
372
- answer = [elem for elem in enumerate(self.graph[index])
373
- if elem[1] != Trie.NO_NODE]
374
- if not return_indexes:
375
- for i, (letter_index, child) in enumerate(answer):
376
- answer[i] = (self.alphabet[letter_index], child)
377
- return answer
378
-
379
- def _get_children(self, index):
380
- """
381
- Извлекает всех потомков вершины с номером index
382
- """
383
- if self.dict_storage:
384
- return list(self.graph[index].values())
385
- else:
386
- return [elem for elem in self.graph[index] if elem != Trie.NO_NODE]
387
-
388
-
389
- class TrieMinimizer:
390
- '''
391
- Класс для сжатия префиксного бора
392
- '''
393
- def __init__(self):
394
- pass
395
-
396
- def minimize(self, trie, dict_storage=False, make_cashed=False, make_numpied=False,
397
- precompute_symbols=None, allow_spaces=False, return_groups=False):
398
- N = len(trie)
399
- if N == 0:
400
- raise ValueError("Trie should be non-empty")
401
- node_classes = np.full(shape=(N,), fill_value=-1, dtype=int)
402
- order = self.generate_postorder(trie)
403
- # processing the first node
404
- index = order[0]
405
- node_classes[index] = 0
406
- class_representatives = [index]
407
- node_key = ((), (), trie.is_final(index))
408
- classes, class_keys = {node_key : 0}, [node_key]
409
- curr_index = 1
410
- for index in order[1:]:
411
- letter_indexes = tuple(trie._get_letters(index, return_indexes=True))
412
- children = trie._get_children(index)
413
- children_classes = tuple(node_classes[i] for i in children)
414
- key = (letter_indexes, children_classes, trie.is_final(index))
415
- key_class = classes.get(key, None)
416
- if key_class is not None:
417
- node_classes[index] = key_class
418
- else:
419
- # появился новый класс
420
- class_keys.append(key)
421
- classes[key] = node_classes[index] = curr_index
422
- class_representatives.append(curr_index)
423
- curr_index += 1
424
- # построение нового дерева
425
- compressed = Trie(trie.alphabet, is_numpied=make_numpied,
426
- dict_storage=dict_storage, allow_spaces=allow_spaces,
427
- precompute_symbols=precompute_symbols)
428
- L = len(classes)
429
- new_final = [elem[2] for elem in class_keys[::-1]]
430
- if dict_storage:
431
- new_graph = [defaultdict(int) for _ in range(L)]
432
- elif make_numpied:
433
- new_graph = np.full(shape=(L, len(trie.alphabet)),
434
- fill_value=Trie.NO_NODE, dtype=int)
435
- new_final = np.array(new_final, dtype=bool)
436
- else:
437
- new_graph = [[Trie.NO_NODE for a in trie.alphabet] for i in range(L)]
438
- for (indexes, children, final), class_index in\
439
- sorted(classes.items(), key=(lambda x: x[1])):
440
- row = new_graph[L-class_index-1]
441
- for i, child_index in zip(indexes, children):
442
- row[i] = L - child_index - 1
443
- compressed.graph = new_graph
444
- compressed.root = L - node_classes[trie.root] - 1
445
- compressed.final = new_final
446
- compressed.nodes_number = L
447
- compressed.data = [None] * L
448
- if make_cashed:
449
- compressed.make_cashed()
450
- if precompute_symbols is not None:
451
- if (trie.is_terminated and trie.precompute_symbols
452
- and trie.allow_spaces == allow_spaces):
453
- # копируем будущие символы из исходного дерева
454
- # нужно, чтобы возврат из финальных состояний в начальное был одинаковым в обоих деревьях
455
- for i, node_index in enumerate(class_representatives[::-1]):
456
- # будущие символы для представителя i-го класса
457
- compressed.data[i] = copy.copy(trie.data[node_index])
458
- else:
459
- precompute_future_symbols(compressed, precompute_symbols, allow_spaces)
460
- if return_groups:
461
- node_classes = [L - i - 1 for i in node_classes]
462
- return compressed, node_classes
463
- else:
464
- return compressed
465
-
466
- def generate_postorder(self, trie):
467
- '''
468
- Обратная топологическая сортировка
469
- '''
470
- order, stack = [], []
471
- stack.append(trie.root)
472
- colors = ['white'] * len(trie)
473
- while len(stack) > 0:
474
- index = stack[-1]
475
- color = colors[index]
476
- if color == 'white': # вершина ещё не обрабатывалась
477
- colors[index] = 'grey'
478
- for child in trie._get_children(index):
479
- # проверяем, посещали ли мы ребёнка раньше
480
- if child != Trie.NO_NODE and colors[child] == 'white':
481
- stack.append(child)
482
- else:
483
- if color == 'grey':
484
- colors[index] = 'black'
485
- order.append(index)
486
- stack = stack[:-1]
487
- return order
488
-
489
- def load_trie(infile):
490
- with open(infile, "r", encoding="utf8") as fin:
491
- line = fin.readline().strip()
492
- flags = [x=='T' for x in line.split()]
493
- if len(flags) != len(Trie.ATTRS) + 1:
494
- raise ValueError("Wrong file format")
495
- nodes_number, root = map(int, fin.readline().strip().split())
496
- alphabet = fin.readline().strip().split()
497
- trie = Trie(alphabet)
498
- for i, attr in enumerate(Trie.ATTRS):
499
- setattr(trie, attr, flags[i])
500
- read_data = flags[-1]
501
- final = [False] * nodes_number
502
- print(len(alphabet), nodes_number)
503
- if trie.dict_storage:
504
- graph = [defaultdict(lambda: -1) for _ in range(nodes_number)]
505
- elif trie.is_numpied:
506
- final = np.array(final)
507
- graph = np.full(shape=(nodes_number, len(alphabet)),
508
- fill_value=Trie.NO_NODE, dtype=int)
509
- else:
510
- graph = [[Trie.NO_NODE for a in alphabet] for i in range(nodes_number)]
511
- for i in range(nodes_number):
512
- line = fin.readline().strip()
513
- if "\t" in line:
514
- label, transitions = line.split("\t")
515
- final[i] = (label == "T")
516
- else:
517
- label = line
518
- final[i] = (label == "T")
519
- continue
520
- transitions = [x.split(":") for x in transitions.split()]
521
- for code, value in transitions:
522
- graph[i][int(code)] = int(value)
523
- trie.graph = graph
524
- trie.root = root
525
- trie.final = final
526
- trie.nodes_number = nodes_number
527
- trie.data = [None] * nodes_number
528
- if read_data:
529
- for i in range(nodes_number):
530
- line = fin.readline().strip("\n")
531
- trie.data[i] = [set(elem.split(",")) for elem in line.split(":")]
532
- if trie.to_make_cashed:
533
- trie.make_cashed()
534
- return trie
535
-
536
-
537
- def make_trie(words, alphabet=None, compressed=True, is_numpied=False,
538
- make_cashed=False, precompute_symbols=False,
539
- allow_spaces=False, dict_storage=False):
540
- if alphabet is None:
541
- alphabet = sorted({x for word in words for x in word})
542
- trie = Trie(alphabet, is_numpied=is_numpied, to_make_cashed=make_cashed,
543
- precompute_symbols=precompute_symbols, dict_storage=dict_storage)
544
- trie.fit(words)
545
- print(len(trie))
546
- if compressed:
547
- tm = TrieMinimizer()
548
- trie = tm.minimize(trie, dict_storage=dict_storage, make_cashed=make_cashed,
549
- make_numpied=is_numpied, precompute_symbols=precompute_symbols,
550
- allow_spaces=allow_spaces)
551
- print(len(trie))
552
- return trie
553
-
554
- def precompute_future_symbols(trie, n, allow_spaces=False):
555
- '''
556
- Collecting possible continuations of length <= n for every node
557
- '''
558
- if n == 0:
559
- return
560
- if trie.is_terminated and trie.precompute_symbols:
561
- # символы уже предпосчитаны
562
- return
563
- for index, final in enumerate(trie.final):
564
- trie.data[index] = [set() for i in range(n)]
565
- for index, (node_data, final) in enumerate(zip(trie.data, trie.final)):
566
- node_data[0] = set(trie._get_letters(index))
567
- if allow_spaces and final:
568
- node_data[0].add(" ")
569
- for d in range(1, n):
570
- for index, (node_data, final) in enumerate(zip(trie.data, trie.final)):
571
- children = set(trie._get_children(index))
572
- for child in children:
573
- node_data[d] |= trie.data[child][d - 1]
574
- # в случае, если разрешён возврат по пробелу в стартовое состояние
575
- if allow_spaces and final:
576
- node_data[d] |= trie.data[trie.root][d - 1]
577
- trie.terminated = True
578
-
579
- def test_basic():
580
- alphabet = "abc"
581
- trie = Trie(alphabet, allow_spaces=True, dict_storage=True)
582
- words = ["aba", "acba", "b", "bab", "a", "cb"]
583
- trie.fit(words)
584
- print(trie)
585
- tm = TrieMinimizer()
586
- compressed = tm.minimize(trie, make_numpied=False, precompute_symbols=2,
587
- make_cashed=True, allow_spaces=True)
588
- print(compressed)
589
- compressed.save("trie.in")
590
- compressed = load_trie("trie.in")
591
- print(compressed.find_partitions('acbacb', 3))
592
- for word in compressed.words():
593
- print(word)
594
- # print(compressed.find_partitions('aba', 1))
595
- # print(compressed.find_partitions('abab', 1))
596
- # print(compressed.find_partitions('abab', 2))
597
-
598
-
599
- def test_performance():
600
- alphabet = 'абвгдеёжзийклмнопрстуфхцчшщьыъэюя-'
601
- infile = "test_data/words_100000.txt"
602
- words = []
603
- with open(infile, "r", encoding="utf8") as fin:
604
- for line in fin:
605
- line = line.strip().lower()
606
- if len(line) != 0:
607
- words.append(line)
608
- tm = TrieMinimizer()
609
- # дерево на списках
610
- trie = Trie(alphabet, is_numpied=False, precompute_symbols=2)
611
- t1 = time.time()
612
- trie.fit(words[:90000])
613
- # trie.make_numpied()
614
- t2 = time.time()
615
- for word in words[10000:]:
616
- flag = (word in trie)
617
- t3 = time.time()
618
- trie.save("trie.out")
619
- t4 = time.time()
620
- trie = load_trie("trie.out")
621
-
622
-
623
-
624
-
625
- t5 = time.time()
626
- print("{:.3f} {:.3f} {:.3f} {:.3f}".format(t5 - t4, t4-t3, t3-t2, t2-t1))
627
- compressed = tm.minimize(trie, make_numpied=False, make_cashed=True, precompute_symbols=2)
628
- t6 = time.time()
629
- for word in words[10000:]:
630
- flag = (word in compressed)
631
- t7 = time.time()
632
- compressed.save("trie_compressed.out")
633
- t8 = time.time()
634
- compressed = load_trie("trie_compressed.out")
635
- t9 = time.time()
636
- print("{:.3f} {:.3f} {:.3f}".format(t9-t8, t8-t7, t7-t6))
637
-
638
- def test_encoding():
639
- alphabet = 'абвгдеёжзийклмнопрстуфхцчшщьыъэюя-'
640
- infile = "test_data/words_1000000.txt"
641
- words = []
642
- with open(infile, "r", encoding="utf8") as fin:
643
- for line in fin:
644
- line = line.strip().lower()
645
- if len(line) != 0:
646
- words.append(line)
647
- tm = TrieMinimizer()
648
- # дерево на списках
649
- trie = Trie(alphabet, is_numpied=False)
650
- t1 = time.time()
651
- for word in words[:90000]:
652
- trie.add(word)
653
- trie.make_cashed()
654
- # trie.make_numpied()
655
- t2 = time.time()
656
- for word in words[10000:]:
657
- flag = (word in trie)
658
- # минимизация
659
- print("{:.3f} {:.3f}".format(time.time()-t2, t2-t1))
660
- # перекодировка
661
- encoded_alphabet = list(range(list(alphabet)))
662
- recoding = {a: code for code, a in enumerate(alphabet)}
663
- recoded_words = [[]]
664
-
665
- def test_precomputing_symbols():
666
- alphabet = 'абвгдеёжзийклмнопрстуфхцчшщьыъэюя-'
667
- infile = "test_data/words_100000.txt"
668
- words = []
669
- with open(infile, "r", encoding="utf8") as fin:
670
- for line in fin:
671
- line = line.strip().lower()
672
- if len(line) != 0:
673
- words.append(line)
674
- tm = TrieMinimizer()
675
- trie = Trie(alphabet, is_numpied=False, precompute_symbols=2)
676
- trie.fit(words[:10])
677
- compressed, node_classes =\
678
- tm.minimize(trie, precompute_symbols=2, return_groups=True)
679
- possible_continuations = [set() for _ in compressed.graph]
680
- for future_symbols, index in zip(trie.data, node_classes):
681
- possible_continuations[index].add("|".join(
682
- ",".join(map(str, sorted(elem))) for elem in future_symbols))
683
- compressed_continuations =\
684
- ["|".join(",".join(map(str, sorted(elem))) for elem in future_symbols)
685
- for future_symbols in compressed.data]
686
- print(sum(int(len(x) > 1) for x in possible_continuations))
687
- print(sum((list(x)[0] != y) for x, y in
688
- zip(possible_continuations, compressed_continuations)))
689
-
690
-
691
- if __name__ == "__main__":
692
- test_basic()
693
- # test_performance()
694
- # test_precomputing_symbols()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
rnc_morphemer/models/morphodict_10_07_2023-1.hdf5 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:f3112f52a2a4b62bfa8e66ac17c92f0f1c167a5754e9a5f66efa11b8e65a4409
3
- size 1768960
 
 
 
 
rnc_morphemer/models/morphodict_10_07_2023-2.hdf5 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:3955f62506514e2465bed8ee1f340aa55de6c61b0801b4020ee4b198250f2fa8
3
- size 1768920
 
 
 
 
rnc_morphemer/models/morphodict_10_07_2023-3.hdf5 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:e71af8506f737bd282714c9a02a8a6bf2e72b3ed5369ea0f24e25c7ae0725752
3
- size 1768920
 
 
 
 
rnc_morphemer/models/morphodict_10_07_2023.json DELETED
The diff for this file is too large to render. See raw diff
 
suffixes.txt ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ аг
2
+ адьj
3
+ ак
4
+ алей
5
+ алеj
6
+ альон
7
+ ам
8
+ амт
9
+ арад
10
+ арий
11
+ ариус
12
+ ац
13
+ ачей
14
+ ачеj
15
+ ащ
16
+ вор
17
+ дцать
18
+ ек
19
+ енец
20
+ енк
21
+ ердяj
22
+ ёрт
23
+ ес
24
+ ёс
25
+ ех
26
+ ёхоньк
27
+ ёшеньк
28
+ жды
29
+ зн
30
+ знь
31
+ иад
32
+ изирова
33
+ изиру
34
+ изова
35
+ изу
36
+ инг
37
+ иньj
38
+ ион
39
+ иот
40
+ ир
41
+ ирова
42
+ иру
43
+ исмент
44
+ иссимус
45
+ итет
46
+ ифицирова
47
+ ича
48
+ й
49
+ лан
50
+ менн
51
+ надцать
52
+ нич
53
+ ован
54
+ овик
55
+ овит
56
+ овл
57
+ озо
58
+ ол
59
+ оньк
60
+ орий
61
+ ориум
62
+ сн
63
+ теп
64
+ тор
65
+ ул
66
+ учи
67
+ ушек
68
+ ушк
69
+ фик
70
+ фиц
71
+ ци
72
+ ческ
73
+ чиц
74
+ ше
75
+ ши
76
+ ья
77
+ юшек
78
+ ющ
79
+ я
80
+ явк
81
+ ян
82
+ янн
83
+ яр
84
+ яшк
85
+ ин
86
+ а
87
+ абельн
88
+ ав
89
+ аж
90
+ аз
91
+ айш
92
+ ал
93
+ альн
94
+ ан
95
+ ант
96
+ ану
97
+ ар
98
+ арн
99
+ арь
100
+ аст
101
+ яст
102
+ ат
103
+ атор
104
+ ациj
105
+ ач
106
+ ачий
107
+ ашн
108
+ б
109
+ бищ
110
+ в
111
+ ва
112
+ вш
113
+ вши
114
+ гейт
115
+ диил
116
+ е
117
+ ей
118
+ еб
119
+ ëб
120
+ ебн
121
+ ев
122
+ ёв
123
+ ева
124
+ евий
125
+ евин
126
+ евич
127
+ евн
128
+ ее
129
+ ёж
130
+ ёз
131
+ ейш
132
+ ёл
133
+ ем
134
+ ен
135
+ ён
136
+ ениj
137
+ енн
138
+ ённ
139
+ ёнок
140
+ ент
141
+ енциj
142
+ ень
143
+ еньк
144
+ енько
145
+ ер
146
+ ёр
147
+ еск
148
+ есс
149
+ еств
150
+ ец
151
+ еч
152
+ ечк
153
+ и
154
+ ив
155
+ ива
156
+ ивн
157
+ ид
158
+ иден
159
+ изм
160
+ ий
161
+ ик
162
+ ил
163
+ илк
164
+ им
165
+ иничн
166
+ инишн
167
+ инк
168
+ ючи
169
+ ист
170
+ ит
171
+ ительн
172
+ их
173
+ иц
174
+ ич
175
+ ическ
176
+ ичий
177
+ ичк
178
+ ичн
179
+ ишк
180
+ ишн
181
+ ищ
182
+ иj
183
+ к
184
+ ка
185
+ л
186
+ лив
187
+ н
188
+ ниj
189
+ ник
190
+ ниц
191
+ нича
192
+ нн
193
+ ну
194
+ няк
195
+ о
196
+ об
197
+ ов
198
+ ова
199
+ оват
200
+ овий
201
+ ович
202
+ овн
203
+ оз
204
+ озн
205
+ оид
206
+ ок
207
+ ом
208
+ он
209
+ онк
210
+ онн
211
+ онок
212
+ онько
213
+ ор
214
+ орн
215
+ ость
216
+ от
217
+ оч
218
+ очк
219
+ очн
220
+ очниц
221
+ ош
222
+ ск
223
+ ств
224
+ сть
225
+ тель
226
+ тельн
227
+ тиj
228
+ тьj
229
+ у
230
+ уг
231
+ ум
232
+ ун
233
+ ур
234
+ ух
235
+ уч
236
+ ущ
237
+ х
238
+ циj
239
+ ч
240
+ чат
241
+ чив
242
+ чик
243
+ чонок
244
+ ш
245
+ щик
246
+ щин
247
+ щиц
248
+ ыва
249
+ ыг
250
+ ын
251
+ ыч
252
+ ыш
253
+ ышек
254
+ ышк
255
+ ю
256
+ юг
257
+ юшк
258
+ яв
259
+ яг
260
+ яж
261
+ як
262
+ янт
263
+ ярн
264
+ ят
265
+ ятин
266
+ ятор
267
+ яциj
268
+ ячий
269
+ ящ
270
+ j
271
+
272
+ же
273
+ либо
274
+ нибудь
275
+ с
276
+ сь
277
+ ся
278
+ то