Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

18 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=3)
#выводразмерностей
print('ShapeofXtrain:',X_train.shape)
print('Shapeofytrain:',y_train.shape)
print('ShapeofXtrain:',X_test.shape)
print('Shapeofytrain:',y_test.shape)
for i in range(4):
    plt.subplot(1, 4, i+1)  # 1 строка, n столбцов
    plt.imshow(X_train[i], cmap='gray')
    plt.axis('off')  # убрать оси
    plt.title(y_train[i])  # метка под картинкой

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('ShapeoftransformedXtrain:',X_train.shape)
#переведемметкивone-hot
from keras.utils import to_categorical
y_train=to_categorical(y_train)
y_test=to_categorical(y_test)
print('Shapeoftransformedytrain:',y_train.shape)
num_classes=y_train.shape[1]
#выводразмерностей
print('ShapeofXtrain:',X_train.shape)
print('Shapeofytrain:',y_train.shape)
print('ShapeofXtrain:',X_test.shape)
print('Shapeofytrain:',y_test.shape)
from keras.models import Sequential
from keras.layers import Dense
#1. создаеммодель-объявляемееобъектомклассаSequential
model=Sequential()
#4. добавляемвыходнойслой
model.add(Dense(input_dim=num_pixels,units=num_classes,activation='softmax'))
#5. компилируеммодель
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('Lossbyepochs')
plt.show()
#Оценкакачестваработымоделинатестовыхданных
scores=model.evaluate(X_test,y_test)
print('Loss on test data:',scores[0])
print('Accuracy on test data:',scores[1])
#1. создаеммодель-объявляемееобъектомклассаSequential
model_1h100=Sequential()
#2. добавляемпервыйскрытыйслой
model_1h100.add(Dense(units=100,input_dim=num_pixels,activation='sigmoid'))
#4. добавляемвыходнойслой
model_1h100.add(Dense(units=num_classes,activation='softmax'))
#5. компилируеммодель
model_1h100.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])
#выводинформацииобархитектуремодели
print(model_1h100.summary())
#Обучаеммодель
H=model_1h100.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('Lossbyepochs')
plt.show()
#Оценкакачестваработымоделинатестовыхданных
scores=model_1h100.evaluate(X_test,y_test)
print('Loss on test data:',scores[0])
print('Accuracy on test data:',scores[1])
#1. создаеммодель-объявляемееобъектомклассаSequential
model_1h300=Sequential()
#2. добавляемпервыйскрытыйслой
model_1h300.add(Dense(units=300,input_dim=num_pixels,activation='sigmoid'))
#4. добавляемвыходнойслой
model_1h300.add(Dense(units=num_classes,activation='softmax'))
#5. компилируеммодель
model_1h300.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])
#выводинформацииобархитектуремодели
print(model_1h300.summary())
#Обучаеммодель
H=model_1h300.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('Lossbyepochs')
plt.show()
#Оценкакачестваработымоделинатестовыхданных
scores=model_1h300.evaluate(X_test,y_test)
print('Loss on test data:',scores[0])
print('Accuracy on test data:',scores[1])
#1. создаеммодель-объявляемееобъектомклассаSequential
model_1h500=Sequential()
#2. добавляемпервыйскрытыйслой
model_1h500.add(Dense(units=500,input_dim=num_pixels,activation='sigmoid'))
#4. добавляемвыходнойслой
model_1h500.add(Dense(units=num_classes,activation='softmax'))
#5. компилируеммодель
model_1h500.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])
#выводинформацииобархитектуремодели
print(model_1h500.summary())
#Обучаеммодель
H=model_1h500.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('Lossbyepochs')
plt.show()
#Оценкакачестваработымоделинатестовыхданных
scores=model_1h500.evaluate(X_test,y_test)
print('Loss on test data:',scores[0])
print('Accuracy on test data:',scores[1])
#1. создаеммодель-объявляемееобъектомклассаSequential
model_1h100_2h50=Sequential()
#2. добавляемпервыйскрытыйслой
model_1h100_2h50.add(Dense(units=100,input_dim=num_pixels,activation='sigmoid'))
#3. добавляемвторойскрытыйслой
model_1h100_2h50.add(Dense(units=50,activation='sigmoid'))
#4. добавляемвыходнойслой
model_1h100_2h50.add(Dense(units=num_classes,activation='softmax'))
#5. компилируеммодель
model_1h100_2h50.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])
#выводинформацииобархитектуремодели
print(model_1h100_2h50.summary())
#Обучаеммодель
H=model_1h100_2h50.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('Lossbyepochs')
plt.show()
#Оценкакачестваработымоделинатестовыхданных
scores=model_1h100_2h50.evaluate(X_test,y_test)
print('Loss on test data:',scores[0])
print('Accuracy on test data:',scores[1])
#1. создаеммодель-объявляемееобъектомклассаSequential
model_1h100_2h100=Sequential()
#2. добавляемпервыйскрытыйслой
model_1h100_2h100.add(Dense(units=100,input_dim=num_pixels,activation='sigmoid'))
#3. добавляемвторойскрытыйслой
model_1h100_2h100.add(Dense(units=50,activation='sigmoid'))
#4. добавляемвыходнойслой
model_1h100_2h100.add(Dense(units=num_classes,activation='softmax'))
#5. компилируеммодель
model_1h100_2h100.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])
#выводинформацииобархитектуремодели
print(model_1h100_2h100.summary())
#Обучаеммодель
H=model_1h100_2h100.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('Lossbyepochs')
plt.show()
#Оценкакачестваработымоделинатестовыхданных
scores=model_1h100_2h100.evaluate(X_test,y_test)
print('Loss on test data:',scores[0])
print('Accuracy on test data:',scores[1])
#сохранение модели на диск, к примеру, в папку best_model
# В общем случае может быть указан произвольныйпуть
model_1h100.save('/content/drive/MyDrive/Colab Notebooks/best_model.keras')
#выводтестовогоизображенияирезультатараспознавания
for i in range(1,3,1):
  result=model_1h100.predict(X_test[i:i+1])
  print('NNoutput:',result)
  plt.imshow(X_test[i].reshape(28,28),cmap=plt.get_cmap('gray'))
  plt.show()
  print('Realmark:',str(np.argmax(y_test[i])))
  print('NNanswer:',str(np.argmax(result)))
#загрузкасобственногоизображения
from PIL import Image
file_data=Image.open('/content/drive/MyDrive/Colab Notebooks/2.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_1h100.predict(test_img)
print('Ithinkit\'s',np.argmax(result))
#загрузкасобственногоизображения
from PIL import Image
file_data=Image.open('/content/drive/MyDrive/Colab Notebooks/5.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_1h100.predict(test_img)
print('Ithinkit\'s',np.argmax(result))
#загрузкасобственногоизображения
from PIL import Image
file_data=Image.open('/content/drive/MyDrive/Colab Notebooks/2_1.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_1h100.predict(test_img)
print('Ithinkit\'s',np.argmax(result))
#загрузкасобственногоизображения
from PIL import Image
file_data=Image.open('/content/drive/MyDrive/Colab Notebooks/5_1.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_1h100.predict(test_img)
print('Ithinkit\'s',np.argmax(result))