This commit is contained in:
Алексей Козлов 2024-01-12 12:01:18 +04:00
parent 1cd312ba98
commit c35f0c25dd
6 changed files with 157 additions and 0 deletions

View File

@ -0,0 +1,66 @@
# Лабораторная работа №7. Рекуррентная нейронная сетьи задача генерации текста
## 14 вариант
___
### Задание:
Выбрать художественный текст (четные варианты русскоязычный, нечетные англоязычный)и обучить на нем рекуррентную нейронную сеть для решения задачи генерации. Подобрать архитектуру и параметры так, чтобы приблизиться к максимально осмысленному результату.
___
### Запуск
- Запустить файл lab7.py (Для английского языка необходимо в коде выбрать соответсвующий файл и начальную строку)
### Используемые технологии
- Язык программирования **Python**
- Среда разработки **PyCharm**
- Библиотеки:
* keras
* tensorflow
* numpy
### Описание программы
Код программы выполняет следующие действия:
1. Импортирует необходимые библиотеки: numpy, Tokenizer и pad_sequences из keras.preprocessing.text, Sequential, LSTM, Dense, Dropout из keras.models.
2. Читает текст из файла "english.txt" и сохраняет его содержимое в переменную "text".
3. Задает параметр "seq_length" как длину входной последовательности.
4. Создает экземпляр класса Tokenizer, который разбивает текст на токены (в данном случае, символы) и обучает его на тексте.
5. Преобразует текст в последовательности чисел с использованием метода texts_to_sequences.
6. Создает входные и выходные последовательности для обучения модели с помощью цикла. Входная последовательность - это последние "seq_length" символов перед текущим символом, а выходная последовательность - это текущий символ.
7. Преобразует входные и выходные данные в формат массивов numpy с использованием функции pad_sequences.
8. Создает модель RNN (рекуррентная нейронная сеть) с помощью класса Sequential из keras.models. Модель состоит из двух слоев LSTM, которые последовательно соединены. Первый LSTM-слои принимает входную последовательность, а второй - выход первого слоя.
9. Компилирует модель, задавая функцию потерь, оптимизатор и метрику для оценки модели.
10. Обучает модель на входных и выходных данных с помощью метода fit.
11. Определяет функцию generate_text для генерации текста. Функция принимает начальный текст seed_text и длину генерируемого текста gen_length.
12. В цикле генерирует текст, используя обученную модель. Начиная с seed_text, функция преобразует его в последовательность чисел, затем преобразует в формат массива numpy и делает предсказание с помощью модели. Следующий символ выбирается с помощью функции argmax для получения индекса символа с наибольшей вероятностью. Затем символ добавляется к сгенерированному тексту и seed_text обновляется, чтобы учесть новый символ.
13. Возвращает сгенерированный текст.
14. Генерирует текст, используя seed_text и функцию generate_text, и выводит результат.
___
### Пример работы
![Graphics](russian.png)
```text
Результат работы модели на основании файла с текстом на русском языке
```
![Graphics](english.png)
```text
Результат работы модели на основании файла с текстом на английском языке
```
### Вывод
На основе выходных данных можно сделать следующий вывод о довольно успешной работе модели, тексты содержат осмысленное содержание и практически не содержат пунктуационных и грамматических ошибок.

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -0,0 +1,14 @@
Canada is a rapidly developing country with incredibly beautiful nature. It is the second largest state in the world (after Russia): its huge territory extends from Arctic glaciers to coniferous and mixed forests on the border with the USA. Canada has rich plant world (oak, maple, fir, pine, etc.) and animal world (wolf, lynx, deer, and various species of fish). It is famous for the colossal Great Lakes and national parks.
The history of Canada is tied with two cultures: English and French. Canada was born in the late 16 th and early 17 th centuries when French colonists settled on the land of the Indian tribes. Later, the British arrived and founded their cities, which led to wars between them, the French, and indigenous people. The French part, with the center in Quebec, and the English part of Canada united in 1840. For a long time, Canada remained the British colony but became sovereign in the 20 th century.
Nowadays, Canada is a member of the Commonwealth of Nations. Although its head is British monarch, the Governor-General and the Parliament sitting in the capital (Ottawa) are independent in their decisions. The country consists of 10 provinces and 3 territories; each subject has its own proportion of Francophone and Anglophone population, but Canada is officially bilingual. Many immigrants from France, Ireland, German, Italy, etc. preserve their native cultures and create the situation of multiculturalism supported by the state.
Due to improved mining industry, agriculture, and trade, Canada has a very high living standard. Toronto, Montreal, Vancouver attract tourists, as well as amazing landscapes and numerous ethnic festivals.
Canada is situated on the north of Northern America, washed by the Atlantic Ocean in the east, the Pacific Ocean in the west, and the Arctic Ocean in the north and in the northeast by the Baffin Bay and the Davis Strait, which separate it from Greenland, In the south and in the north Canada borders on the USA. It is a land of vast distances and rich natural resources. Canada became a self-governing dominion in 1867 while retaining ties to the British crown. Canadas territory is the worlds second largest country, surpassed in size only by Russia. It includes many islands, notably the Canadian Arctic Islands, also called Arctic Archipelago in the Arctic Ocean. Economically and technologically the nation has developed in parallel with the US, its neighbour to the south. The total area is about 10 million sq km. Canada is slightly larger than the US. It is an important manufacturer, and its major cities, such as Toronto, Montreal, Vancouver, Ottawa, Edmonton, Calgary and Winnipeg are centres of commerce and industry.
The climate of Canada varies from temperate in the south to subarctic and arctic in the north. The highest Canadian point is Mount Logan 5,959 m. The population of Canada is about 32 million people. There are two state languages: English and French. English is spoken by 60 % of population; French is spoken by 23 % of people.
Most of Canadas inhabitants live in the southern part of the country and vast areas of the north are sparsely inhabited. The country is divided into ten provinces (Alberta, British Columbia, Manitoba, New Brunswick, Newfoundland, Nova Scotia, Ontario, Prince Edward Island, Quebec, Saskatchewan) and three territories (Northwest Territories, Yukon Territory, Nunavut Territory). The third territory called Nunavut, to be carved from the present Northwest Territories, was created in 1999.
The name Canada is derived from an Iroquoian term meaning «village».
Among the great rivers of Canada there are the Saint Lawrence River, draining the Great Lakes and emptying into the Gulf of Saint Lawrence; the Ottawa and the Saguenay rivers, the principal affluents of the Saint Lawrence River; the Saint John River, emptying into the Bay of Fundy.
The government type is confederation with parliamentary democracy. The capital of Canada is Ottawa.
Canada became independent from the United Kingdom on July, 1, 1867. Legal system is based on the English common law, except in Quebec, where civil law system based on the French law prevails.
The racial and ethnic makeup of the Canadian people is diversified. About 35 percent of the population is composed of people of the British origin. People of the French origin total about 25 percent of the population. The vast majority of French-speaking Canadians reside in Quebec, where they make up about three-fourths of the population; large numbers also live in Ontario and New Brunswick.
French-speaking Canadians maintain their language, culture, and traditions, and the federal government follows the policy of a bilingual and bicultural nation. During the 1970s and 1980s the proportion of Asians among the Canadian population increased, and today those who count their ancestry as wholly Asian make up 8 to 10 percent of the population. More than two-thirds of the Asian immigrants live in Ontario or British Columbia. The remainder of the population is composed of people of various ethnic groups, such as German, Italian, Ukrainian, Netherlands Dutch, Scandinavian, Polish, Hungarian, Greek, and Native American. Blacks have never constituted\a major segment of the Canadian population. Indigenous people make up nearly 2 percent of Canadas inhabitants.
The largest religious community in Canada is Roman Catholic. Nearly half of Canadians who are Roman Catholic live in Quebec. Of the Protestant denominations in Canada the largest is the United Church of Canada, followed by the Anglican Church of Canada. Other important Protestant groups are the Baptist, Presbyterian and Lutheran. Nearly 2 percent of the population are Orthodox. Muslim and Jewish adherents each number about 1 percent. A substantial number of Buddhists, Hindus and Sikhs have been brought to the country in recent years by immigration. Nearly 13 percent of Canadians claim no religion.

