{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"scrolled":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":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom skimage.transform import rescale\nfrom sklearn import preprocessing\nfrom keras.models import load_model\nfrom keras.layers import BatchNormalization\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"86c525c8bbf3aa48f1f1d4362eb4b7b7d9f3b34b"},"cell_type":"code","source":"img_rows = 40\nimg_cols = 40","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8827c5e5b4c247207896327b7751bb64c2eaf9c3"},"cell_type":"code","source":"#X = np.load(\"../input/rescalinginputdata/40x40_rescaled_trainX.npy\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f4a853a43094285ef2b530cadabee623a27e436a"},"cell_type":"code","source":"encoder = preprocessing.LabelEncoder()\nencoder.fit(np.load(\"../input/tmpfory/trainY.npy\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"210473dc63c87625c3afb0fb822c5d51b7709f3b"},"cell_type":"code","source":"T = np.load(\"../input/inputtestdata40x40/testT.npy\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a8447c850112eef39a75591366eeaea002e18c13","scrolled":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, kernel_size = 3, activation='relu', input_shape = (img_rows, img_cols, 1)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size = 3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, kernel_size = 5, strides=2, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(128, kernel_size = 3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, kernel_size = 3, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, kernel_size = 5, strides=2, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(256, kernel_size = 4, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Flatten())\nmodel.add(Dropout(0.4))\nmodel.add(Dense(1000, activation='softmax'))\n\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\n\nprint(model.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"648c3057b3d262553763f3a9162b96a78ae9d5f2"},"cell_type":"code","source":"# CREATE MORE IMAGES VIA DATA AUGMENTATION\ndatagen = ImageDataGenerator(\n        rotation_range=8,\n        zoom_range = 0.10,\n        width_shift_range=0.1, \n        height_shift_range=0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"100476fd8085be0dd616e8db34c86fae156ccea4"},"cell_type":"code","source":"annealer = LearningRateScheduler(lambda x: 1e-3 * 0.95 ** x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e7d62b6cab0ccb1404579914cb469151ed2dde3c"},"cell_type":"code","source":"#X_train2, X_val2, Y_train2, Y_val2 = train_test_split(X, y, test_size = 0.1)\nX_train2 = np.load(\"../input/rescalinginputdata/X_train2.npy\")\nX_val2 = np.load(\"../input/rescalinginputdata/X_val2.npy\")\nY_train2 = np_utils.to_categorical(encoder.transform(np.load(\"../input/rescalinginputdata/Y_train2.npy\")))\nY_val2 = np_utils.to_categorical(encoder.transform(np.load(\"../input/rescalinginputdata/Y_val2.npy\")))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a0bd4ee1b602da646eeabc2837b02972822a9735"},"cell_type":"code","source":"history = model.fit_generator(datagen.flow(X_train2,Y_train2, batch_size=64),\n    epochs = 18, steps_per_epoch = X_train2.shape[0]//64,  \n    validation_data = (X_val2,Y_val2), callbacks=[annealer], verbose=0, initial_epoch=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b3e92cf96e5668ca36d69cafd9dd8d4a8c26312a"},"cell_type":"code","source":"str(history.history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"84bf8e70e0cdff701757821316f18393b70d9f30"},"cell_type":"code","source":"history = history.history\nfile = open('info.csv', 'w')\nfile.write(str(history))\nfile.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"441ac6701a3e631eedfe7e301281eed2d14ea7a1"},"cell_type":"code","source":"# epochs = 20\n# history = [0] * epochs\n\n# for j in range(epochs):\n#     #X_train2, X_val2, Y_train2, Y_val2 = train_test_split(X, y, test_size = 0.1)\n#     history[j] = model.fit_generator(datagen.flow(X, y, batch_size=64),\n#         epochs = j+1, steps_per_epoch = X.shape[0]//64,\n#         callbacks=[annealer], verbose=0, initial_epoch=j)\n#     if j % 3 == 0:\n#         predictions = model.predict(T)\n#         predictions = np.argmax(predictions, axis=1)\n#         res = encoder.inverse_transform(predictions)\n#         file = open('ans' + str(j) + '.csv', 'w')\n#         file.write(str(history[j].history) + '\\n')\n#         file.write('Id,Category\\n')\n#         for i in range(res.size):\n#             file.write('' + str(i + 1) + ',' + str(res[i]) + '\\n')\n#         file.close()\n#     #print(\"Epoch={}, Train accuracy={2:.5f}\".format(j+1, max(history[j].history['acc'])))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"792aa4d230ae42a3d7e0bc980f41b11e466240b8"},"cell_type":"code","source":"# last = model.fit(X, y, batch_size=64, epochs=1, verbose=0, initial_epoch=0, validation_split=0.1)\n# history.append(last)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9351867803088e2513e13685c0f9c076a112f20c"},"cell_type":"code","source":"#history[0].history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fb3d6e7a4397d45947bf92731e6096ab8b93932f"},"cell_type":"code","source":"predictions = model.predict(T)\npredictions = np.argmax(predictions, axis=1)\nres = encoder.inverse_transform(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"08477da994dbc8bc607f1db4208c8856e7b4254b"},"cell_type":"code","source":"file = open('ansEpochs.csv', 'w')\nfile.write('Id,Category\\n')\nfor i in range(res.size):\n    file.write('' + str(i + 1) + ',' + str(res[i]) + '\\n')\nfile.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"69c3f90e3b2747990e88c7043a9674c5915cae84"},"cell_type":"code","source":"# from IPython.display import HTML\n# import pandas as pd\n# import numpy as np\n# import base64\n\n# # function that takes in a dataframe and creates a text link to  \n# # download it (will only work for files < 2MB or so)\n\n# def create_download_link(df, title = \"Download CSV file\", filename = \"data.csv\"):  \n#     df = pd.DataFrame(df)\n#     df.index += 1\n#     csv = df.to_csv(index=True)\n#     b64 = base64.b64encode(csv.encode())\n#     payload = b64.decode()\n#     html = '<a download=\"{filename}\" href=\"data:text/csv;base64,{payload}\" target=\"_blank\">{title}</a>'\n#     html = html.format(payload=payload,title=title,filename=filename)\n#     return HTML(html)\n\n# create_download_link(res, filename=\"answer.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ed6f3cbb2acf9fd05eae95e20bce208763150fd6"},"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.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}