{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","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 the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":1,"outputs":[]},{"metadata":{"_cell_guid":"32e89bdd-a51a-49a0-be36-9b6e8f0bfd4e","_uuid":"def0e6f95ef0704ad8ae1bfcf7054feb9c8ba8e4","trusted":true},"cell_type":"code","source":"\nfrom distutils.version import LooseVersion\nimport warnings\nimport tensorflow as tf\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n    warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))","execution_count":2,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"trusted":true},"cell_type":"code","source":"from tqdm import tqdm\nimport numpy as np\nimport pandas as pd\nimport time\nimport matplotlib.pyplot as plt\nimport os\nimport cv2\nimport random","execution_count":3,"outputs":[]},{"metadata":{"_cell_guid":"e82126bb-c38d-446b-9f06-64df0167f484","_uuid":"ad70b083b1ad253d1903fd37bcbd73272c45af88","collapsed":true,"trusted":true},"cell_type":"code","source":"path_root = '../input'\npath_train = os.path.join(path_root, 'train')\npath_test = os.path.join(path_root, 'test')\npath_labels_csv = os.path.join(path_root, 'labels.csv')\npath_result_csv = os.path.join(path_root, 'sample_submission.csv')\n\nlen_train = len(os.listdir(path_train))\nlen_test = len(os.listdir(path_test))","execution_count":4,"outputs":[]},{"metadata":{"_cell_guid":"d254454c-171d-4245-8867-ba5666f799e6","_uuid":"4cb4f50ee569910ac29ddcf7ab8d7a0a835de5b8","trusted":true},"cell_type":"code","source":"labels = pd.read_csv(path_labels_csv)\nprint(labels.head(5))\n\nbreed = list(set(labels['breed']))\nn_classes = len(breed)\nprint(n_classes, len(os.listdir(path_train)))\n\nlabels.shape","execution_count":5,"outputs":[]},{"metadata":{"_cell_guid":"3e8e3c09-2f75-4d57-9f96-b62d9ff66fca","_uuid":"ba96ddfab7faee418adb061bd41b64350f6576a3","collapsed":true,"trusted":true},"cell_type":"code","source":"class_to_num = dict(zip(breed, range(n_classes)))\nnum_to_class = dict(zip(range(n_classes), breed))","execution_count":6,"outputs":[]},{"metadata":{"_cell_guid":"ccda6814-fade-4342-acbd-8d6f755a3cba","_uuid":"296a860e6c74dcdba16c8ed3f0d366dcdc34786b","trusted":true},"cell_type":"code","source":"width = 300\nX_train = np.zeros((len_train, width, width, 3), dtype = np.uint8)\ny_train = np.zeros((len_train, n_classes))\nn = len(labels)\n\nfor i in tqdm(range(n)):\n    X_train[i] = cv2.resize(cv2.imread(os.path.join(path_train, '%s.jpg' % labels['id'][i])), dsize = (width, width))\n    y_train[i][class_to_num[labels['breed'][i]]] = 1","execution_count":7,"outputs":[]},{"metadata":{"_cell_guid":"4a854221-e02b-4527-9b30-f9791deccb53","_uuid":"ea7dde08885c632d2301197cca2a3b94d675dcb4","collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"ed7261b8-73d7-468f-8f30-82b141378965","_uuid":"f4cbd01b379d4dffcb1bd2cd4d2c7021dbbc91ba","trusted":true},"cell_type":"code","source":"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nplt.figure(figsize = (15, 9))\nfor i in range(12):\n    index = random.randint(0, len_train - 1)\n    plt.subplot(3, 4, i + 1)\n    plt.imshow(X_train[index][:, :, ::-1])\n    plt.title(num_to_class[y_train[index].argmax()])","execution_count":8,"outputs":[]},{"metadata":{"_cell_guid":"98bc6bba-2ebd-4946-b0af-b7e596a3850e","_uuid":"21d100ea35d3edb72ab9069ebd582ec58fa8af41","trusted":true},"cell_type":"code","source":"from keras.models import *\nfrom keras.layers import *","execution_count":9,"outputs":[]},{"metadata":{"_cell_guid":"f295d628-35cd-4aca-bb09-861e4e06dc4b","_uuid":"b88574f12ba72d0508d10ef57401e7884b83c213","collapsed":true,"trusted":true},"cell_type":"code","source":"from keras.applications import resnet50\nfrom keras.preprocessing import image\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions","execution_count":10,"outputs":[]},{"metadata":{"_cell_guid":"2c2b2992-8045-4b33-b4e4-ed7553e0617a","_uuid":"8e4a746387168f284aead146ca71b7ee409f66b3","trusted":true},"cell_type":"code","source":"resnet_model = resnet50.ResNet50(include_top = False, weights='imagenet', input_shape = (300, 300, 3))\n    \ninputs = Input((width, width, 3))\nx = inputs\nx = resnet_model(x)\nx = GlobalAveragePooling2D()(x)\nresnet_model = Model(inputs, x)\n\nresnet_model.summary()","execution_count":11,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"7784c9e699cd5a6ae5158c1e2b4fea0aba08a2c5"},"cell_type":"code","source":"\nfeatures = resnet_model.predict(X_train, batch_size=64, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"529e083d-06b5-45d2-8801-811b951454df","_uuid":"0b207fd250b1051882cd6798d1415dbba0664fb6","trusted":true},"cell_type":"code","source":"inputs = Input(features.shape[1:])\nx = inputs\nx = Dropout(0.5)(x)\nx = Dense(n_classes, activation='softmax')(x)\nmodel = Model(inputs, x)\nmodel.compile(optimizer='adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\nmodel.summary()","execution_count":12,"outputs":[]},{"metadata":{"collapsed":true,"_cell_guid":"785eaba1-6d26-4603-b0c9-5d87614a5a68","_uuid":"8db969cdc34a41bf5583e3cfeb4d02ad43a8606b","trusted":false},"cell_type":"code","source":"\nh = model.fit(features, y_train, batch_size=128, epochs=10, validation_split=0.1)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"9144213b-fb3f-4c7e-b4ab-05b37c88e35a","_uuid":"ff4a8f569632678d0433671e590823c082c4fee4","collapsed":true,"trusted":false},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nplt.figure(figsize=(10, 4))\nplt.subplot(1, 2, 1)\nplt.plot(h.history['loss'])\nplt.plot(h.history['val_loss'])\nplt.legend(['loss', 'val_loss'])\nplt.ylabel('loss')\nplt.xlabel('epoch')\n\nplt.subplot(1, 2, 2)\nplt.plot(h.history['acc'])\nplt.plot(h.history['val_acc'])\nplt.legend(['acc', 'val_acc'])\nplt.ylabel('acc')\nplt.xlabel('epoch')","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"236997d8-ccf1-4540-ba74-69c231c400e3","_uuid":"562abf0da83987914a4b72bf1f932103144c0fb5","collapsed":true,"trusted":false},"cell_type":"code","source":"test_data = pd.read_csv(path_result_csv)\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"69774e0b-c4fa-46ea-8fd8-7189bd55c2b3","_uuid":"ad0940ff56697a7dcb39fe5d463f6cee81f45baf","collapsed":true,"trusted":false},"cell_type":"code","source":"n_test = len(test_data)\nX_test = np.zeros((len_test, width, width, 3), dtype=np.uint8)\nfor i in tqdm(range(len_test)):\n    X_test[i] = cv2.resize(cv2.imread(os.path.join(path_test, '%s.jpg' % test_data['id'][i])), (width, width))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"ede7b8c18a5ebabd97a7c43382011f71d5454551"},"cell_type":"code","source":"features_test = resnet_model.predict(X_test, batch_size=64, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"5212d664-ef5a-433a-a8e0-19d450c1c48e","_uuid":"5cb2bb995afc9e7f41468e7639819726009d86d7","collapsed":true,"trusted":false},"cell_type":"code","source":"y_pred = model.predict(features_test, batch_size=128)\n\nfor b in breed:\n    test_data[b] = y_pred[:,class_to_num[b]]\n    \ntest_data.to_csv('pred.csv', index=None)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"8d40874e-0a6f-4def-9eee-e990987f4a42","_uuid":"493f87c6dc83ec3e411d990ed050e2ed721d68fc","collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}