View File

@ -0,0 +1,70 @@
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
# Чтение текста из файла
#with open('russian.txt', 'r', encoding='utf-8') as file:
# text = file.read()
with open('english.txt', 'r', encoding='utf-8') as file:
text = file.read()
# Параметры модели
seq_length = 10
# Создание экземпляра Tokenizer и обучение на тексте
tokenizer = Tokenizer(char_level=True)
tokenizer.fit_on_texts([text])
# Преобразование текста в последовательности чисел
sequences = tokenizer.texts_to_sequences([text])[0]
# Создание входных и выходных последовательностей
X_data = []
y_data = []
for i in range(seq_length, len(sequences)):
sequence = sequences[i - seq_length:i]
target = sequences[i]
X_data.append(sequence)
y_data.append(target)
# Преобразование входных и выходных данных в формат массивов numpy
X = pad_sequences(X_data, maxlen=seq_length)
y = np.array(y_data)
# Создание модели RNN
vocab_size = len(tokenizer.word_index) + 1
model = Sequential()
model.add(LSTM(256, input_shape=(seq_length, 1), return_sequences=True))
model.add(LSTM(128, input_shape=(seq_length, 1)))
model.add(Dense(vocab_size, activation='softmax'))
# Компиляция модели
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Обучение модели
model.fit(X, y, epochs=100, verbose=1)
# Функция для генерации текста
def generate_text(seed_text, gen_length):
generated_text = seed_text
for _ in range(gen_length):
sequence = tokenizer.texts_to_sequences([seed_text])[0]
sequence = pad_sequences([sequence], maxlen=seq_length)
prediction = model.predict(sequence)[0]
predicted_index = np.argmax(prediction)
predicted_char = tokenizer.index_word[predicted_index]
generated_text += predicted_char
seed_text += predicted_char
seed_text = seed_text[1:]
return generated_text
# Генерация текста
#seed_text = "Это было бы чудом"
seed_text = "The climate of"
generated_text = generate_text(seed_text, 250)
print(generated_text)

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -0,0 +1,7 @@
Мир таков, каков он есть. Трудно предположить, чтобы мир был создан единственно для удовлетворения наших потребностей. Это было бы чудом из чудес. Мир нейтрален. Он не дружествен и не враждебен человеку. Вам внушили, что человек рождается для того, чтобы умереть, и что вы должны всю жизнь терзаться этой мыслью. Чего ради? Смерть - не факт сознания. “Смысл раздумий о смерти в том, что они лишены смысла”, - писал Монтерлан. Смерть близких потрясает нас. А наша собственная? Бояться ее - значит представлять себе и мир, где мы есть, и мир, где нас нет. Эти два образа несовместимы.
Вам внушили, что мы живем на краю пропасти, но даже если мы идем по краю пропасти, ничто не толкает нас вниз.
Вам внушили, что старые моральные ценности канули в прошлое. Это ложь Я напомню вам для начала несколько древних как мир истин
Нельзя жить для себя. Думая только о себе, человек всегда найдет тысячу причин чувствовать себя несчастным. Никогда он не делал всего того, что хотел и должен был делать, никогда не получал всего того, чего, по его мнению, заслуживал, редко был любим так, как мечтал быть любимым. Без конца пережёвывая свое прошлое, он будет испытывать одни сожаления Зачеркнуть прошлое все равно невозможно, попытайтесь лучше создать настоящее, которым вы сможете гордиться. Всякий, кто живет ради других - ради своей страны, ради женщины, ради творчества, ради голодающих или гонимых, - словно по волшебству забывает свою тоску
Второе правило - надо действовать. Вместо того, чтобы жаловаться на абсурдность мира, постараемся преобразить тот уголок, куда забросила нас судьба. Мы не в силах изменить вселенную, да и не стремимся к этому. Наши цели ближе и проще: заниматься своим делом - правильно выбрать его, глубоко изучить и достичь в нем мастерства Если человек в совершенстве овладел каким-нибудь ремеслом, работа приносит ему счастье.
Третье правило - надо верить в силу воли Безусловно, никто из нас не всемогущ. Не в моей власти помешать войне, но мои призывы, помноженные на призывы миллионов других людей, ослабят угрозу войны. Я не в силах выиграть битву, но я в силах быть храбрым солдатом, исполнить свой долг. “Возможности наши зависят от того, на что мы дерзнём,” поэтому надо быть всегда в форме. Усилием воли человек заставляет себя трудиться на совесть и совершать геройские поступки. Быть может, воля и есть царица добродетелей.
Важно и четвертое правило - надо хранить верность. Верность слову, обязательствам, другим, самому себе.