{"cells":[{"metadata":{},"cell_type":"markdown","source":"Model olarak model1i kullanacağım. Diğer iki modeli görmezden gelebilirsiniz."},{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","colab":{},"colab_type":"code","id":"uQpk4CE6fJE_","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":989,"status":"ok","timestamp":1575301625125,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"Cn4wiHA56s0B","outputId":"6bbe3716-35f5-461d-c760-dcc24620fdfb","trusted":true},"cell_type":"code","source":"import os\n\nurl = \"../input/dogs-vs-cats-redux-kernels-edition/\"\nprint(os.listdir(url +\"\"))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","colab":{"base_uri":"https://localhost:8080/","height":80},"colab_type":"code","executionInfo":{"elapsed":4449,"status":"ok","timestamp":1575301654305,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"isrKS5vyfJFE","outputId":"80f52090-9f39-4bc9-9116-f04c0846fe15","trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":544},"colab_type":"code","executionInfo":{"elapsed":4310,"status":"ok","timestamp":1575301654821,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"dh3uLw85N8bV","outputId":"ca6aa561-c979-4c19-a929-bb19ab05a1f7","trusted":true},"cell_type":"code","source":"from tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"VxYOx_s4fJFI","trusted":true},"cell_type":"code","source":"FAST_RUN = False\nwidth = 128\nheight = 128\nsize = (width,height)\nimg_channels = 3","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"OaA6WEfVfJFL","trusted":true},"cell_type":"code","source":"filenames = os.listdir(url + \"train/train/\")\ncategories = []\nfor filename in filenames:\n    cate = filename.split('.')[0]\n    categories.append(int(cate=='dog'))\ndf = pd.DataFrame({\n    'filename':filenames,\n    'category':categories\n})","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":204},"colab_type":"code","executionInfo":{"elapsed":54328,"status":"ok","timestamp":1575301716333,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"GxhonaG2fJFN","outputId":"c3e342fa-3aca-4c04-da7c-e5a275e97db9","trusted":true},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":204},"colab_type":"code","executionInfo":{"elapsed":53564,"status":"ok","timestamp":1575301716337,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"oNtvXWcpfJFQ","outputId":"6064b690-d2f5-4f25-bb3c-84c2b5366b56","trusted":true},"cell_type":"code","source":"df.tail()","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":279},"colab_type":"code","executionInfo":{"elapsed":26332,"status":"ok","timestamp":1575301716338,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"M1koiTSYfJFS","outputId":"cb239925-7434-4875-a77d-d237398dbdb8","trusted":true},"cell_type":"code","source":"df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"VLjIYPuwfJFX","trusted":true},"cell_type":"code","source":"import keras\nfrom keras.layers import Dense,GlobalAveragePooling2D, BatchNormalization,Dropout\nfrom keras.applications import inception_resnet_v2,inception_v3\nfrom keras.preprocessing import image\nfrom keras.applications import MobileNet\nfrom keras.applications.mobilenet import preprocess_input\nfrom keras.models import Model\nfrom keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":286},"colab_type":"code","executionInfo":{"elapsed":2872,"status":"ok","timestamp":1575301739359,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"peHo4eI2Af5_","outputId":"2e560c19-1235-415e-f28d-2bba27e20eae","trusted":true},"cell_type":"code","source":"sample = random.choice(filenames)\nimage=load_img(url + \"train/train/\"+sample)\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":615},"colab_type":"code","executionInfo":{"elapsed":86652,"status":"ok","timestamp":1575301830811,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"UN8sh3e6AoFH","outputId":"6b55a5a8-a6d8-4493-e518-07854b4f718d","trusted":true},"cell_type":"code","source":"mode_1 = MobileNet(weights = 'imagenet', include_top = False, input_shape = (width, height, 3))\nmode_2 = inception_resnet_v2.InceptionResNetV2(weights = 'imagenet',include_top = False,input_shape = (width, height, 3))\nmode_3 = inception_v3.InceptionV3(weights = 'imagenet',include_top=False , input_shape = (width, height, 3))\n\nx_1 = mode_1.output\nx_2 = mode_2.output\nx_3 = mode_3.output\n\nx_1 = GlobalAveragePooling2D()(x_1)\nx_2 = GlobalAveragePooling2D()(x_2)\nx_3 = GlobalAveragePooling2D()(x_3)","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"Qcn1cIqtDNN3","trusted":true},"cell_type":"code","source":"x_1 = Dense(256,activation='relu')(x_1)\nx_2 = Dense(256,activation='relu')(x_2)\nx_3 = Dense(256,activation='relu')(x_3)\n\nx_1 = BatchNormalization()(x_1)\nx_2 = BatchNormalization()(x_2)\nx_3 = BatchNormalization()(x_3)\n\nx_1 = Dropout(0.20)(x_1)\nx_2 = Dropout(0.20)(x_2)\nx_3 = Dropout(0.20)(x_3)\n\npreds_1 = Dense(2,activation='softmax')(x_1)\npreds_2 = Dense(2,activation='softmax')(x_2)\npreds_3 = Dense(2,activation='softmax')(x_3)","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"fE9pYClVDy24","trusted":true},"cell_type":"code","source":"model_1 = Model(inputs = mode_1.input,outputs = preds_1)\nmodel_2 = Model(inputs = mode_2.input,outputs = preds_2)\nmodel_3 = Model(inputs = mode_3.input,outputs = preds_3)","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":1000},"colab_type":"code","executionInfo":{"elapsed":1561,"status":"ok","timestamp":1575301929641,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"f3fRsxMVGfp8","outputId":"c51e919b-0368-4fd5-dc5e-ff4d27a8834e"},"cell_type":"markdown","source":"for i,layer in enumerate(model_1.layers):\n  print(i,layer.name)"},{"metadata":{"colab":{},"colab_type":"code","id":"7g1FXfJnHBmI","trusted":true},"cell_type":"code","source":"for layer in model_1.layers:\n  layer.trainable = False\nfor layer in model_1.layers[87:]:\n  layer.trainable = True","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":1000},"colab_type":"code","executionInfo":{"elapsed":1628,"status":"ok","timestamp":1575301935640,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"56CTKxPMGy0F","outputId":"7ad416d3-45b5-4110-f084-2c302c2f91b3"},"cell_type":"markdown","source":"for i,layer in enumerate(model_2.layers):\n  print(i,layer.name)"},{"metadata":{"colab":{},"colab_type":"code","id":"7-2lVNrQHdhs","trusted":true},"cell_type":"code","source":"for layer in model_2.layers:\n  layer.trainable = False\nfor layer in model_2.layers[780:]:\n  layer.trainable = True","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":1000},"colab_type":"code","executionInfo":{"elapsed":1538,"status":"ok","timestamp":1575301941134,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"hjJeTYLtGymM","outputId":"24cab7cf-2f05-499e-a910-f2d043829e37"},"cell_type":"markdown","source":"for i,layer in enumerate(model_3.layers):\n  print(i,layer.name)"},{"metadata":{"colab":{},"colab_type":"code","id":"C1ytzlu-HiTV","trusted":true},"cell_type":"code","source":"for layer in model_3.layers:\n  layer.trainable = False\nfor layer in model_3.layers[311:]:\n  layer.trainable = True","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":105},"colab_type":"code","executionInfo":{"elapsed":1123,"status":"ok","timestamp":1575302104902,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"kT00c12ZfJFa","outputId":"8c61ad0a-32fb-4aa4-d265-997f00cb6a7b","trusted":true},"cell_type":"code","source":"model_1.compile(optimizer = 'Adam',loss = 'categorical_crossentropy',metrics=['accuracy'])\nmodel_2.compile(optimizer = 'Adam',loss = 'categorical_crossentropy',metrics=['accuracy'])\nmodel_3.compile(optimizer = 'Adam',loss = 'categorical_crossentropy',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"1oqgD9aEfJFc","trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping,ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"H2SOa50VfJFe","trusted":true},"cell_type":"code","source":"earlystop=EarlyStopping(patience=10)","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"HqPJ6kAxfJFh","trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',\n                                            patience=2,\n                                            verbose=1,\n                                            factor=0.5,\n                                            min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"eN2s9VcvfJFj","trusted":true},"cell_type":"code","source":"callbacks= [earlystop,learning_rate_reduction]","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"Z2vxD7T6fJFl","trusted":true},"cell_type":"code","source":"df[\"category\"] = df[\"category\"].replace({0:'cat',1:'dog'})","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"FxF3B6UdfJFn","trusted":true},"cell_type":"code","source":"train_df,validate_df = train_test_split(df,test_size=0.2, random_state=42)\ntrain_df = train_df.reset_index(drop=True) #drops dog.blahblah from dataset\nvalidate_df=validate_df.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":291},"colab_type":"code","executionInfo":{"elapsed":1585,"status":"ok","timestamp":1575302128830,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"J76Ov4aYfJFq","outputId":"7873caaa-b79e-42c8-f22c-81288575a8d4","trusted":true},"cell_type":"code","source":"train_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":291},"colab_type":"code","executionInfo":{"elapsed":1884,"status":"ok","timestamp":1575302129515,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"BVNISoiGfJFs","outputId":"46263083-ef69-4573-fd17-f35c0b4873b4","trusted":true},"cell_type":"code","source":"validate_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"lJzqueTAfJFu","trusted":true},"cell_type":"code","source":"total_train = train_df.shape[0]\ntotal_validate = validate_df.shape[0]\nbatch_size = 15","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":36099,"status":"ok","timestamp":1575302282155,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"FxaacybmfJFx","outputId":"236e497c-8ac1-4533-e3d4-ef3c0d660ff8","trusted":true},"cell_type":"code","source":"train_datagen=ImageDataGenerator(\n    rotation_range=15,\n    rescale=1./255,\n    shear_range=0.1,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\ntrain_generator=train_datagen.flow_from_dataframe(\n    train_df,\n    url+\"train/train/\",\n    x_col='filename',\n    y_col=\"category\",\n    target_size=size,\n    class_mode='categorical',\n    batch_size=batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"colab_type":"text","id":"ibTpytOtfJF1"},"cell_type":"markdown","source":"Validation Generator"},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":43524,"status":"ok","timestamp":1575302291046,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"ksbSeEd0fJF2","outputId":"b8faa983-329a-49b1-e645-aa58b354fd01","trusted":true},"cell_type":"code","source":"validation_datagen = ImageDataGenerator(rescale=1./255)\nvalidation_generator = validation_datagen.flow_from_dataframe(\n    validate_df,\n    url+\"train/train/\",\n    x_col='filename', \n    y_col='category',\n    target_size=size,\n    class_mode='categorical',\n    batch_size=batch_size\n)","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":34},"colab_type":"code","executionInfo":{"elapsed":42737,"status":"ok","timestamp":1575302291048,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"AWsg9uekfJF6","outputId":"5b20dbb9-9836-4293-cc1c-19ab12000165","trusted":true},"cell_type":"code","source":"example_df = train_df.sample(n=1).reset_index(drop=True)\nexample_generator = train_datagen.flow_from_dataframe(\n    example_df,\n    url+\"train/train/\",\n    x_col='filename',\n    y_col='category',\n    target_size=size,\n    class_mode='categorical'\n)","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":873},"colab_type":"code","executionInfo":{"elapsed":47519,"status":"ok","timestamp":1575302296693,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"Vaj5pVp7fJF9","outputId":"bced0887-8e6e-4379-ad36-e2927d39da88","trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12,12))\nfor i in range(0,15):\n    plt.subplot(5,3,i+1)\n    for X_batch,Y_batch in example_generator:\n        image=X_batch[0]\n        plt.imshow(image)\n        break\nplt.tight_layout()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":544},"colab_type":"code","executionInfo":{"elapsed":2236,"status":"ok","timestamp":1575302302899,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"vUuJVWKZkYAl","outputId":"2ff526f9-4d19-472d-82ae-fd08bd67b4f7","trusted":true},"cell_type":"code","source":"print(device_lib.list_local_devices())","execution_count":null,"outputs":[]},{"metadata":{"colab_type":"text","id":"wHzTqLywfJGA"},"cell_type":"markdown","source":"Fit Model"},{"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":392},"colab_type":"code","executionInfo":{"elapsed":31760,"status":"error","timestamp":1575302338610,"user":{"displayName":"Ahmet Burkay KINIK","photoUrl":"","userId":"02453636707183305587"},"user_tz":-180},"id":"imlq5xIifJGA","outputId":"a6d8adbe-b802-417c-cd1f-704e63570b43","trusted":true},"cell_type":"code","source":"FAST_RUN = False\nepochs=3 if FAST_RUN else 12\nhistory_1 = model_1.fit_generator(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n    callbacks=callbacks\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_1.save_weights(\"w1.h5\")\nmodel_1.save('m1.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_2 = model_2.fit_generator(\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n    callbacks=callbacks\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_2.save_weights(\"w2.h5\")\nmodel_2.save('m2.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_3 = model_3.fit_generator(\n\n\n    train_generator,\n    epochs=epochs,\n    validation_data=validation_generator,\n    validation_steps=total_validate//batch_size,\n    steps_per_epoch=total_train//batch_size,\n    callbacks=callbacks\n)","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"NHyJYjXgfJGD","trusted":true},"cell_type":"code","source":"model_3.save_weights(\"w3.h5\")\nmodel_3.save('m3.h5')","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"a0VKZn7QfJGF","trusted":true},"cell_type":"code","source":"history = history_1\nfig,(ax1,ax2) = plt.subplots(2,1,figsize=(12,12))\nax1.plot(history.history['loss'],color='b',label='Training Loss')\nax1.plot(history.history['val_loss'],color='r',label='Validation Loss')\nax1.set_xticks(np.arange(1,epochs,1))\nax1.set_yticks(np.arange(0,1,0.1))\n\nax2.plot(history.history['accuracy'],color='b',label='Training Accuracy')\nax2.plot(history.history['val_accuracy'],color='r',label='Validation Accuracy')\nax2.set_xticks(np.arange(1,epochs,1))\n\nlegend = plt.legend(loc='best',shadow=True)\nplt.tight_layout()\nplt.savefig('p1.png')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = history_2\nfig,(ax1,ax2) = plt.subplots(2,1,figsize=(12,12))\nax1.plot(history.history['loss'],color='b',label='Training Loss')\nax1.plot(history.history['val_loss'],color='r',label='Validation Loss')\nax1.set_xticks(np.arange(1,epochs,1))\nax1.set_yticks(np.arange(0,1,0.1))\n\nax2.plot(history.history['accuracy'],color='b',label='Training Accuracy')\nax2.plot(history.history['val_accuracy'],color='r',label='Validation Accuracy')\nax2.set_xticks(np.arange(1,epochs,1))\n\nlegend = plt.legend(loc='best',shadow=True)\nplt.tight_layout()\nplt.savefig('p2.png')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = history_3\nfig,(ax1,ax2) = plt.subplots(2,1,figsize=(12,12))\nax1.plot(history.history['loss'],color='b',label='Training Loss')\nax1.plot(history.history['val_loss'],color='r',label='Validation Loss')\nax1.set_xticks(np.arange(1,epochs,1))\nax1.set_yticks(np.arange(0,1,0.1))\n\nax2.plot(history.history['accuracy'],color='b',label='Training Accuracy')\nax2.plot(history.history['val_accuracy'],color='r',label='Validation Accuracy')\nax2.set_xticks(np.arange(1,epochs,1))\n\nlegend = plt.legend(loc='best',shadow=True)\nplt.tight_layout()\nplt.savefig('p3.png')","execution_count":null,"outputs":[]},{"metadata":{"colab_type":"text","id":"UQac_d7XfJGH"},"cell_type":"markdown","source":"Testing data preperation"},{"metadata":{"colab":{},"colab_type":"code","id":"Q5jShMdEfJGI","trusted":true},"cell_type":"code","source":"test_filenames = os.listdir(url+\"test/test/\")\ntest_df = pd.DataFrame({\n    'filename' : test_filenames\n})\nnb_samples = test_df.shape[0]\n","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"YqLcfXXufJGL","outputId":"d2755c49-54b3-448c-88fc-b1a1a8d7910b","trusted":true},"cell_type":"code","source":"test_gen = ImageDataGenerator(rescale=1./255)\ntest_generator = test_gen.flow_from_dataframe(\n    test_df,\n    url+\"test/test/\",\n    x_col = 'filename',\n    y_col = None,\n    class_mode=None,\n    target_size=size,\n    batch_size=batch_size,\n    shuffle=False\n)","execution_count":null,"outputs":[]},{"metadata":{"colab":{},"colab_type":"code","id":"mveA0a7OfJGN"},"cell_type":"markdown","source":"model_1.load_weights('../input/models/model_1.h5')\nmodel_2.load_weights('../input/models/model_2.h5')\nmodel_3.load_weights('../input/models/model_3.h5')"},{"metadata":{"trusted":true},"cell_type":"code","source":"predict_1 = model_1.predict_generator(test_generator,steps = np.ceil(nb_samples/batch_size))\npredict_2 = model_2.predict_generator(test_generator,steps = np.ceil(nb_samples/batch_size))\npredict_3 = model_3.predict_generator(test_generator,steps = np.ceil(nb_samples/batch_size))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = np.argmax(predict_1,axis=-1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = test_df['category'].replace({'dog' : 1, 'cat' : 0})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'].value_counts().plot.bar()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename','category'],axis = 1, inplace=True)\nsubmission_df.to_csv('submitthis1.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = np.argmax(predict_2,axis=-1)\nlabel_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)\ntest_df['category'] = test_df['category'].replace({'dog' : 1, 'cat' : 0})\n\nsubmission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename','category'],axis = 1, inplace=True)\nsubmission_df.to_csv('submitthis2.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['category'] = np.argmax(predict_3,axis=-1)\nlabel_map = dict((v,k) for k,v in train_generator.class_indices.items())\ntest_df['category'] = test_df['category'].replace(label_map)\ntest_df['category'] = test_df['category'].replace({'dog' : 1, 'cat' : 0})\n\nsubmission_df = test_df.copy()\nsubmission_df['id'] = submission_df['filename'].str.split('.').str[0]\nsubmission_df['label'] = submission_df['category']\nsubmission_df.drop(['filename','category'],axis = 1, inplace=True)\nsubmission_df.to_csv('submitthis3.csv',index=False)","execution_count":null,"outputs":[]}],"metadata":{"accelerator":"GPU","colab":{"collapsed_sections":[],"name":"trainedlkernel.ipynb","provenance":[]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"}},"nbformat":4,"nbformat_minor":1}