{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"gpuType":"T4","mount_file_id":"1pB_9A5KEAxR-yaJKEK-xnufva6qeYoGt","authorship_tag":"ABX9TyPTj5kxzxkYSrIyEAiji6SV"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU"},"cells":[{"cell_type":"code","execution_count":null,"metadata":{"id":"Q8_YxCOaQUt0"},"outputs":[],"source":["import os\n","os.chdir('/content/drive/MyDrive/Colab Notebooks')"]},{"cell_type":"code","source":["#импортмодулей\n","from tensorflow import keras\n","import matplotlib.pyplot as plt\n","import numpy as np\n","import sklearn"],"metadata":{"id":"akKkgoU5R6V0"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#загрузкадатасета\n","from keras.datasets import mnist\n","(X_train,y_train),(X_test,y_test)=mnist.load_data()"],"metadata":{"id":"pY5Sd4glSkGW"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#созданиесвоегоразбиениядатасета\n","from sklearn.model_selection import train_test_split\n","\n","#объединяемводиннабор\n","X=np.concatenate((X_train,X_test))\n","y=np.concatenate((y_train,y_test))\n","\n","#разбиваемповариантам\n","X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=10000,train_size=60000,random_state=3)\n"],"metadata":{"id":"o7qrOgNbTnHu"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводразмерностей\n","print('ShapeofXtrain:',X_train.shape)\n","print('Shapeofytrain:',y_train.shape)\n","print('ShapeofXtrain:',X_test.shape)\n","print('Shapeofytrain:',y_test.shape)"],"metadata":{"id":"SE_C2JaCK6o0"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["for i in range(4):\n"," plt.subplot(1, 4, i+1) # 1 строка, n столбцов\n"," plt.imshow(X_train[i], cmap='gray')\n"," plt.axis('off') # убрать оси\n"," plt.title(y_train[i]) # метка под картинкой\n","\n","plt.show()"],"metadata":{"id":"Az-Nx-d5ZOiU"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#развернемкаждоеизображение28*28ввектор784\n","num_pixels=X_train.shape[1]*X_train.shape[2]\n","X_train=X_train.reshape(X_train.shape[0],num_pixels) / 255\n","X_test=X_test.reshape(X_test.shape[0],num_pixels) / 255\n","print('ShapeoftransformedXtrain:',X_train.shape)"],"metadata":{"id":"91nxqKwwZ065"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#переведемметкивone-hot\n","from keras.utils import to_categorical\n","y_train=to_categorical(y_train)\n","y_test=to_categorical(y_test)\n","print('Shapeoftransformedytrain:',y_train.shape)\n","num_classes=y_train.shape[1]"],"metadata":{"id":"jptZc4o5atsC"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводразмерностей\n","print('ShapeofXtrain:',X_train.shape)\n","print('Shapeofytrain:',y_train.shape)\n","print('ShapeofXtrain:',X_test.shape)\n","print('Shapeofytrain:',y_test.shape)"],"metadata":{"id":"9E6AgNHqa-iq"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["from keras.models import Sequential\n","from keras.layers import Dense"],"metadata":{"id":"crgcsx98cSfp"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#1. создаеммодель-объявляемееобъектомклассаSequential\n","model=Sequential()\n","#4. добавляемвыходнойслой\n","model.add(Dense(input_dim=num_pixels,units=num_classes,activation='softmax'))\n","#5. компилируеммодель\n","model.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])"],"metadata":{"id":"XYlqJGvbflQi"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводинформацииобархитектуремодели\n","print(model.summary())"],"metadata":{"id":"y1IAptZvfTe8"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Обучаеммодель\n","H=model.fit(X_train,y_train,validation_split=0.1,epochs=50)"],"metadata":{"id":"f5TUtfc2fyJb"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводграфикаошибкипоэпохам\n","plt.plot(H.history['loss'])\n","plt.plot(H.history['val_loss'])\n","plt.grid()\n","plt.xlabel('Epochs')\n","plt.ylabel('loss')\n","plt.legend(['train_loss','val_loss'])\n","plt.title('Lossbyepochs')\n","plt.show()"],"metadata":{"id":"bADnh1ohhwBt"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Оценкакачестваработымоделинатестовыхданных\n","scores=model.evaluate(X_test,y_test)\n","print('Loss on test data:',scores[0])\n","print('Accuracy on test data:',scores[1])"],"metadata":{"id":"ObDBL_UbiLmz"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#1. создаеммодель-объявляемееобъектомклассаSequential\n","model_1h100=Sequential()\n","#2. добавляемпервыйскрытыйслой\n","model_1h100.add(Dense(units=100,input_dim=num_pixels,activation='sigmoid'))\n","#4. добавляемвыходнойслой\n","model_1h100.add(Dense(units=num_classes,activation='softmax'))\n","#5. компилируеммодель\n","model_1h100.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])"],"metadata":{"id":"MdQpaAHTjUmC"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводинформацииобархитектуремодели\n","print(model_1h100.summary())"],"metadata":{"id":"8ucG_PWRjQEH"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Обучаеммодель\n","H=model_1h100.fit(X_train,y_train,validation_split=0.1,epochs=50)"],"metadata":{"id":"BSuXwm4Ije_W"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводграфикаошибкипоэпохам\n","plt.plot(H.history['loss'])\n","plt.plot(H.history['val_loss'])\n","plt.grid()\n","plt.xlabel('Epochs')\n","plt.ylabel('loss')\n","plt.legend(['train_loss','val_loss'])\n","plt.title('Lossbyepochs')\n","plt.show()"],"metadata":{"id":"Fbuton7ejnBK"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Оценкакачестваработымоделинатестовыхданных\n","scores=model_1h100.evaluate(X_test,y_test)\n","print('Loss on test data:',scores[0])\n","print('Accuracy on test data:',scores[1])"],"metadata":{"id":"6a49VWXljq3w"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#1. создаеммодель-объявляемееобъектомклассаSequential\n","model_1h300=Sequential()\n","#2. добавляемпервыйскрытыйслой\n","model_1h300.add(Dense(units=300,input_dim=num_pixels,activation='sigmoid'))\n","#4. добавляемвыходнойслой\n","model_1h300.add(Dense(units=num_classes,activation='softmax'))\n","#5. компилируеммодель\n","model_1h300.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])"],"metadata":{"id":"kciVMYeNjzHX"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводинформацииобархитектуремодели\n","print(model_1h300.summary())"],"metadata":{"id":"kigRJsHoj6y1"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Обучаеммодель\n","H=model_1h300.fit(X_train,y_train,validation_split=0.1,epochs=50)"],"metadata":{"id":"wdp6M3Y-kDAA"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводграфикаошибкипоэпохам\n","plt.plot(H.history['loss'])\n","plt.plot(H.history['val_loss'])\n","plt.grid()\n","plt.xlabel('Epochs')\n","plt.ylabel('loss')\n","plt.legend(['train_loss','val_loss'])\n","plt.title('Lossbyepochs')\n","plt.show()"],"metadata":{"id":"FoECwiVRkEv2"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Оценкакачестваработымоделинатестовыхданных\n","scores=model_1h300.evaluate(X_test,y_test)\n","print('Loss on test data:',scores[0])\n","print('Accuracy on test data:',scores[1])"],"metadata":{"id":"AObBzqb1kKsg"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#1. создаеммодель-объявляемееобъектомклассаSequential\n","model_1h500=Sequential()\n","#2. добавляемпервыйскрытыйслой\n","model_1h500.add(Dense(units=500,input_dim=num_pixels,activation='sigmoid'))\n","#4. добавляемвыходнойслой\n","model_1h500.add(Dense(units=num_classes,activation='softmax'))\n","#5. компилируеммодель\n","model_1h500.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])"],"metadata":{"id":"pppCSy5DkMG2"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводинформацииобархитектуремодели\n","print(model_1h500.summary())"],"metadata":{"id":"cIhtFnldkRFD"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Обучаеммодель\n","H=model_1h500.fit(X_train,y_train,validation_split=0.1,epochs=50)"],"metadata":{"id":"pRSEYZPkkVRx"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводграфикаошибкипоэпохам\n","plt.plot(H.history['loss'])\n","plt.plot(H.history['val_loss'])\n","plt.grid()\n","plt.xlabel('Epochs')\n","plt.ylabel('loss')\n","plt.legend(['train_loss','val_loss'])\n","plt.title('Lossbyepochs')\n","plt.show()"],"metadata":{"id":"mQ4jVEtUkWqY"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Оценкакачестваработымоделинатестовыхданных\n","scores=model_1h500.evaluate(X_test,y_test)\n","print('Loss on test data:',scores[0])\n","print('Accuracy on test data:',scores[1])"],"metadata":{"id":"XKkpVAPXkdFe"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#1. создаеммодель-объявляемееобъектомклассаSequential\n","model_1h100_2h50=Sequential()\n","#2. добавляемпервыйскрытыйслой\n","model_1h100_2h50.add(Dense(units=100,input_dim=num_pixels,activation='sigmoid'))\n","#3. добавляемвторойскрытыйслой\n","model_1h100_2h50.add(Dense(units=50,activation='sigmoid'))\n","#4. добавляемвыходнойслой\n","model_1h100_2h50.add(Dense(units=num_classes,activation='softmax'))\n","#5. компилируеммодель\n","model_1h100_2h50.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])"],"metadata":{"id":"pgW5whX5oDly"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводинформацииобархитектуремодели\n","print(model_1h100_2h50.summary())"],"metadata":{"id":"VohVnj6BobvZ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Обучаеммодель\n","H=model_1h100_2h50.fit(X_train,y_train,validation_split=0.1,epochs=50)"],"metadata":{"id":"NXe3m7h3ofNJ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводграфикаошибкипоэпохам\n","plt.plot(H.history['loss'])\n","plt.plot(H.history['val_loss'])\n","plt.grid()\n","plt.xlabel('Epochs')\n","plt.ylabel('loss')\n","plt.legend(['train_loss','val_loss'])\n","plt.title('Lossbyepochs')\n","plt.show()"],"metadata":{"id":"hL9PJ1nAop1X"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Оценкакачестваработымоделинатестовыхданных\n","scores=model_1h100_2h50.evaluate(X_test,y_test)\n","print('Loss on test data:',scores[0])\n","print('Accuracy on test data:',scores[1])"],"metadata":{"id":"q4RZeZKMotDH"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#1. создаеммодель-объявляемееобъектомклассаSequential\n","model_1h100_2h100=Sequential()\n","#2. добавляемпервыйскрытыйслой\n","model_1h100_2h100.add(Dense(units=100,input_dim=num_pixels,activation='sigmoid'))\n","#3. добавляемвторойскрытыйслой\n","model_1h100_2h100.add(Dense(units=50,activation='sigmoid'))\n","#4. добавляемвыходнойслой\n","model_1h100_2h100.add(Dense(units=num_classes,activation='softmax'))\n","#5. компилируеммодель\n","model_1h100_2h100.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])"],"metadata":{"id":"LRrTGUjlovso"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводинформацииобархитектуремодели\n","print(model_1h100_2h100.summary())"],"metadata":{"id":"ESm8Dst8o3Dz"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Обучаеммодель\n","H=model_1h100_2h100.fit(X_train,y_train,validation_split=0.1,epochs=50)"],"metadata":{"id":"8D0_5J1ho7mY"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводграфикаошибкипоэпохам\n","plt.plot(H.history['loss'])\n","plt.plot(H.history['val_loss'])\n","plt.grid()\n","plt.xlabel('Epochs')\n","plt.ylabel('loss')\n","plt.legend(['train_loss','val_loss'])\n","plt.title('Lossbyepochs')\n","plt.show()"],"metadata":{"id":"8nR-jaLXo-Gm"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#Оценкакачестваработымоделинатестовыхданных\n","scores=model_1h100_2h100.evaluate(X_test,y_test)\n","print('Loss on test data:',scores[0])\n","print('Accuracy on test data:',scores[1])"],"metadata":{"id":"HgSZgyP4pAbQ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#сохранение модели на диск, к примеру, в папку best_model\n","# В общем случае может быть указан произвольныйпуть\n","model_1h100.save('/content/drive/MyDrive/Colab Notebooks/best_model.keras')"],"metadata":{"id":"0OxGWL-bsYCu"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводтестовогоизображенияирезультатараспознавания\n","for i in range(1,3,1):\n"," result=model_1h100.predict(X_test[i:i+1])\n"," print('NNoutput:',result)\n"," plt.imshow(X_test[i].reshape(28,28),cmap=plt.get_cmap('gray'))\n"," plt.show()\n"," print('Realmark:',str(np.argmax(y_test[i])))\n"," print('NNanswer:',str(np.argmax(result)))\n",""],"metadata":{"id":"Wz5W-GoxtWWj"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#загрузкасобственногоизображения\n","from PIL import Image\n","file_data=Image.open('/content/drive/MyDrive/Colab Notebooks/2.png')\n","file_data=file_data.convert('L')\n","#переводвградациисерого\n","test_img=np.array(file_data)"],"metadata":{"id":"9mf7D_Il-N4-"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводсобственногоизображения\n","plt.imshow(test_img,cmap=plt.get_cmap('gray'))\n","plt.show()\n","#предобработка\n","test_img=test_img/255\n","test_img=test_img.reshape(1,num_pixels)\n","#распознавание\n","result=model_1h100.predict(test_img)\n","print('Ithinkit\\'s',np.argmax(result))"],"metadata":{"id":"tYJNuErx-93n"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#загрузкасобственногоизображения\n","from PIL import Image\n","file_data=Image.open('/content/drive/MyDrive/Colab Notebooks/5.png')\n","file_data=file_data.convert('L')\n","#переводвградациисерого\n","test_img=np.array(file_data)"],"metadata":{"id":"VBo05XDvCQhg"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводсобственногоизображения\n","plt.imshow(test_img,cmap=plt.get_cmap('gray'))\n","plt.show()\n","#предобработка\n","test_img=test_img/255\n","test_img=test_img.reshape(1,num_pixels)\n","#распознавание\n","result=model_1h100.predict(test_img)\n","print('Ithinkit\\'s',np.argmax(result))"],"metadata":{"id":"FHRi9FqdCRMm"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#загрузкасобственногоизображения\n","from PIL import Image\n","file_data=Image.open('/content/drive/MyDrive/Colab Notebooks/2_1.png')\n","file_data=file_data.convert('L')\n","#переводвградациисерого\n","test_img=np.array(file_data)"],"metadata":{"id":"QNEPW5OlCVUr"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводсобственногоизображения\n","plt.imshow(test_img,cmap=plt.get_cmap('gray'))\n","plt.show()\n","#предобработка\n","test_img=test_img/255\n","test_img=test_img.reshape(1,num_pixels)\n","#распознавание\n","result=model_1h100.predict(test_img)\n","print('Ithinkit\\'s',np.argmax(result))"],"metadata":{"id":"d9r-7ekxCSkh"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#загрузкасобственногоизображения\n","from PIL import Image\n","file_data=Image.open('/content/drive/MyDrive/Colab Notebooks/5_1.png')\n","file_data=file_data.convert('L')\n","#переводвградациисерого\n","test_img=np.array(file_data)"],"metadata":{"id":"mP13GXpGCWB_"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#выводсобственногоизображения\n","plt.imshow(test_img,cmap=plt.get_cmap('gray'))\n","plt.show()\n","#предобработка\n","test_img=test_img/255\n","test_img=test_img.reshape(1,num_pixels)\n","#распознавание\n","result=model_1h100.predict(test_img)\n","print('Ithinkit\\'s',np.argmax(result))"],"metadata":{"id":"Mgyf8ZbFCTZ2"},"execution_count":null,"outputs":[]}]}