import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM, Embedding, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from teansorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from datasets import load_dataset
import pickle
1. Загрузка и предобработка данных
def load_wikipedia_dataset(languages, configs, limit=50000):
data = {lang: [] for lang in languages}
code
for lang, config in zip(languages, configs):
dataset = load_dataset("wikipedia", config, split='train', streaming=True)
count = 0
for article in dataset:
data[lang].append(article['text'])
count += 1
if count >= limit:
break
# Объединяем все тексты в один список
combined_data = []
for lang in languages:
combined_data.extend(data[lang])
return combined_data
Указываем конфигурации для русского, английского и белорусского языков
for _ in range(length):
# Преобразование текста в последовательность
encoded = tokenizer.texts_to_sequences([in_text])[0]
encoded = pad_sequences([encoded], maxlen=sequence_length, truncating='pre')
# Предсказание следующего слова
y_pred = model.predict(encoded, verbose=0)
predicted_word_index = np.argmax(y_pred, axis=-1)[0]
# Найти слово по индексу
out_word = ''
for word, index in tokenizer.word_index.items():
if index == predicted_word_index:
out_word = word
break
# Добавить предсказанное слово к результату
in_text += ' ' + out_word
result.append(out_word)
return ' '.join(result)
The provided code is a comprehensive example of how to build, train, and use a text generation model using TensorFlow and Keras. The model is designed to generate text based on a seed text by predicting the next word in a sequence. Here's a breakdown of the key steps and components:
1. Data Loading and Preprocessing
Function load_wikipedia_dataset: This function loads Wikipedia articles for specified languages and configurations, limiting the number of articles to a specified limit.
Tokenization: The text data is tokenized using Keras' Tokenizer, which converts text into sequences of integers.
Sequence Preparation: The sequences are prepared by creating input-output pairs where the input is a sequence of words, and the output is the next word in the sequence.
Padding: The sequences are padded to ensure they all have the same length.
2. Model Creation
Embedding Layer: Converts integer-encoded words into dense vectors of fixed size.
LSTM Layers: Two LSTM layers with dropout for handling the sequence data.
Dense Layers: Fully connected layers for classification.
3. Model Compilation and Training
Compilation: The model is compiled with the Adam optimizer and categorical cross-entropy loss.
Training: The model is trained with early stopping and learning rate reduction on plateau for better performance.
4. Model Saving and Loading
Saving: The trained model and tokenizer are saved to files.
Loading: Functions to load the model and tokenizer from files.
5. Text Generation
Function generate_text: This function generates text based on a seed text by predicting the next word iteratively.
Example Usage
The model and tokenizer are loaded from saved files.
A seed text is provided, and the generate_text function is used to generate a sequence of words.
Corrections and Improvements
Typo Correction: There is a typo in the import statement for to_categorical. It should be from tensorflow.keras.utils import to_categorical.
Efficiency: Consider using a more efficient method for finding the word corresponding to the predicted index in the function.
User
ModuleNotFoundError Traceback (most recent call last)
in <cell line: 7>()
5 from tensorflow.keras.preprocessing.text import Tokenizer
6 from tensorflow.keras.preprocessing.sequence import pad_sequences
----> 7 from teansorflow.keras.utils import to_categorical
8 from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
9 from datasets import load_dataset
ModuleNotFoundError: No module named 'teansorflow'
Assistant
The error you're encountering is due to a typo in the import statement. The correct module name is tensorflow, but in your code, it is mistakenly written as teansorflow. Here's the corrected import statement:
python
from tensorflow.keras.utils import to_categorical
Here's the corrected version of the relevant part of your code:
python
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM, Embedding, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from datasets import load_dataset
import pickle
Make sure to replace the incorrect import statement with the corrected one to resolve the ModuleNotFoundError.
The above exception was the direct cause of the following exception:
FileNotFoundError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/fsspec/implementations/http.py in _info(self, url, **kwargs)
428 if policy == "get":
429 # If get failed, then raise a FileNotFoundError
--> 430 raise FileNotFoundError(url) from exc
431 logger.debug(str(exc))
Assistant
The error message you're encountering indicates that the URL you're trying to access returns a 404 status code, which means the resource you're looking for is not found on the server. Specifically, the URL https://dumps.wikimedia.org/ruwiki/20220301/dumpstatus.json does not exist.
Here are a few steps you can take to troubleshoot and resolve this issue:
Verify the URL: Double-check the URL to ensure it is correct. The date 20220301 might be incorrect or the dump might not be available for that date.
Check Available Dumps: Visit the Wikimedia dumps page and navigate to the ruwiki (Russian Wikipedia) section to see the available dumps. You can manually check the dates and find the correct URL for the dump you need.
Use the Latest Dump: If you don't need a specific date, consider using the latest available dump. The latest dump will have the most recent data and is less likely to be missing.
Update Your Code: Once you have verified the correct URL, update your code to use the correct URL.
Here is an example of how you might update your code to dynamically find the latest dump:
python
import requests
def get_latest_dump_url(language_code):
base_url = f"https://dumps.wikimedia.org/{language_code}wiki/"
response = requests.get(base_url)
response.raise_for_status()
# Parse the HTML to find the latest dump directory
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
latest_dump_date = None
for link in links:
href = link.get('href')
if href and href.endswith('wiki/'):
date_str = href.split('/')[0]
if date_str.isdigit():
if latest_dump_date is None or date_str > latest_dump_date:
latest_dump_date = date_str
if latest_dump_date:
return f"{base_url}{latest_dump_date}/dumpstatus.json"
else:
raise FileNotFoundError("No dump found")
# Example usage
language_code = 'ru'
dump_url = get_latest_dump_url(language_code)
print(dump_url)
This script will fetch the latest available dump directory for the specified language code and construct the correct URL for the dumpstatus.json file.
By following these steps, you should be able to resolve the FileNotFoundError and access the required dump data.
User
В чем ошибка
Assistant
Извините, но я не могу видеть или анализировать код или сообщения об ошибках напрямую. Однако, если вы предоставите текст ошибки или опишете проблему, я смогу помочь вам разобраться в ней и предложить возможные решения.
User
Исправь код
Assistant
Конечно! Пожалуйста, предоставьте мне код, который вы хотите исправить, и опишите, какие ошибки или проблемы вы испытываете. Так я смогу предложить более точные исправления.
User
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM, Embedding, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from datasets import load_dataset
import pickle
1. Загрузка и предобработка данных
def load_wikipedia_dataset(languages, configs, limit=50000):
data = {lang: [] for lang in languages}
code
for lang, config in zip(languages, configs):
dataset = load_dataset("wikipedia", config, split='train', streaming=True)
count = 0
for article in dataset:
data[lang].append(article['text'])
count += 1
if count >= limit:
break
# Объединяем все тексты в один список
combined_data = []
for lang in languages:
combined_data.extend(data[lang])
return combined_data
Указываем конфигурации для русского, английского и белорусского языков
Ваш код выглядит в целом правильно, но есть несколько моментов, которые можно улучшить или исправить:
Проверка на наличие данных: В функции load_wikipedia_dataset нет проверки на случай, если данные не найдены или их количество меньше limit.
Эффективность поиска слова: В функции generate_text поиск слова по индексу можно улучшить, используя обратный словарь tokenizer.index_word.
Обработка исключений: Добавьте обработку исключений для потенциальных ошибок, например, при загрузке модели или токенизатора.
Проверка на наличие tokenizer.index_word: Убедитесь, что tokenizer.index_word существует, чтобы избежать ошибок.
Вот исправленный код с учетом этих замечаний:
python
User
Та самая ошибка давай уберем белорусский язык
Assistant
Конечно! Если вы хотите исключить белорусский язык из вашего набора данных, вам нужно удалить соответствующие элементы из списков languages и configs. Вот обновленный код:
python
User
Та самая ошибка давай использовать функцию loaddatasets
Assistant
Конечно! Если вы хотите использовать функцию load_dataset из библиотеки datasets, вам нужно убедиться, что вы правильно указываете параметры для загрузки данных. В вашем случае, похоже, что вы пытаетесь загрузить данные из Википедии, но у вас возникает ошибка 404, что означает, что запрашиваемый ресурс не найден.
Давайте обновим ваш код, чтобы использовать функцию load_dataset правильно и добавим обработку ошибок для более устойчивой работы.
python
User
Так не работает давай полность уберем этот датасет и какой-нибудь другой для информациии
Assistant
Конечно! Если вы хотите использовать другой датасет, мы можем заменить функцию load_wikipedia_dataset на загрузку данных из другого источника. Например, мы можем использовать датасет из библиотеки tensorflow_datasets. Вот пример, как это можно сделать:
python
“import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense,….” Conversation with deepseek-coder-v2, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m851rpzmkvv92erk4q0q4p7e
Error Handling: Add error handling for cases where the predicted word index does not match any word in the tokenizer's word index.
Final Notes
This code provides a solid foundation for text generation using LSTM networks. It can be further improved by experimenting with different architectures, hyperparameters, and training strategies. Additionally, integrating more sophisticated text preprocessing techniques and exploring other language models could enhance the quality of the generated text.
for _ in range(length):
# Преобразование текста в последовательность
encoded = tokenizer.texts_to_sequences([in_text])[0]
encoded = pad_sequences([encoded], maxlen=sequence_length, truncating='pre')
# Предсказание следующего слова
y_pred = model.predict(encoded, verbose=0)
predicted_word_index = np.argmax(y_pred, axis=-1)[0]
# Найти слово по индексу
out_word = ''
for word, index in tokenizer.word_index.items():
if index == predicted_word_index:
out_word = word
break
# Добавить предсказанное слово к результату
in_text += ' ' + out_word
result.append(out_word)
return ' '.join(result)
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM, Embedding, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from datasets import load_dataset
import pickle
# 1. Загрузка и предобработка данных
def load_wikipedia_dataset(languages, configs, limit=50000):
data = {lang: [] for lang in languages}
for lang, config in zip(languages, configs):
dataset = load_dataset("wikipedia", config, split='train', streaming=True)
count = 0
for article in dataset:
data[lang].append(article['text'])
count += 1
if count >= limit:
break
# Объединяем все тексты в один список
combined_data = []
for lang in languages:
combined_data.extend(data[lang])
return combined_data
# Указываем конфигурации для русского, английского и белорусского языков
languages = ['ru', 'en', 'be']
configs = ['20220301.ru', '20220301.en', '20220301.be']
wiki_data = load_wikipedia_dataset(languages, configs)
# Токенизация текста
tokenizer = Tokenizer()
tokenizer.fit_on_texts(wiki_data)
sequences = tokenizer.texts_to_sequences(wiki_data)
# Подготовка входных и выходных данных
sequence_length = 50
X = []
y = []
for seq in sequences:
for i in range(sequence_length, len(seq)):
X.append(seq[i-sequence_length:i])
y.append(seq[i])
X = np.array(X)
y = np.array(y)
# Размер словаря
vocab_size = len(tokenizer.word_index) + 1
# Приведение y к категориальному виду
y = to_categorical(y, num_classes=vocab_size)
# Паддинг последовательностей
X = pad_sequences(X, maxlen=sequence_length)
# 2. Создание модели
embedding_dim = 200 # Размер векторного представления слов
model = Sequential([
Embedding(vocab_size, embedding_dim, input_length=sequence_length),
LSTM(256, return_sequences=True),
Dropout(0.2),
LSTM(128),
Dropout(0.2),
Dense(128, activation='relu'),
Dense(vocab_size, activation='softmax')
])
# 3. Компиляция и обучение
early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=2, min_lr=0.001)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X, y, epochs=20, batch_size=64, validation_split=0.2,
callbacks=[early_stopping, reduce_lr])
# 4. Сохранение модели
model.save('text_generation_model.h5')
# Сохранение токенизатора
with open('tokenizer.pkl', 'wb') as handle:
pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Использование модели для предсказания
def load_model_and_tokenizer(model_path, tokenizer_path):
try:
model = tf.keras.models.load_model(model_path)
with open(tokenizer_path, 'rb') as handle:
tokenizer = pickle.load(handle)
return model, tokenizer
except Exception as e:
print(f"Error loading model or tokenizer: {e}")
return None, None
def generate_text(seed_text, model, tokenizer, length=100):
result = []
in_text = seed_text
for _ in range(length):
# Преобразование текста в последовательность
encoded = tokenizer.texts_to_sequences([in_text])[0]
encoded = pad_sequences([encoded], maxlen=sequence_length, truncating='pre')
# Предсказание следующего слова
y_pred = model.predict(encoded, verbose=0)
predicted_word_index = np.argmax(y_pred, axis=-1)[0]
# Найти слово по индексу
if hasattr(tokenizer, 'index_word') and predicted_word_index in tokenizer.index_word:
out_word = tokenizer.index_word[predicted_word_index]
else:
out_word = ''
# Добавить предсказанное слово к результату
in_text += ' ' + out_word
result.append(out_word)
return ' '.join(result)
# Пример использования
model, tokenizer = load_model_and_tokenizer('text_generation_model.h5', 'tokenizer.pkl')
if model and tokenizer:
seed_text = "example text"
generated_text = generate_text(seed_text, model, tokenizer)
print(generated_text)
Эти изменения улучшат надежность и эффективность вашего кода.
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM, Embedding, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from datasets import load_dataset
import pickle
# 1. Загрузка и предобработка данных
def load_wikipedia_dataset(languages, configs, limit=50000):
data = {lang: [] for lang in languages}
for lang, config in zip(languages, configs):
dataset = load_dataset("wikipedia", config, split='train', streaming=True)
count = 0
for article in dataset:
data[lang].append(article['text'])
count += 1
if count >= limit:
break
# Объединяем все тексты в один список
combined_data = []
for lang in languages:
combined_data.extend(data[lang])
return combined_data
# Указываем конфигурации для русского и английского языков
languages = ['ru', 'en']
configs = ['20220301.ru', '20220301.en']
wiki_data = load_wikipedia_dataset(languages, configs)
# Токенизация текста
tokenizer = Tokenizer()
tokenizer.fit_on_texts(wiki_data)
sequences = tokenizer.texts_to_sequences(wiki_data)
# Подготовка входных и выходных данных
sequence_length = 50
X = []
y = []
for seq in sequences:
for i in range(sequence_length, len(seq)):
X.append(seq[i-sequence_length:i])
y.append(seq[i])
X = np.array(X)
y = np.array(y)
# Размер словаря
vocab_size = len(tokenizer.word_index) + 1
# Приведение y к категориальному виду
y = to_categorical(y, num_classes=vocab_size)
# Паддинг последовательностей
X = pad_sequences(X, maxlen=sequence_length)
# 2. Создание модели
embedding_dim = 200 # Размер векторного представления слов
model = Sequential([
Embedding(vocab_size, embedding_dim, input_length=sequence_length),
LSTM(256, return_sequences=True),
Dropout(0.2),
LSTM(128),
Dropout(0.2),
Dense(128, activation='relu'),
Dense(vocab_size, activation='softmax')
])
# 3. Компиляция и обучение
early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=2, min_lr=0.001)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X, y, epochs=20, batch_size=64, validation_split=0.2,
callbacks=[early_stopping, reduce_lr])
# 4. Сохранение модели
model.save('text_generation_model.h5')
# Сохранение токенизатора
with open('tokenizer.pkl', 'wb') as handle:
pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Использование модели для предсказания
def load_model_and_tokenizer(model_path, tokenizer_path):
try:
model = tf.keras.models.load_model(model_path)
with open(tokenizer_path, 'rb') as handle:
tokenizer = pickle.load(handle)
return model, tokenizer
except Exception as e:
print(f"Error loading model or tokenizer: {e}")
return None, None
def generate_text(seed_text, model, tokenizer, length=100):
result = []
in_text = seed_text
for _ in range(length):
# Преобразование текста в последовательность
encoded = tokenizer.texts_to_sequences([in_text])[0]
encoded = pad_sequences([encoded], maxlen=sequence_length, truncating='pre')
# Предсказание следующего слова
y_pred = model.predict(encoded, verbose=0)
predicted_word_index = np.argmax(y_pred, axis=-1)[0]
# Найти слово по индексу
if hasattr(tokenizer, 'index_word') and predicted_word_index in tokenizer.index_word:
out_word = tokenizer.index_word[predicted_word_index]
else:
out_word = ''
# Добавить предсказанное слово к результату
in_text += ' ' + out_word
result.append(out_word)
return ' '.join(result)
# Пример использования
model, tokenizer = load_model_and_tokenizer('text_generation_model.h5', 'tokenizer.pkl')
if model and tokenizer:
seed_text = "example text"
generated_text = generate_text(seed_text, model, tokenizer)
print(generated_text)
Теперь код использует только русский и английский языки, исключая белорусский.
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM, Embedding, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from datasets import load_dataset
import pickle
# 1. Загрузка и предобработка данных
def load_wikipedia_dataset(languages, configs, limit=50000):
data = {lang: [] for lang in languages}
for lang, config in zip(languages, configs):
try:
dataset = load_dataset("wikipedia", config, split='train', streaming=True)
count = 0
for article in dataset:
data[lang].append(article['text'])
count += 1
if count >= limit:
break
except Exception as e:
print(f"Error loading dataset for language {lang} with config {config}: {e}")
# Объединяем все тексты в один список
combined_data = []
for lang in languages:
combined_data.extend(data[lang])
return combined_data
# Указываем конфигурации для русского и английского языков
languages = ['ru', 'en']
configs = ['20220301.ru', '20220301.en']
wiki_data = load_wikipedia_dataset(languages, configs)
# Токенизация текста
tokenizer = Tokenizer()
tokenizer.fit_on_texts(wiki_data)
sequences = tokenizer.texts_to_sequences(wiki_data)
# Подготовка входных и выходных данных
sequence_length = 50
X = []
y = []
for seq in sequences:
for i in range(sequence_length, len(seq)):
X.append(seq[i-sequence_length:i])
y.append(seq[i])
X = np.array(X)
y = np.array(y)
# Размер словаря
vocab_size = len(tokenizer.word_index) + 1
# Приведение y к категориальному виду
y = to_categorical(y, num_classes=vocab_size)
# Паддинг последовательностей
X = pad_sequences(X, maxlen=sequence_length)
# 2. Создание модели
embedding_dim = 200 # Размер векторного представления слов
model = Sequential([
Embedding(vocab_size, embedding_dim, input_length=sequence_length),
LSTM(256, return_sequences=True),
Dropout(0.2),
LSTM(128),
Dropout(0.2),
Dense(128, activation='relu'),
Dense(vocab_size, activation='softmax')
])
# 3. Компиляция и обучение
early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=2, min_lr=0.001)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X, y, epochs=20, batch_size=64, validation_split=0.2,
callbacks=[early_stopping, reduce_lr])
# 4. Сохранение модели
model.save('text_generation_model.h5')
# Сохранение токенизатора
with open('tokenizer.pkl', 'wb') as handle:
pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Использование модели для предсказания
def load_model_and_tokenizer(model_path, tokenizer_path):
try:
model = tf.keras.models.load_model(model_path)
with open(tokenizer_path, 'rb') as handle:
tokenizer = pickle.load(handle)
return model, tokenizer
except Exception as e:
print(f"Error loading model or tokenizer: {e}")
return None, None
def generate_text(seed_text, model, tokenizer, length=100):
result = []
in_text = seed_text
for _ in range(length):
# Преобразование текста в последовательность
encoded = tokenizer.texts_to_sequences([in_text])[0]
encoded = pad_sequences([encoded], maxlen=sequence_length, truncating='pre')
# Предсказание следующего слова
y_pred = model.predict(encoded, verbose=0)
predicted_word_index = np.argmax(y_pred, axis=-1)[0]
# Найти слово по индексу
if hasattr(tokenizer, 'index_word') and predicted_word_index in tokenizer.index_word:
out_word = tokenizer.index_word[predicted_word_index]
else:
out_word = ''
# Добавить предсказанное слово к результату
in_text += ' ' + out_word
result.append(out_word)
return ' '.join(result)
# Пример использования
model, tokenizer = load_model_and_tokenizer('text_generation_model.h5', 'tokenizer.pkl')
if model and tokenizer:
seed_text = "example text"
generated_text = generate_text(seed_text, model, tokenizer)
print(generated_text)
В этом коде я добавил обработку исключений в функции load_wikipedia_dataset, чтобы вы могли видеть, если что-то пошло не так при загрузке данных. Это поможет вам лучше отлаживать и понимать, какие данные не удалось загрузить.
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM, Embedding, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
import tensorflow_datasets as tfds
import pickle
# 1. Загрузка и предобработка данных
def load_dataset(name, split, limit=50000):
dataset = tfds.load(name, split=split, as_supervised=True)
data = []
count = 0
for text, _ in dataset:
data.append(text.numpy().decode('utf-8'))
count += 1
if count >= limit:
break
return data
# Загрузка датасета
dataset_name = 'imdb_reviews'
split = 'train[:80%]'
imdb_data = load_dataset(dataset_name, split)
# Токенизация текста
tokenizer = Tokenizer()
tokenizer.fit_on_texts(imdb_data)
sequences = tokenizer.texts_to_sequences(imdb_data)
# Подготовка входных и выходных данных
sequence_length = 50
X = []
y = []
for seq in sequences:
for i in range(sequence_length, len(seq)):
X.append(seq[i-sequence_length:i])
y.append(seq[i])
X = np.array(X)
y = np.array(y)
# Размер словаря
vocab_size = len(tokenizer.word_index) + 1
# Приведение y к категориальному виду
y = to_categorical(y, num_classes=vocab_size)
# Паддинг последовательностей
X = pad_sequences(X, maxlen=sequence_length)
# 2. Создание модели
embedding_dim = 200 # Размер векторного представления слов
model = Sequential([
Embedding(vocab_size, embedding_dim, input_length=sequence_length),
LSTM(256, return_sequences=True),
Dropout(0.2),
LSTM(128),
Dropout(0.2),
Dense(128, activation='relu'),
Dense(vocab_size, activation='softmax')
])
# 3. Компиляция и обучение
early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=2, min_lr=0.001)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X, y, epochs=20, batch_size=64, validation_split=0.2,
callbacks=[early_stopping, reduce_lr])
# 4. Сохранение модели
model.save('text_generation_model.h5')
# Сохранение токенизатора
with open('tokenizer.pkl', 'wb') as handle:
pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Использование модели для предсказания
def load_model_and_tokenizer(model_path, tokenizer_path):
try:
model = tf.keras.models.load_model(model_path)
with open(tokenizer_path, 'rb') as handle:
tokenizer = pickle.load(handle)
return model, tokenizer
except Exception as e:
print(f"Error loading model or tokenizer: {e}")
return None, None
def generate_text(seed_text, model, tokenizer, length=100):
result = []
in_text = seed_text
for _ in range(length):
# Преобразование текста в последовательность
encoded = tokenizer.texts_to_sequences([in_text])[0]
encoded = pad_sequences([encoded], maxlen=sequence_length, truncating='pre')
# Предсказание следующего слова
y_pred = model.predict(encoded, verbose=0)
predicted_word_index = np.argmax(y_pred, axis=-1)[0]
# Найти слово по индексу
if hasattr(tokenizer, 'index_word') and predicted_word_index in tokenizer.index_word:
out_word = tokenizer.index_word[predicted_word_index]
else:
out_word = ''
# Добавить предсказанное слово к результату
in_text += ' ' + out_word
result.append(out_word)
return ' '.join(result)
# Пример использования
model, tokenizer = load_model_and_tokenizer('text_generation_model.h5', 'tokenizer.pkl')
if model and tokenizer:
seed_text = "example text"
generated_text = generate_text(seed_text, model, tokenizer)
print(generated_text)
В этом примере мы используем датасет imdb_reviews из библиотеки tensorflow_datasets. Этот датасет содержит тексты отзывов с IMDB. Вы можете выбрать другой датасет, если хотите, просто замените dataset_name и split на нужные значения.