{"cells":[{"cell_type":"markdown","metadata":{"_cell_guid":"f80afe77-d9fc-135f-b1ee-3da5a197ead1"},"source":""},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"26350de1-ccf2-493e-c44f-a0cad37d34ff"},"outputs":[],"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\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output."},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"d136ef10-313b-f44f-866b-6a34616ca1af"},"outputs":[],"source":"trainLabels = pd.read_csv(\"../input/trainLabels.csv\")\ntrainLabels.head()"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"1e791a50-0c32-47f6-a208-9a142e826e6c"},"outputs":[],"source":"import os\n\nlisting = os.listdir(\"../input\") \nlisting.remove(\"trainLabels.csv\")\nnp.size(listing)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"62f7c4ce-9401-6b14-6b56-8dea4b32628e"},"outputs":[],"source":"from PIL import Image\n\n# input image dimensions\nimg_rows, img_cols = 200, 200\n\nimmatrix = []\nimlabel = []\n\nfor file in listing:\n    base = os.path.basename(\"../input/\" + file)\n    fileName = os.path.splitext(base)[0]\n    imlabel.append(trainLabels.loc[trainLabels.image==fileName, 'level'].values[0])\n    im = Image.open(\"../input/\" + file)   \n    img = im.resize((img_rows,img_cols))\n    gray = img.convert('L')\n    immatrix.append(np.array(gray).flatten())"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"b20ecbdf-2d93-251c-c170-312e874ea080"},"outputs":[],"source":"immatrix = np.asarray(immatrix)\nimlabel = np.asarray(imlabel)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"eb69f726-dff5-d63e-7962-9b9acf56aab2"},"outputs":[],"source":"from sklearn.utils import shuffle\n\ndata,Label = shuffle(immatrix,imlabel, random_state=2)\ntrain_data = [data,Label]\ntype(train_data)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"e9dc0695-77ec-0745-ad7b-231bd6a05c1c"},"outputs":[],"source":"import matplotlib.pyplot as plt\nimport matplotlib\n\nimg=immatrix[167].reshape(img_rows,img_cols)\nplt.imshow(img)\nplt.imshow(img,cmap='gray')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"4a4649db-b109-fade-60c9-34768ebdd86d"},"outputs":[],"source":"#batch_size to train\nbatch_size = 32\n# number of output classes\nnb_classes = 5\n# number of epochs to train\nnb_epoch = 5"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"7d8860d1-c057-ea4c-81c5-b3ec2e0545f3"},"outputs":[],"source":"# number of convolutional filters to use\nnb_filters = 32\n# size of pooling area for max pooling\nnb_pool = 2\n# convolution kernel size\nnb_conv = 3"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"d5d391a3-037e-e458-8531-52f88b475239"},"outputs":[],"source":"(X, y) = (train_data[0],train_data[1])"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"18384427-2ec9-9d65-b30f-669a07441b03"},"outputs":[],"source":"from sklearn.cross_validation import train_test_split\n\n# STEP 1: split X and y into training and testing sets\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)\n\nprint(X_train.shape)\nprint(X_test.shape)\n\n#X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)\n#X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)\n\nX_train = X_train.reshape(X_train.shape[0], img_cols, img_rows, 1)\nX_test = X_test.reshape(X_test.shape[0], img_cols, img_rows, 1)\n\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n\nX_train /= 255\nX_test /= 255\n\nprint('X_train shape:', X_train.shape)\nprint(X_train.shape[0], 'train samples')\nprint(X_test.shape[0], 'test samples')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"71c8b327-d726-da45-829f-1b71fbe2b546"},"outputs":[],"source":"from keras.utils import np_utils\n\n# convert class vectors to binary class matrices\nY_train = np_utils.to_categorical(y_train, nb_classes)\nY_test = np_utils.to_categorical(y_test, nb_classes)\n\ni = 100\nplt.imshow(X_train[i, 0], interpolation='nearest')\nprint(\"label : \", Y_train[i,:])"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"98a7e62e-3fc5-45e7-7088-ef5b0f856719"},"outputs":[],"source":"#KERAS\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nfrom keras.optimizers import SGD,RMSprop,adam\n\nmodel = Sequential()\n\nmodel.add(Convolution2D(nb_filters, nb_conv, nb_conv,\n                        border_mode='valid',\n                        input_shape=(img_cols, img_rows, 1)))\nconvout1 = Activation('relu')\nmodel.add(convout1)\nmodel.add(Convolution2D(nb_filters, nb_conv, nb_conv))\nconvout2 = Activation('relu')\nmodel.add(convout2)\nmodel.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\nmodel.add(Dense(128))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(nb_classes))\nmodel.add(Activation('softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adadelta')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"281944be-20ed-2355-ee95-10807b2782ad"},"outputs":[],"source":"from keras.preprocessing.image import ImageDataGenerator\n\n# create generators  - training data will be augmented images\nvalidationdatagenerator = ImageDataGenerator()\ntraindatagenerator = ImageDataGenerator(width_shift_range=0.1,height_shift_range=0.1,rotation_range=15,zoom_range=0.1 )\n\nbatchsize=8\ntrain_generator=traindatagenerator.flow(X_train, Y_train, batch_size=batchsize) \nvalidation_generator=validationdatagenerator.flow(X_test, Y_test,batch_size=batchsize)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"bbcb45fb-4dae-7ebe-85e6-1de933b3fedd"},"outputs":[],"source":"#hist = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(X_test, Y_test))\n\nmodel.fit_generator(train_generator, steps_per_epoch=int(len(X_train)/batchsize), epochs=3, validation_data=validation_generator, validation_steps=int(len(X_test)/batchsize))\n\n#hist = model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,\n#              show_accuracy=True, verbose=1, validation_split=0.2)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"66858f4b-ae99-c4ef-85d7-42cf180b7be2"},"outputs":[],"source":"score = model.evaluate(X_test, Y_test, verbose=0)\nprint(score)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"d624d98a-da5d-da27-1177-9810e575b1df"},"outputs":[],"source":""}],"metadata":{"_change_revision":0,"_is_fork":false,"kernelspec":{"display_name":"Python 3","language":"python","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.0"}},"nbformat":4,"nbformat_minor":0}