форкнуто от main/is_dnn
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
25 KiB
25 KiB
import os
os.chdir('/content/drive/MyDrive/Colab Notebooks')# импорт модулей
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
import sklearn# загрузка датасета
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()# создание своего разбиения датасета
from sklearn.model_selection import train_test_split
# объединяем в один набор
X = np.concatenate((X_train, X_test))
y = np.concatenate((y_train, y_test))
# разбиваем по вариантам
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size = 10000,
train_size = 60000,
random_state = 15)# вывод размерностей
print('Shape of X train:', X_train.shape)
print('Shape of y train:', y_train.shape)# Вывод 4 изображений
plt.figure(figsize=(10, 3))
for i in range(4):
plt.subplot(1, 4, i + 1)
plt.imshow(X_train[i], cmap='gray')
plt.title(f'Label: {y_train[i]}')
plt.axis('off')
plt.tight_layout()
plt.show()# развернем каждое изображение 28*28 в вектор 784
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels) / 255
X_test = X_test.reshape(X_test.shape[0], num_pixels) / 255
print('Shape of transformed X train:', X_train.shape)# переведем метки в one-hot
from keras.utils import to_categorical
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
print('Shape of transformed y train:', y_train.shape)
num_classes = y_train.shape[1]from keras.models import Sequential
from keras.layers import Dense# 1. создаем модель - объявляем ее объектом класса Sequential
model = Sequential()
# 2. добавляем выходной слой(скрытые слои отсутствуют)
model.add(Dense(units=num_classes, activation='softmax'))
# 3. компилируем модель
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])# вывод информации об архитектуре модели
print(model.summary())# обучение модели
H = model.fit(X_train, y_train, validation_split=0.1, epochs=50)# вывод графика ошибки по эпохам
plt.plot(H.history['loss'])
plt.plot(H.history['val_loss'])
plt.grid()
plt.xlabel('Epochs')
plt.ylabel('loss')
plt.legend(['train_loss', 'val_loss'])
plt.title('Loss by epochs')
plt.show()# Оценка качества работы модели на тестовых данных
scores = model.evaluate(X_test, y_test)
print('Loss on test data:', scores[0])
print('Accuracy on test data:', scores[1])# сохранение модели на диск
model.save('/content/drive/MyDrive/Colab Notebooks/models/model_zero_hide.keras')model100 = Sequential()
model100.add(Dense(units=100,input_dim=num_pixels, activation='sigmoid'))
model100.add(Dense(units=num_classes, activation='softmax'))
model100.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])# вывод информации об архитектуре модели
print(model100.summary())# Обучаем модель
H = model100.fit(X_train, y_train, validation_split=0.1, epochs=50)# вывод графика ошибки по эпохам
plt.plot(H.history['loss'])
plt.plot(H.history['val_loss'])
plt.grid()
plt.xlabel('Epochs')
plt.ylabel('loss')
plt.legend(['train_loss', 'val_loss'])
plt.title('Loss by epochs')
plt.show()# Оценка качества работы модели на тестовых данных
scores = model100.evaluate(X_test, y_test)
print('Loss on test data:', scores[0])
print('Accuracy on test data:', scores[1])# сохранение модели на диск
model100.save('/content/drive/MyDrive/Colab Notebooks/models/model100in_1hide.keras')model300 = Sequential()
model300.add(Dense(units=300,input_dim=num_pixels, activation='sigmoid'))
model300.add(Dense(units=num_classes, activation='softmax'))
model300.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])# вывод информации об архитектуре модели
print(model300.summary())# Обучаем модель
H = model300.fit(X_train, y_train, validation_split=0.1, epochs=50)# вывод графика ошибки по эпохам
plt.plot(H.history['loss'])
plt.plot(H.history['val_loss'])
plt.grid()
plt.xlabel('Epochs')
plt.ylabel('loss')
plt.legend(['train_loss', 'val_loss'])
plt.title('Loss by epochs')
plt.show()# Оценка качества работы модели на тестовых данных
scores = model300.evaluate(X_test, y_test)
print('Loss on test data:', scores[0])
print('Accuracy on test data:', scores[1])# сохранение модели на диск
model300.save('/content/drive/MyDrive/Colab Notebooks/models/model300in_1hide.keras')model500 = Sequential()
model500.add(Dense(units=500,input_dim=num_pixels, activation='sigmoid'))
model500.add(Dense(units=num_classes, activation='softmax'))
model500.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])# вывод информации об архитектуре модели
print(model500.summary())# Обучаем модель
H = model500.fit(X_train, y_train, validation_split=0.1, epochs=50)# вывод графика ошибки по эпохам
plt.plot(H.history['loss'])
plt.plot(H.history['val_loss'])
plt.grid()
plt.xlabel('Epochs')
plt.ylabel('loss')
plt.legend(['train_loss', 'val_loss'])
plt.title('Loss by epochs')
plt.show()# Оценка качества работы модели на тестовых данных
scores = model500.evaluate(X_test, y_test)
print('Loss on test data:', scores[0])
print('Accuracy on test data:', scores[1])# сохранение модели на диск
model500.save('/content/drive/MyDrive/Colab Notebooks/models/model500in_1hide.keras')model10050 = Sequential()
model10050.add(Dense(units=100,input_dim=num_pixels, activation='sigmoid'))
model10050.add(Dense(units=50,activation='sigmoid'))
model10050.add(Dense(units=num_classes, activation='softmax'))
model10050.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])# вывод информации об архитектуре модели
print(model10050.summary())# Обучаем модель
H = model10050.fit(X_train, y_train, validation_split=0.1, epochs=50)# вывод графика ошибки по эпохам
plt.plot(H.history['loss'])
plt.plot(H.history['val_loss'])
plt.grid()
plt.xlabel('Epochs')
plt.ylabel('loss')
plt.legend(['train_loss', 'val_loss'])
plt.title('Loss by epochs')
plt.show()# Оценка качества работы модели на тестовых данных
scores = model10050.evaluate(X_test, y_test)
print('Loss on test data:', scores[0])
print('Accuracy on test data:', scores[1])# сохранение модели на диск
model10050.save('/content/drive/MyDrive/Colab Notebooks/models/model100in_1hide_50in_2hide.keras')model100100 = Sequential()
model100100.add(Dense(units=100,input_dim=num_pixels, activation='sigmoid'))
model100100.add(Dense(units=100,activation='sigmoid'))
model100100.add(Dense(units=num_classes, activation='softmax'))
model100100.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])# вывод информации об архитектуре модели
print(model100100.summary())# Обучаем модель
H = model100100.fit(X_train, y_train, validation_split=0.1, epochs=50)# вывод графика ошибки по эпохам
plt.plot(H.history['loss'])
plt.plot(H.history['val_loss'])
plt.grid()
plt.xlabel('Epochs')
plt.ylabel('loss')
plt.legend(['train_loss', 'val_loss'])
plt.title('Loss by epochs')
plt.show()# Оценка качества работы модели на тестовых данных
scores = model100100.evaluate(X_test, y_test)
print('Loss on test data:', scores[0])
print('Accuracy on test data:', scores[1])# сохранение модели на диск
model100100.save('/content/drive/MyDrive/Colab Notebooks/models/model100in_1hide_100in_2hide.keras')# сохранение лучшей модели в папку best_model
model100.save('/content/drive/MyDrive/Colab Notebooks/best_model/model100.keras')# Загрузка модели с диска
from keras.models import load_model
model = load_model('/content/drive/MyDrive/Colab Notebooks/best_model/model100.keras')# вывод тестового изображения и результата распознавания
n = 222
result = model.predict(X_test[n:n+1])
print('NN output:', result)
plt.imshow(X_test[n].reshape(28,28), cmap=plt.get_cmap('gray'))
plt.show()
print('Real mark: ', str(np.argmax(y_test[n])))
print('NN answer: ', str(np.argmax(result)))# вывод тестового изображения и результата распознавания
n = 123
result = model.predict(X_test[n:n+1])
print('NN output:', result)
plt.imshow(X_test[n].reshape(28,28), cmap=plt.get_cmap('gray'))
plt.show()
print('Real mark: ', str(np.argmax(y_test[n])))
print('NN answer: ', str(np.argmax(result)))# загрузка собственного изображения
from PIL import Image
file_data = Image.open('test.png')
file_data = file_data.convert('L') # перевод в градации серого
test_img = np.array(file_data)# вывод собственного изображения
plt.imshow(test_img, cmap=plt.get_cmap('gray'))
plt.show()
# предобработка
test_img = test_img / 255
test_img = test_img.reshape(1, num_pixels)
# распознавание
result = model.predict(test_img)
print('I think it\'s ', np.argmax(result))# загрузка собственного изображения
from PIL import Image
file2_data = Image.open('test2.png')
file2_data = file2_data.convert('L') # перевод в градации серого
test2_img = np.array(file2_data)# вывод собственного изображения
plt.imshow(test2_img, cmap=plt.get_cmap('gray'))
plt.show()
# предобработка
test2_img = test2_img / 255
test2_img = test2_img.reshape(1, num_pixels)
# распознавание
result_2 = model.predict(test2_img)
print('I think it\'s ', np.argmax(result_2))# загрузка собственного изображения, повернутого на 90 градусов
from PIL import Image
file90_data = Image.open('test90.png')
file90_data = file90_data.convert('L') # перевод в градации серого
test90_img = np.array(file90_data)# вывод собственного изображения
plt.imshow(test90_img, cmap=plt.get_cmap('gray'))
plt.show()
# предобработка
test90_img = test90_img / 255
test90_img = test90_img.reshape(1, num_pixels)
# распознавание
result_3 = model.predict(test90_img)
print('I think it\'s ', np.argmax(result_3))# загрузка собственного изображения, повернутого на 90 градусов
from PIL import Image
file902_data = Image.open('test90_2.png')
file902_data = file902_data.convert('L') # перевод в градации серого
test902_img = np.array(file902_data)# вывод собственного изображения
plt.imshow(test902_img, cmap=plt.get_cmap('gray'))
plt.show()
# предобработка
test902_img = test902_img / 255
test902_img = test902_img.reshape(1, num_pixels)
# распознавание
result_4 = model.predict(test902_img)
print('I think it\'s ', np.argmax(result_4))