{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"},{"sourceId":9900,"sourceType":"datasetVersion","datasetId":6209}],"dockerImageVersionId":11543,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Загружаем библеотеки","metadata":{}},{"cell_type":"code","source":"import os, cv2, random\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom tqdm import tqdm\nfrom random import shuffle \nfrom IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\nfrom tensorflow.python.keras.applications import ResNet50\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D\n%matplotlib inline ","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-12-26T16:36:31.667402Z","iopub.execute_input":"2023-12-26T16:36:31.667725Z","iopub.status.idle":"2023-12-26T16:36:32.988062Z","shell.execute_reply.started":"2023-12-26T16:36:31.667657Z","shell.execute_reply":"2023-12-26T16:36:32.987020Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TEST_SIZE = 0.5\nRANDOM_STATE = 2018\nBATCH_SIZE = 64\nNO_EPOCHS = 20\nNUM_CLASSES = 2\nSAMPLE_SIZE = 20000\nPATH = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/'\nTRAIN_FOLDER = './train/'\nTEST_FOLDER =  './test/'\nIMG_SIZE = 224\nRESNET_WEIGHTS_PATH = '/kaggle/input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'","metadata":{"_uuid":"f265a0cfc1bc6379507962130087e7f212e12f83","execution":{"iopub.status.busy":"2023-12-26T16:36:32.991547Z","iopub.execute_input":"2023-12-26T16:36:32.991876Z","iopub.status.idle":"2023-12-26T16:36:32.997607Z","shell.execute_reply.started":"2023-12-26T16:36:32.991815Z","shell.execute_reply":"2023-12-26T16:36:32.996825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Читаем данные\n\n\nМы устанавливаем список изображений train.\nУстановив значение SAMPLE_SIZE, мы можем уменьшить/увеличить размер обучающего набора.\nВ настоящее время SAMPLE_SIZE установлен равным 20 000.","metadata":{"_uuid":"a1c725fa996e10190a924b977354d82b767c68bf"}},{"cell_type":"code","source":"train_image_path = os.path.join(PATH, \"train.zip\")\ntest_image_path = os.path.join(PATH, \"test.zip\")","metadata":{"execution":{"iopub.status.busy":"2023-12-26T16:36:32.998798Z","iopub.execute_input":"2023-12-26T16:36:32.999087Z","iopub.status.idle":"2023-12-26T16:36:33.010536Z","shell.execute_reply.started":"2023-12-26T16:36:32.999033Z","shell.execute_reply":"2023-12-26T16:36:33.009838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nwith zipfile.ZipFile(train_image_path,\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2023-12-26T16:36:33.013749Z","iopub.execute_input":"2023-12-26T16:36:33.014048Z","iopub.status.idle":"2023-12-26T16:36:44.352082Z","shell.execute_reply.started":"2023-12-26T16:36:33.013991Z","shell.execute_reply":"2023-12-26T16:36:44.351247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with zipfile.ZipFile(test_image_path,\"r\") as z:\n    z.extractall(\".\")","metadata":{"execution":{"iopub.status.busy":"2023-12-26T16:36:44.353289Z","iopub.execute_input":"2023-12-26T16:36:44.353532Z","iopub.status.idle":"2023-12-26T16:36:50.165688Z","shell.execute_reply.started":"2023-12-26T16:36:44.353492Z","shell.execute_reply":"2023-12-26T16:36:50.164916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image_list = os.listdir(\"./train/\")[0:SAMPLE_SIZE]\ntest_image_list = os.listdir(\"./test/\")","metadata":{"_uuid":"12d65488fa58182f965485608965ae36f345f183","execution":{"iopub.status.busy":"2023-12-26T16:36:50.167014Z","iopub.execute_input":"2023-12-26T16:36:50.167268Z","iopub.status.idle":"2023-12-26T16:36:50.195246Z","shell.execute_reply.started":"2023-12-26T16:36:50.167219Z","shell.execute_reply":"2023-12-26T16:36:50.194667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Мы настроили функцию для разбора названий изображений, чтобы извлечь первые 3 буквы из названий изображений, что дает метку изображения. Это будет либо кошка, либо собака. Мы используем один горячий кодер, сохраняя [1,0] для кошки и [0,1] для собаки.","metadata":{"_uuid":"729f56cad0895facac99467faec510d3d61156a9"}},{"cell_type":"code","source":"def label_pet_image_one_hot_encoder(img):\n    pet = img.split('.')[-3]\n    if pet == 'cat': return [1,0]\n    elif pet == 'dog': return [0,1]","metadata":{"_uuid":"1df3dd73913a3e63a059edec2496e2db1d570c34","execution":{"iopub.status.busy":"2023-12-26T16:36:50.196741Z","iopub.execute_input":"2023-12-26T16:36:50.197038Z","iopub.status.idle":"2023-12-26T16:36:50.201541Z","shell.execute_reply.started":"2023-12-26T16:36:50.196984Z","shell.execute_reply":"2023-12-26T16:36:50.200775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def process_data(data_image_list, DATA_FOLDER, isTrain=True):\n    data_df = []\n    for img in tqdm(data_image_list):\n        path = os.path.join(DATA_FOLDER,img)\n        if(isTrain):\n            label = label_pet_image_one_hot_encoder(img)\n        else:\n            label = img.split('.')[0]\n        img = cv2.imread(path,cv2.IMREAD_COLOR)\n        img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))\n        data_df.append([np.array(img),np.array(label)])\n    shuffle(data_df)\n    return data_df","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","execution":{"iopub.status.busy":"2023-12-26T16:36:50.202798Z","iopub.execute_input":"2023-12-26T16:36:50.203029Z","iopub.status.idle":"2023-12-26T16:36:50.212270Z","shell.execute_reply.started":"2023-12-26T16:36:50.202981Z","shell.execute_reply":"2023-12-26T16:36:50.211505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Исследуем данные\n\n\n## <a id=\"41\">Class distribution</a>\n","metadata":{"_uuid":"cd19491249f9dd5bc2fd8bfbdfd124fdcdb0cbe1"}},{"cell_type":"code","source":"def plot_image_list_count(data_image_list):\n    labels = []\n    for img in data_image_list:\n        labels.append(img.split('.')[-3])\n    sns.countplot(labels)\n    plt.title('Cats and Dogs')\n    \nplot_image_list_count(train_image_list)","metadata":{"_uuid":"2901e1126ebe160a5a5c5a03dd07d5b8792a5290","execution":{"iopub.status.busy":"2023-12-26T16:36:50.213480Z","iopub.execute_input":"2023-12-26T16:36:50.213761Z","iopub.status.idle":"2023-12-26T16:36:50.448908Z","shell.execute_reply.started":"2023-12-26T16:36:50.213707Z","shell.execute_reply":"2023-12-26T16:36:50.447899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Также посмотрим весь сет на тренеровочной выборке","metadata":{"_uuid":"1815a71df706af6e6d7592a7366caaba5c0cdad1"}},{"cell_type":"code","source":"plot_image_list_count(os.listdir(TRAIN_FOLDER))","metadata":{"_uuid":"1f36b71d110658540e3cbf3e435e00810ebb2d19","execution":{"iopub.status.busy":"2023-12-26T16:36:50.450521Z","iopub.execute_input":"2023-12-26T16:36:50.451084Z","iopub.status.idle":"2023-12-26T16:36:50.743502Z","shell.execute_reply.started":"2023-12-26T16:36:50.451014Z","shell.execute_reply":"2023-12-26T16:36:50.742499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Образцы изображенний","metadata":{"_uuid":"c76a6072f4d272ffc7906d56a3008449a569f45b"}},{"cell_type":"code","source":"train = process_data(train_image_list, TRAIN_FOLDER)","metadata":{"_uuid":"d1b8ee45b627b58a3a5d04bb0c64fb18d5e8f592","execution":{"iopub.status.busy":"2023-12-26T16:36:50.745125Z","iopub.execute_input":"2023-12-26T16:36:50.745690Z","iopub.status.idle":"2023-12-26T16:37:31.227478Z","shell.execute_reply.started":"2023-12-26T16:36:50.745618Z","shell.execute_reply":"2023-12-26T16:37:31.226667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Затем мы наносим на график выбранное изображение.","metadata":{"_uuid":"a3583fc9056b32953bae9b90a3aaab7ff451c025"}},{"cell_type":"code","source":"def show_images(data, isTest=False):\n    f, ax = plt.subplots(5,5, figsize=(15,15))\n    for i,data in enumerate(data[:25]):\n        img_num = data[1]\n        img_data = data[0]\n        label = np.argmax(img_num)\n        if label  == 1: \n            str_label='Dog'\n        elif label == 0: \n            str_label='Cat'\n        if(isTest):\n            str_label=\"None\"\n        ax[i//5, i%5].imshow(img_data)\n        ax[i//5, i%5].axis('off')\n        ax[i//5, i%5].set_title(\"Label: {}\".format(str_label))\n    plt.show()\n\nshow_images(train)","metadata":{"_uuid":"8a2b305bce44360f693d678a4b7eb9f27b3a7d36","execution":{"iopub.status.busy":"2023-12-26T16:37:31.229064Z","iopub.execute_input":"2023-12-26T16:37:31.229422Z","iopub.status.idle":"2023-12-26T16:37:32.768735Z","shell.execute_reply.started":"2023-12-26T16:37:31.229357Z","shell.execute_reply":"2023-12-26T16:37:32.767700Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = process_data(test_image_list, TEST_FOLDER, False)","metadata":{"_uuid":"cb0696a3111e5421b3809f91bcb040f32cbde799","execution":{"iopub.status.busy":"2023-12-26T16:37:32.769939Z","iopub.execute_input":"2023-12-26T16:37:32.770157Z","iopub.status.idle":"2023-12-26T16:37:57.806429Z","shell.execute_reply.started":"2023-12-26T16:37:32.770118Z","shell.execute_reply":"2023-12-26T16:37:57.805560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_images(test,True)","metadata":{"_uuid":"485ff5d66200edf7159027b49d4e60619b8b404a","execution":{"iopub.status.busy":"2023-12-26T16:37:57.807639Z","iopub.execute_input":"2023-12-26T16:37:57.807877Z","iopub.status.idle":"2023-12-26T16:37:59.458675Z","shell.execute_reply.started":"2023-12-26T16:37:57.807827Z","shell.execute_reply":"2023-12-26T16:37:59.457235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Модель\nГотовим модель\nДавайте начнем с подготовки модели.","metadata":{}},{"cell_type":"code","source":"X = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,3)\ny = np.array([i[1] for i in train])","metadata":{"_uuid":"7651e9ef5ff8074165a5208257c5db81ab83b75f","execution":{"iopub.status.busy":"2023-12-26T16:37:59.459811Z","iopub.execute_input":"2023-12-26T16:37:59.460056Z","iopub.status.idle":"2023-12-26T16:38:01.608604Z","shell.execute_reply.started":"2023-12-26T16:37:59.460004Z","shell.execute_reply":"2023-12-26T16:38:01.607836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Подготовьте модель\nМы инициализируем модель ResNet-50, добавляя дополнительный последний слой типа Dense с функцией активации softmax.\n\nМы также устанавливаем, что первый слой модели не поддается обучению, поскольку модель ResNet-50 уже была обучена.","metadata":{"_uuid":"802f6921a5ab7e2b75b6cb239bedd71cb2c0e4cd"}},{"cell_type":"code","source":"model = Sequential()\nmodel.add(ResNet50(include_top=False, pooling='max', weights=RESNET_WEIGHTS_PATH))\nmodel.add(Dense(NUM_CLASSES, activation='softmax'))\n# ResNet-50 model is already trained, should not be trained\nmodel.layers[0].trainable = True","metadata":{"_uuid":"94892424cb4e898d6b7c3df1269cfab6371c4eb9","execution":{"iopub.status.busy":"2023-12-26T16:38:01.610078Z","iopub.execute_input":"2023-12-26T16:38:01.610310Z","iopub.status.idle":"2023-12-26T16:38:13.606039Z","shell.execute_reply.started":"2023-12-26T16:38:01.610259Z","shell.execute_reply":"2023-12-26T16:38:13.605328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"_uuid":"c24a3f51ef3487e15efdc8c2e876aea7c429b876","execution":{"iopub.status.busy":"2023-12-26T16:38:13.607189Z","iopub.execute_input":"2023-12-26T16:38:13.607466Z","iopub.status.idle":"2023-12-26T16:38:13.733009Z","shell.execute_reply.started":"2023-12-26T16:38:13.607413Z","shell.execute_reply":"2023-12-26T16:38:13.732408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Краткое описание модели\nМы строим описание модели. Мы видим, что модель ResNet-50 представляет собой 1-й уровень нашей модели, типа Model.","metadata":{"_uuid":"52e06decf4d5ea9e099b4669681b8ebb36ccd7bd"}},{"cell_type":"code","source":"model.summary()","metadata":{"_uuid":"3e2a3ff8c2dd896fd9ca725625587564165d0727","execution":{"iopub.status.busy":"2023-12-26T17:16:33.395958Z","iopub.execute_input":"2023-12-26T17:16:33.396278Z","iopub.status.idle":"2023-12-26T17:16:33.409639Z","shell.execute_reply.started":"2023-12-26T17:16:33.396233Z","shell.execute_reply":"2023-12-26T17:16:33.408736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_model(model, to_file='model.png')\nSVG(model_to_dot(model).create(prog='dot', format='svg'))","metadata":{"_uuid":"64561287fa8faaa756ba4043a2a3c671810a9dbf","execution":{"iopub.status.busy":"2023-12-26T17:16:33.806134Z","iopub.execute_input":"2023-12-26T17:16:33.806461Z","iopub.status.idle":"2023-12-26T17:16:34.972392Z","shell.execute_reply.started":"2023-12-26T17:16:33.806401Z","shell.execute_reply":"2023-12-26T17:16:34.971383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Сплитуем данные для обучения","metadata":{"_uuid":"cba1cd58d8f3e3240fafe88ba5ac4c8cd3885008"}},{"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=TEST_SIZE, random_state=RANDOM_STATE)","metadata":{"_uuid":"e80c5bd03d275807865c424187f752b521c99f15","execution":{"iopub.status.busy":"2023-12-26T17:16:36.478831Z","iopub.execute_input":"2023-12-26T17:16:36.479122Z","iopub.status.idle":"2023-12-26T17:16:38.682601Z","shell.execute_reply.started":"2023-12-26T17:16:36.479069Z","shell.execute_reply":"2023-12-26T17:16:38.681915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Тренеруем модель","metadata":{"_uuid":"cb28fa20f06729cb20a31e7b5c1f99970ebe62fa"}},{"cell_type":"code","source":"train_model = model.fit(X_train, y_train,\n                  batch_size=BATCH_SIZE,\n                  epochs=NO_EPOCHS,\n                  verbose=1,\n                  validation_data=(X_val, y_val))","metadata":{"_uuid":"3899d6c135949c4546d5aa10291fb5b1ff4498da","execution":{"iopub.status.busy":"2023-12-26T17:16:41.014221Z","iopub.execute_input":"2023-12-26T17:16:41.014544Z","iopub.status.idle":"2023-12-26T17:47:44.982188Z","shell.execute_reply.started":"2023-12-26T17:16:41.014483Z","shell.execute_reply":"2023-12-26T17:47:44.981412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_accuracy_and_loss(train_model):\n    hist = train_model.history\n    acc = hist['acc']\n    val_acc = hist['val_acc']\n    loss = hist['loss']\n    val_loss = hist['val_loss']\n    epochs = range(len(acc))\n    f, ax = plt.subplots(1,2, figsize=(14,6))\n    ax[0].plot(epochs, acc, 'g', label='Training accuracy')\n    ax[0].plot(epochs, val_acc, 'r', label='Validation accuracy')\n    ax[0].set_title('Training and validation accuracy')\n    ax[0].legend()\n    ax[1].plot(epochs, loss, 'g', label='Training loss')\n    ax[1].plot(epochs, val_loss, 'r', label='Validation loss')\n    ax[1].set_title('Training and validation loss')\n    ax[1].legend()\n    plt.show()\nplot_accuracy_and_loss(train_model)","metadata":{"execution":{"iopub.status.busy":"2023-12-26T17:47:44.983775Z","iopub.execute_input":"2023-12-26T17:47:44.984041Z","iopub.status.idle":"2023-12-26T17:47:45.307367Z","shell.execute_reply.started":"2023-12-26T17:47:44.983989Z","shell.execute_reply":"2023-12-26T17:47:45.306589Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Точность и потери при валидации\nДавайте покажем состав и точность валидации на одном графике. Также мы представим состав и потери при валидации на одном графике. Validation accuracy and loss","metadata":{"_uuid":"e9c9159b0a2f2fc8bafe9bfc1983c30a846f099a"}},{"cell_type":"code","source":"score = model.evaluate(X_val, y_val, verbose=0)\nprint('Validation loss:', score[0])\nprint('Validation accuracy:', score[1])","metadata":{"_uuid":"0935a9e239a7af382208ecede99bd2afb5098482","execution":{"iopub.status.busy":"2023-12-26T17:47:45.308744Z","iopub.execute_input":"2023-12-26T17:47:45.309021Z","iopub.status.idle":"2023-12-26T17:48:09.110985Z","shell.execute_reply.started":"2023-12-26T17:47:45.308971Z","shell.execute_reply":"2023-12-26T17:48:09.110137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Точность проверки для каждого класса\nДавайте покажем точность проверки для каждого класса.\n\nМы начинаем с прогнозирования меток для набора проверок.","metadata":{"_uuid":"ec8bbac69464197827260097132a0c297dd07b94"}},{"cell_type":"code","source":"#get the predictions for the test data\npredicted_classes = model.predict_classes(X_val)\n#get the indices to be plotted\ny_true = np.argmax(y_val,axis=1)","metadata":{"_uuid":"dd52f4c515120a0c9aa2ecd4f1fd7cfaa71a08d0","execution":{"iopub.status.busy":"2023-12-26T17:48:09.112446Z","iopub.execute_input":"2023-12-26T17:48:09.112675Z","iopub.status.idle":"2023-12-26T17:48:32.725140Z","shell.execute_reply.started":"2023-12-26T17:48:09.112635Z","shell.execute_reply":"2023-12-26T17:48:32.724390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Мы создаем два индекса, правильный и неправильный, для изображений в наборе проверки с классом, предсказанным правильно и неправильно, соответственно.","metadata":{"_uuid":"431664690b241560041cec6e5c93ddb0b045d63f"}},{"cell_type":"code","source":"correct = np.nonzero(predicted_classes==y_true)[0]\nincorrect = np.nonzero(predicted_classes!=y_true)[0]","metadata":{"_uuid":"9da776ea97666c99a141cf26d2e64705cf5d9069","execution":{"iopub.status.busy":"2023-12-26T17:48:32.726249Z","iopub.execute_input":"2023-12-26T17:48:32.726475Z","iopub.status.idle":"2023-12-26T17:48:32.730417Z","shell.execute_reply.started":"2023-12-26T17:48:32.726436Z","shell.execute_reply":"2023-12-26T17:48:32.729597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Мы увидели, каково количество правильно и неправильно предсказанных значений в наборе проверки.\n\nЗдесь мы показываем отчет о классификации для набора проверки с точностью по классу и в целом.","metadata":{"_uuid":"6a1c361f6319484bc17f41ab71ecf1d07992dbe7"}},{"cell_type":"code","source":"target_names = [\"Class {}:\".format(i) for i in range(NUM_CLASSES)]\nprint(classification_report(y_true, predicted_classes, target_names=target_names))","metadata":{"_uuid":"3a92b2e2751942fd9fff4792ee932ee0d5f9bef2","execution":{"iopub.status.busy":"2023-12-26T17:48:32.731823Z","iopub.execute_input":"2023-12-26T17:48:32.732135Z","iopub.status.idle":"2023-12-26T17:48:32.757380Z","shell.execute_reply.started":"2023-12-26T17:48:32.732065Z","shell.execute_reply":"2023-12-26T17:48:32.756457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Подготовьте отправку\nДелаем тестовые изображения с предсказанным классом","metadata":{"_uuid":"14d8d48765b4c4fe17c25be6605164eac34df534","trusted":true}},{"cell_type":"code","source":"f, ax = plt.subplots(5,5, figsize=(15,15))\nfor i,data in enumerate(test[:25]):\n    img_num = data[1]\n    img_data = data[0]\n    orig = img_data\n    data = img_data.reshape(-1,IMG_SIZE,IMG_SIZE,3)\n    model_out = model.predict([data])[0]\n    \n    if np.argmax(model_out) == 1: \n        str_predicted='Dog'\n    else: \n        str_predicted='Cat'\n    ax[i//5, i%5].imshow(orig)\n    ax[i//5, i%5].axis('off')\n    ax[i//5, i%5].set_title(\"Predicted:{}\".format(str_predicted))    \nplt.show()","metadata":{"_uuid":"07e788faee58139d33db79be0093cdb0900d8073","execution":{"iopub.status.busy":"2023-12-26T17:48:32.758638Z","iopub.execute_input":"2023-12-26T17:48:32.758932Z","iopub.status.idle":"2023-12-26T17:48:34.423201Z","shell.execute_reply.started":"2023-12-26T17:48:32.758876Z","shell.execute_reply":"2023-12-26T17:48:34.421864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Прогнозирование тестовых данных","metadata":{"_uuid":"2e2199cdb3dbef1620298f0b9060908b7e2d4f90"}},{"cell_type":"code","source":"pred_list = []\nimg_list = []\nfor img in tqdm(test):\n    img_data = img[0]\n    img_idx = img[1]\n    data = img_data.reshape(-1,IMG_SIZE,IMG_SIZE,3)\n    predicted = model.predict([data])[0]\n    img_list.append(img_idx)\n    pred_list.append(predicted[1])","metadata":{"_uuid":"15afbef65cdfe94ffa3a2e63ed97f0fdd9a34d89","execution":{"iopub.status.busy":"2023-12-26T17:48:34.424380Z","iopub.execute_input":"2023-12-26T17:48:34.424613Z","iopub.status.idle":"2023-12-26T17:50:43.909637Z","shell.execute_reply.started":"2023-12-26T17:48:34.424566Z","shell.execute_reply":"2023-12-26T17:50:43.908819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Submit.file","metadata":{"_uuid":"a932e7efa19b93fc6a53d681ad7e195134acad17"}},{"cell_type":"code","source":"submission = pd.DataFrame({'id':img_list , 'label':pred_list})\nsubmission.head()\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"_uuid":"9bd2fc5c0e3722cbc44c0211512574b2ab0cd249","execution":{"iopub.status.busy":"2023-12-26T17:50:43.911158Z","iopub.execute_input":"2023-12-26T17:50:43.911496Z","iopub.status.idle":"2023-12-26T17:50:44.008731Z","shell.execute_reply.started":"2023-12-26T17:50:43.911433Z","shell.execute_reply":"2023-12-26T17:50:44.007794Z"},"trusted":true},"execution_count":null,"outputs":[]}]}