{"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","execution":{"iopub.status.busy":"2021-12-04T05:14:37.869696Z","iopub.execute_input":"2021-12-04T05:14:37.870183Z","iopub.status.idle":"2021-12-04T05:14:37.885160Z","shell.execute_reply.started":"2021-12-04T05:14:37.870140Z","shell.execute_reply":"2021-12-04T05:14:37.884356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip -q -o '/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip'","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:37.887451Z","iopub.execute_input":"2021-12-04T05:14:37.887725Z","iopub.status.idle":"2021-12-04T05:14:45.027016Z","shell.execute_reply.started":"2021-12-04T05:14:37.887689Z","shell.execute_reply":"2021-12-04T05:14:45.026047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip -q -o '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:45.030477Z","iopub.execute_input":"2021-12-04T05:14:45.030778Z","iopub.status.idle":"2021-12-04T05:14:48.810082Z","shell.execute_reply.started":"2021-12-04T05:14:45.030739Z","shell.execute_reply":"2021-12-04T05:14:48.809155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# test/10007.jpg\n# train/cat.4511.jpg","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:48.811735Z","iopub.execute_input":"2021-12-04T05:14:48.812015Z","iopub.status.idle":"2021-12-04T05:14:48.819823Z","shell.execute_reply.started":"2021-12-04T05:14:48.811978Z","shell.execute_reply":"2021-12-04T05:14:48.816533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image\n\nImage.open('train/cat.4511.jpg')","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:48.822999Z","iopub.execute_input":"2021-12-04T05:14:48.823365Z","iopub.status.idle":"2021-12-04T05:14:48.866206Z","shell.execute_reply.started":"2021-12-04T05:14:48.823335Z","shell.execute_reply":"2021-12-04T05:14:48.865564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import glob\n\ntrain = pd.DataFrame({'path' : glob.glob('train/*')})\ntrain.head(2)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:48.867415Z","iopub.execute_input":"2021-12-04T05:14:48.867962Z","iopub.status.idle":"2021-12-04T05:14:48.965957Z","shell.execute_reply.started":"2021-12-04T05:14:48.867928Z","shell.execute_reply":"2021-12-04T05:14:48.964567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train['target'] = train['path'].apply(lambda x: x.split('/')[1].split('.')[0])\ntrain","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:48.968691Z","iopub.execute_input":"2021-12-04T05:14:48.972399Z","iopub.status.idle":"2021-12-04T05:14:49.026558Z","shell.execute_reply.started":"2021-12-04T05:14:48.972363Z","shell.execute_reply":"2021-12-04T05:14:49.025241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:49.028636Z","iopub.execute_input":"2021-12-04T05:14:49.029549Z","iopub.status.idle":"2021-12-04T05:14:49.047662Z","shell.execute_reply.started":"2021-12-04T05:14:49.029511Z","shell.execute_reply":"2021-12-04T05:14:49.046727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1. 점수 올리기 -> data augmentation","metadata":{}},{"cell_type":"code","source":"idg = ImageDataGenerator()\nidg2 = ImageDataGenerator(horizontal_flip = True, brightness_range = [0.2,1.0])","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:49.050145Z","iopub.execute_input":"2021-12-04T05:14:49.050960Z","iopub.status.idle":"2021-12-04T05:14:49.072371Z","shell.execute_reply.started":"2021-12-04T05:14:49.050921Z","shell.execute_reply":"2021-12-04T05:14:49.071116Z"},"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, \n                                   stratify = train['target'])","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:49.076102Z","iopub.execute_input":"2021-12-04T05:14:49.078387Z","iopub.status.idle":"2021-12-04T05:14:49.174483Z","shell.execute_reply.started":"2021-12-04T05:14:49.078343Z","shell.execute_reply":"2021-12-04T05:14:49.172202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_valid['target'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:49.177031Z","iopub.execute_input":"2021-12-04T05:14:49.177544Z","iopub.status.idle":"2021-12-04T05:14:49.192964Z","shell.execute_reply.started":"2021-12-04T05:14:49.177489Z","shell.execute_reply":"2021-12-04T05:14:49.191750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train['target'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:49.195552Z","iopub.execute_input":"2021-12-04T05:14:49.196500Z","iopub.status.idle":"2021-12-04T05:14:49.220410Z","shell.execute_reply.started":"2021-12-04T05:14:49.196198Z","shell.execute_reply":"2021-12-04T05:14:49.219605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_generator = idg2.flow_from_dataframe(x_train, x_col = 'path', y_col = 'target',\n                                         target_size = (300,300))","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:49.224133Z","iopub.execute_input":"2021-12-04T05:14:49.229015Z","iopub.status.idle":"2021-12-04T05:14:49.550743Z","shell.execute_reply.started":"2021-12-04T05:14:49.228966Z","shell.execute_reply":"2021-12-04T05:14:49.549928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"valid_generator = idg.flow_from_dataframe(x_valid, x_col = 'path', y_col = 'target',\n                                         target_size = (300,300))","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:49.554205Z","iopub.execute_input":"2021-12-04T05:14:49.554663Z","iopub.status.idle":"2021-12-04T05:14:49.661420Z","shell.execute_reply.started":"2021-12-04T05:14:49.554621Z","shell.execute_reply":"2021-12-04T05:14:49.660619Z"},"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\n# plt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:49.663031Z","iopub.execute_input":"2021-12-04T05:14:49.663892Z","iopub.status.idle":"2021-12-04T05:14:53.819412Z","shell.execute_reply.started":"2021-12-04T05:14:49.663835Z","shell.execute_reply":"2021-12-04T05:14:53.818772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. 점수올리기 --> 모델을 B0 -> B1","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras import Sequential\n\nfrom tensorflow.keras.layers import *\n\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.applications import EfficientNetB1","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:53.820581Z","iopub.execute_input":"2021-12-04T05:14:53.821368Z","iopub.status.idle":"2021-12-04T05:14:53.826403Z","shell.execute_reply.started":"2021-12-04T05:14:53.821327Z","shell.execute_reply":"2021-12-04T05:14:53.825687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"eb0 = EfficientNetB0(include_top = False, pooling = 'avg')\neb1 = EfficientNetB1(include_top = False, pooling = 'avg')","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:53.827877Z","iopub.execute_input":"2021-12-04T05:14:53.828676Z","iopub.status.idle":"2021-12-04T05:14:58.151199Z","shell.execute_reply.started":"2021-12-04T05:14:53.828639Z","shell.execute_reply":"2021-12-04T05:14:58.150353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(eb1)\nmodel.add(Dense(2, activation = 'softmax'))\n\nfrom tensorflow.keras.optimizers import SGD\n\nmodel.compile(metrics = ['acc'], loss = 'categorical_crossentropy',\n             optimizer = SGD(momentum = 0.9 , nesterov = True, lr = 0.01))","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:58.152602Z","iopub.execute_input":"2021-12-04T05:14:58.153170Z","iopub.status.idle":"2021-12-04T05:14:58.994153Z","shell.execute_reply.started":"2021-12-04T05:14:58.153124Z","shell.execute_reply":"2021-12-04T05:14:58.993345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:58.995503Z","iopub.execute_input":"2021-12-04T05:14:58.995949Z","iopub.status.idle":"2021-12-04T05:14:59.023357Z","shell.execute_reply.started":"2021-12-04T05:14:58.995910Z","shell.execute_reply":"2021-12-04T05:14:59.022527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3. 점수올리기-  callback 함수 추가","metadata":{}},{"cell_type":"code","source":"##callback\n\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n\nes = EarlyStopping(patience = 5, verbose = 1)\n\nmc = ModelCheckpoint('best.h5', save_best_only = True, verbose = 1)\n\nrl = ReduceLROnPlateau(patience = 3, verbose = 1)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:59.024700Z","iopub.execute_input":"2021-12-04T05:14:59.024974Z","iopub.status.idle":"2021-12-04T05:14:59.108537Z","shell.execute_reply.started":"2021-12-04T05:14:59.024939Z","shell.execute_reply":"2021-12-04T05:14:59.107539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_generator, epochs = 100, callbacks = [es, mc, rl], validation_data = valid_generator)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T05:14:59.110098Z","iopub.execute_input":"2021-12-04T05:14:59.110797Z","iopub.status.idle":"2021-12-04T06:25:08.905332Z","shell.execute_reply.started":"2021-12-04T05:14:59.110755Z","shell.execute_reply":"2021-12-04T06:25:08.903861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.DataFrame({'path' : glob.glob('test/*')})","metadata":{"execution":{"iopub.status.busy":"2021-12-04T06:25:12.014712Z","iopub.execute_input":"2021-12-04T06:25:12.015288Z","iopub.status.idle":"2021-12-04T06:25:12.062837Z","shell.execute_reply.started":"2021-12-04T06:25:12.015249Z","shell.execute_reply":"2021-12-04T06:25:12.061994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_generator = idg.flow_from_dataframe(test, x_col = 'path', y_col = None,\n                                        class_mode = None, target_size = (300,300),\n                                        shuffle = False)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T06:25:12.239454Z","iopub.execute_input":"2021-12-04T06:25:12.240038Z","iopub.status.idle":"2021-12-04T06:25:12.341577Z","shell.execute_reply.started":"2021-12-04T06:25:12.240003Z","shell.execute_reply":"2021-12-04T06:25:12.340801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result  = model.predict(test_generator, verbose=  1)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T06:25:12.464442Z","iopub.execute_input":"2021-12-04T06:25:12.465163Z","iopub.status.idle":"2021-12-04T06:26:14.893134Z","shell.execute_reply.started":"2021-12-04T06:25:12.465124Z","shell.execute_reply":"2021-12-04T06:26:14.892424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result","metadata":{"execution":{"iopub.status.busy":"2021-12-04T06:26:14.895057Z","iopub.execute_input":"2021-12-04T06:26:14.895301Z","iopub.status.idle":"2021-12-04T06:26:14.900921Z","shell.execute_reply.started":"2021-12-04T06:26:14.895267Z","shell.execute_reply":"2021-12-04T06:26:14.899892Z"},"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=(100, 100))\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":{"execution":{"iopub.status.busy":"2021-12-04T06:26:14.902214Z","iopub.execute_input":"2021-12-04T06:26:14.902709Z","iopub.status.idle":"2021-12-04T06:26:16.037234Z","shell.execute_reply.started":"2021-12-04T06:26:14.902673Z","shell.execute_reply":"2021-12-04T06:26:16.036587Z"},"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":{"execution":{"iopub.status.busy":"2021-12-04T06:26:16.039075Z","iopub.execute_input":"2021-12-04T06:26:16.039734Z","iopub.status.idle":"2021-12-04T06:26:16.068562Z","shell.execute_reply.started":"2021-12-04T06:26:16.039694Z","shell.execute_reply":"2021-12-04T06:26:16.067900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['id'] = test['path'].apply(lambda x : x.split('/')[1].split('.')[0] )","metadata":{"execution":{"iopub.status.busy":"2021-12-04T06:26:16.072637Z","iopub.execute_input":"2021-12-04T06:26:16.074898Z","iopub.status.idle":"2021-12-04T06:26:16.095152Z","shell.execute_reply.started":"2021-12-04T06:26:16.074840Z","shell.execute_reply":"2021-12-04T06:26:16.094473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub['label'] = result[:,1].clip(0.005, 0.995)\nsub","metadata":{"execution":{"iopub.status.busy":"2021-12-04T06:26:16.096558Z","iopub.execute_input":"2021-12-04T06:26:16.097202Z","iopub.status.idle":"2021-12-04T06:26:16.111976Z","shell.execute_reply.started":"2021-12-04T06:26:16.097160Z","shell.execute_reply":"2021-12-04T06:26:16.111148Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub.to_csv('base.csv', index = 0)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T06:26:16.113363Z","iopub.execute_input":"2021-12-04T06:26:16.113695Z","iopub.status.idle":"2021-12-04T06:26:16.148831Z","shell.execute_reply.started":"2021-12-04T06:26:16.113574Z","shell.execute_reply":"2021-12-04T06:26:16.148229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 4. 점수올리기 - Ensemble (Blending, Stacking..) Blending","metadata":{}},{"cell_type":"code","source":"# csv1 = pd.read_csv('/kaggle/input/ensemble/DogVsCats_submission (7).csv')\n# csv2 = pd.read_csv('/kaggle/input/ensemble/DogVsCats_submission (1) (3).csv')\n\n# csv1 = csv1.sort_values('id').reset_index(drop = True)\n# csv2 = csv2.sort_values('id').reset_index(drop = True)\n\n# sub = pd.read_csv('/kaggle/input/dogs-vs-cats-redux-kernels-edition/sample_submission.csv')\n# sub['label'] = (csv1['label'] * 0.5) + (csv2['label'] *0.5)\n# sub.to_csv('sub1.csv', index = 0)","metadata":{"execution":{"iopub.status.busy":"2021-12-04T06:26:16.150045Z","iopub.execute_input":"2021-12-04T06:26:16.150264Z","iopub.status.idle":"2021-12-04T06:26:16.155257Z","shell.execute_reply.started":"2021-12-04T06:26:16.150234Z","shell.execute_reply":"2021-12-04T06:26:16.153098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}