{"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_minor":4,"nbformat":4,"cells":[{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train/cat.10192.jpg ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip -q -o '/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip'\n!unzip -q -o '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\n\nImage.open('train/cat.10192.jpg')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import glob\n\n# glob.glob('train/*')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.DataFrame({'path' : glob.glob('train/*')})\ntrain","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"a = train['path'].apply(lambda x: x.split('/')[1])\na","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train['target'] = train['path'].apply(lambda x: x.split('/')[1].split('.')[0])\ntrain\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nx_train, x_valid = train_test_split(train, test_size = 0.2, random_state = 42, stratify = train['target'] )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_valid['target'].value_counts()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train['target'].value_counts()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\n\nidg = ImageDataGenerator()\nidg2 = ImageDataGenerator(horizontal_flip = True, vertical_flip = True, brightness_range = [0.2, 1.0] )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = idg2.flow_from_dataframe(x_train, x_col = 'path', y_col = 'target', target_size = (100,100))\nvalid_generator = idg.flow_from_dataframe(x_valid, x_col = 'path', y_col = 'target', target_size = (100,100))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n\nplt.figure(figsize = (12,12))\nfor i in range(0,15):\n    plt.subplot(5,3,i+1)\n    for x, y in train_generator:\n        image = x[0]\n        plt.imshow(image.astype('uint8'))\n        break\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n\nplt.figure(figsize = (12,12))\nfor i in range(0,15):\n    plt.subplot(5,3,i+1)\n    for x, y in valid_generator:\n        image = x[0]\n        plt.imshow(image.astype('uint8'))\n        break\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import Sequential\n\nfrom tensorflow.keras.layers import *\n\nfrom tensorflow.keras.applications import EfficientNetB1","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eb0 = EfficientNetB1(include_top = False, pooling = 'avg')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(eb0)\nmodel.add(Dense(2, activation = 'softmax'))\n\nfrom tensorflow.keras.optimizers import SGD\n\nmodel.compile(metrics = ['acc'], loss = 'categorical_crossentropy', optimizer = SGD(momentum = 0.9, nesterov = True, lr = 0.01))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_generator, epochs = 5, validation_data = valid_generator )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test  = pd.DataFrame({'path' : glob.glob('test/*')})\n\ntest_generator = idg.flow_from_dataframe(test, x_col = 'path', y_col = None, class_mode = None,target_size = (100,100), shuffle = False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result = model.predict(test_generator, verbose = 1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import load_img\n\n\nn = 10\nfor i, (index, row) in enumerate(test.iterrows()):\n    if i >= n:\n        break\n    fig = plt.figure(figsize=(8, 32))\n    img = load_img(row['path'], target_size=(300, 300))\n    subfig = fig.add_subplot(n, 1, i + 1)\n    pred = result[i][0]\n    pred_label = 'cat' if pred > 0.5 else 'dog'\n    pred = pred if pred > 0.5 else 1-pred\n    plt.title('Looks like a {0} with probability {1}'.format(pred_label, pred))\n    f = plt.imshow(img)\n    f.axes.get_xaxis().set_visible(False)\n    f.axes.get_yaxis().set_visible(False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv')\nsub","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['id'] = test['path'].apply(lambda x : x.split('/')[1].split('.')[0])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['label'] = result[:,1].clip(0.001, 0.999)\nsub","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.to_csv('sub_0518.csv', index= 0 )","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}