2023-12-14 22:33:48 +04:00
|
|
|
|
import numpy as np
|
|
|
|
|
from keras.preprocessing.sequence import pad_sequences
|
|
|
|
|
from keras.preprocessing.text import Tokenizer
|
2023-12-07 22:35:52 +04:00
|
|
|
|
from keras.models import Sequential
|
|
|
|
|
from keras.layers import Embedding, LSTM, Dense
|
2023-12-14 22:33:48 +04:00
|
|
|
|
from keras.utils import to_categorical
|
2023-12-07 22:35:52 +04:00
|
|
|
|
|
2023-12-14 22:33:48 +04:00
|
|
|
|
with open('ru.txt', "r", encoding='utf-8') as file:
|
2023-12-07 22:35:52 +04:00
|
|
|
|
text = file.read()
|
|
|
|
|
|
|
|
|
|
# Предварительная обработка текста (в зависимости от вашей задачи)
|
|
|
|
|
|
|
|
|
|
# Создание словаря для отображения слов в индексы и обратно
|
2023-12-14 22:33:48 +04:00
|
|
|
|
tokenizer = Tokenizer()
|
2023-12-07 22:35:52 +04:00
|
|
|
|
tokenizer.fit_on_texts([text])
|
|
|
|
|
total_words = len(tokenizer.word_index) + 1
|
|
|
|
|
|
|
|
|
|
# Подготовка данных для обучения (в зависимости от вашей задачи)
|
|
|
|
|
|
|
|
|
|
input_sequences = []
|
|
|
|
|
for line in text.split('\n'):
|
|
|
|
|
token_list = tokenizer.texts_to_sequences([line])[0]
|
|
|
|
|
for i in range(1, len(token_list)):
|
|
|
|
|
n_gram_sequence = token_list[:i+1]
|
|
|
|
|
input_sequences.append(n_gram_sequence)
|
|
|
|
|
|
|
|
|
|
max_sequence_length = max([len(x) for x in input_sequences])
|
2023-12-14 22:33:48 +04:00
|
|
|
|
input_sequences = pad_sequences(input_sequences, maxlen=max_sequence_length, padding='pre')
|
2023-12-07 22:35:52 +04:00
|
|
|
|
X, y = input_sequences[:,:-1],input_sequences[:,-1]
|
2023-12-14 22:33:48 +04:00
|
|
|
|
y = to_categorical(y, num_classes=total_words)
|
2023-12-07 22:35:52 +04:00
|
|
|
|
|
|
|
|
|
# Определение архитектуры модели
|
|
|
|
|
|
|
|
|
|
model = Sequential()
|
|
|
|
|
model.add(Embedding(total_words, 50, input_length=max_sequence_length-1))
|
|
|
|
|
model.add(LSTM(100))
|
|
|
|
|
model.add(Dense(total_words, activation='softmax'))
|
|
|
|
|
|
|
|
|
|
# Компиляция модели
|
|
|
|
|
|
|
|
|
|
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
|
|
|
|
|
|
|
|
|
|
# Обучение модели
|
|
|
|
|
|
|
|
|
|
model.fit(X, y, epochs=100, verbose=2)
|
|
|
|
|
|
|
|
|
|
# Генерация текста с использованием обученной модели
|
|
|
|
|
|
2023-12-14 22:33:48 +04:00
|
|
|
|
def generate_text(seed_text, next_words, model_, max_sequence_length):
|
2023-12-07 22:35:52 +04:00
|
|
|
|
for _ in range(next_words):
|
|
|
|
|
token_list = tokenizer.texts_to_sequences([seed_text])[0]
|
2023-12-14 22:33:48 +04:00
|
|
|
|
token_list = pad_sequences([token_list], maxlen=max_sequence_length - 1, padding='pre')
|
|
|
|
|
predicted_probs = model.predict(token_list, verbose=0)[0]
|
|
|
|
|
predicted_index = np.argmax(predicted_probs)
|
2023-12-07 22:35:52 +04:00
|
|
|
|
output_word = ""
|
|
|
|
|
for word, index in tokenizer.word_index.items():
|
2023-12-14 22:33:48 +04:00
|
|
|
|
if index == predicted_index:
|
2023-12-07 22:35:52 +04:00
|
|
|
|
output_word = word
|
|
|
|
|
break
|
|
|
|
|
seed_text += " " + output_word
|
|
|
|
|
|
|
|
|
|
return seed_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# Пример генерации текста (замените seed_text и next_words на свои значения)
|
2023-12-14 22:33:48 +04:00
|
|
|
|
seed_text = "здесь был"
|
2023-12-07 22:35:52 +04:00
|
|
|
|
next_words = 50
|
|
|
|
|
generated_text = generate_text(seed_text, next_words, model, max_sequence_length)
|
|
|
|
|
|
|
|
|
|
print(generated_text)
|