{"cells":[{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"d9d40dc8-eae2-5e9d-87cf-f15e58f82c29"},"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":"963016ae-a336-dc37-7d91-c41503710698"},"outputs":[],"source":"trainLabels = pd.read_csv(\"../input/trainLabels.csv\")\ntrainLabels.head()"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"5e72b0dc-412a-da1b-3b75-56811c08b05e"},"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":"3c7587b9-2de9-3225-1b17-ed01819e719b"},"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())\n    "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"4ea9a682-76b3-f14f-b78b-bf740ae59624"},"outputs":[],"source":"immatrix = np.asarray(immatrix)\nimlabel = np.asarray(imlabel)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"c94fde6e-04a1-2b1d-d969-24c7eec5c774"},"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":"3c83f8a0-06ee-d7b9-2f68-0b8378f6bb6e"},"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":"81a382eb-b5ba-b941-0b2a-2790252a907e"},"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":"0c59ad38-3144-807b-e5d2-7e56974162d2"},"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":"8b52b20b-0e5e-91cb-664d-a33167995111"},"outputs":[],"source":"(X, y) = (train_data[0],train_data[1])\nfrom 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":"6c5d9169-cdb8-df65-2ea3-a3a6f9694fa3"},"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":"c1c4b87a-053e-c580-fcf6-93d80d5ed8e6"},"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')#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":"e7871692-22bd-eceb-d429-deac0787fa09"},"outputs":[],"source":"from IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\n\nSVG(model_to_dot(model).create(prog='dot', format='svg'))"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"19b57223-dcd9-c3f0-35b3-e693e6fac730"},"outputs":[],"source":"from pydot import pydot.Graph\nimport graphviz\nfrom keras.utils import plot_model\nplot_model(model, to_file='model.png')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"85aa895e-a687-3874-e965-89dc9ff00462"},"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)\n"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"77510f9e-4f66-e38d-3620-a7b33cdd04d1"},"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":"908a049d-0c6b-a2b9-8b4d-3df740b525b8"},"outputs":[],"source":"score = model.evaluate(X_test, Y_test, verbose=0)\nprint(score)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"9edd5723-70ee-223c-2be0-feb69d4a8843"},"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}