{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten\nfrom tensorflow.keras.layers import Dropout, BatchNormalization, SpatialDropout2D, GaussianDropout\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.keras import utils\nfrom tensorflow.keras.preprocessing import image\nimport matplotlib.pyplot as plt\n%matplotlib inline ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 128\nnb_classes = 10\nnb_epoch = 40\nimg_rows, img_cols = 32, 32\nimg_channels = 3\nclasses = ['самолет', 'автомобиль', 'птица', 'кот', 'олень', 'собака', 'лягушка', 'лошадь', 'корабль', 'грузовик']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"(X_train, y_train), (X_test, y_test) = cifar10.load_data()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n = 101\n# plt.imshow(X_train[n])\n# plt.show()\n# print(\"Номер класса:\", y_train[n])\n# print(\"Тип объекта:\", classes[y_train[n][0]])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# X_train = X_train.reshape((50000, 32, 32, 3))\nX_train = X_train.astype('float32')\n# X_test = X_test.reshape((10000, 32, 32, 3))\nX_test = X_test.astype('float32')\nX_train /= 255\nX_test /= 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = utils.to_categorical(y_train, nb_classes)\nY_test = utils.to_categorical(y_test, nb_classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=32, kernel_size=(3, 3), padding='same',\n                        input_shape=(img_rows, img_cols, img_channels), activation='relu'))\nmodel.add(Conv2D(128, (3, 3), activation='relu', padding='same'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(64, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(Conv2D(128, (3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.25))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(BatchNormalization()) \nmodel.add(Dropout(0.75))\nmodel.add(Dense(nb_classes, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ncallbacks_list = [EarlyStopping(monitor='val_loss', patience=5),\n                  ModelCheckpoint(filepath='my_model.h5',\n                                  monitor='val_loss',\n                                  save_best_only=True),\n                  ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3)\n                  ] \nmodel.compile(loss='categorical_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nhistory = model.fit(X_train, Y_train,\n              batch_size=batch_size,\n              epochs=nb_epoch,\n              callbacks=callbacks_list,\n              validation_split=0.1,\n              verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = model.evaluate(X_test, Y_test, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Доля верных ответов на тестовых данных, в процентах:\", round(scores[1] * 100, 4))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['accuracy'], \n         label='Доля правильных ответов на обучающем наборе')\nplt.plot(history.history['val_accuracy'], \n         label='Доля правильных ответов на проверочном наборе')\nplt.xlabel('Эпоха обучения')\nplt.ylabel('Доля правильных ответов')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'], \n         label='Оценка потерь на обучающем наборе')\nplt.plot(history.history['val_loss'], \n         label='Оценка потерь на проверочном наборе')\nplt.xlabel('Эпоха обучения')\nplt.ylabel('Оценка потерь')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.save(\"cifar10_model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# files.download(\"cifar10_model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}