{"cells":[{"metadata":{"_uuid":"dd26e28535802684399edd48f6c84f77cbe0a0c2"},"cell_type":"markdown","source":"<h1 style=\"color:steelblue; font-family:Ewert; font-size:150%;\" class=\"font-effect-3d\">Code Library, Style, and Links</h1>"},{"metadata":{"trusted":true,"_uuid":"254b8034bc54f6f9ebca00474ee1a402d8f8e3af","_kg_hide-input":true},"cell_type":"code","source":"%%html\n<style>\n@import url('https://fonts.googleapis.com/css?family=Ewert|Roboto&effect=3d|ice|');\nspan {font-family:'Roboto'; color:black; text-shadow:5px 5px 5px #aaa;}  \ndiv.output_area pre{font-family:'Roboto'; font-size:110%; color:steelblue;}      \n</style>","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np,pandas as pd,keras as ks\nimport os,ast,cv2,warnings\nimport pylab as pl\nfrom skimage.transform import resize\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix,\\\nclassification_report\nfrom keras.callbacks import ModelCheckpoint,\\\nReduceLROnPlateau\nfrom keras.models import Sequential\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers import Activation,Dropout,Dense,\\\nConv2D,MaxPooling2D,GlobalMaxPooling2D\nwarnings.filterwarnings('ignore')\npl.style.use('seaborn-whitegrid')\nstyle_dict={'background-color':'gainsboro','color':'steelblue', \n            'border-color':'white','font-family':'Roboto'}\nfpath='../input/quickdraw-doodle-recognition/train_simplified/'\nos.listdir(\"../input\")","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"af70f9dfaf326bf5c47c9aba8875921f3c3e5da7"},"cell_type":"markdown","source":"<h1 style=\"color:steelblue; font-family:Ewert; font-size:150%;\" class=\"font-effect-3d\">Data Exploration</h1>"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"I=64 # image size in pixels\nS=1 # current number of the label set {1,...,17} -> {1-20,..., 321-340}\nT=20 # number of labels in one set \nN=24000 # number of images with the same label in the training set\nfiles=sorted(os.listdir(fpath))\nlabels=[el.replace(\" \",\"_\")[:-4] for el in files]\nprint(labels)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true,"_uuid":"31b4af8cf851eef945a8af2b912f407f23a1f602"},"cell_type":"code","source":"def display_drawing():\n    for k in range(5) :  \n        pl.figure(figsize=(10,2))\n        pl.suptitle(files[(S-1)*T+k])\n        for i in range(5):\n            picture=ast.literal_eval(data[labels[(S-1)*T+k]].values[i])\n            for x,y in picture:\n                pl.subplot(1,5,i+1)\n                pl.plot(x,y,'-o',markersize=1,color='slategray')\n                pl.xticks([]); pl.yticks([])\n            pl.gca().invert_yaxis(); pl.axis('equal');            \ndef get_image(data,lw=7,time_color=True):\n    data=ast.literal_eval(data)\n    image=np.zeros((280,280),np.uint8)\n    for t,s in enumerate(data):\n        for i in range(len(s[0])-1):\n            color=255-min(t,10)*15 if time_color else 255\n            _=cv2.line(image,(s[0][i]+10,s[1][i]+10),\n                       (s[0][i+1]+10,s[1][i+1]+10),color,lw) \n    return cv2.resize(image,(I,I))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9e8612c6425f1c7a737c648c04d3efcbe467b375","_kg_hide-output":true},"cell_type":"code","source":"data=pd.DataFrame(index=range(N),\n                  columns=labels[(S-1)*T:S*T])\nfor i in range((S-1)*T,S*T):\n    data[labels[i]]=\\\n    pd.read_csv(fpath+files[i],\n                index_col='key_id').drawing.values[:N]\ndata.head(3).T.style.set_properties(**style_dict)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6f7fe6696e4b10e931617821285eaeaaabf80f93"},"cell_type":"code","source":"display_drawing()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5a03210c911976e767e2cc11e0dc8bbb1fc956e3"},"cell_type":"code","source":"images=[]\nfor label in labels[(S-1)*T:S*T]:\n    images.extend([get_image(data[label].iloc[i]) \n                   for i in range(N)])\nimages=np.array(images,dtype=np.uint8)\ntargets=np.array([[]+N*[k] for k in range((S-1)*T,S*T)],\n                 dtype=np.int32).reshape(N*T)\ndel data\nimages.shape,targets.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dc9ca5d3e2e74b977951fdfa696f49591bcdad13"},"cell_type":"code","source":"images=images.reshape(-1,I,I,1)\nx_train,x_test,y_train,y_test=\\\ntrain_test_split(images,targets,\n                 test_size=.2,random_state=1)\nn=int(len(x_test)/2)\nx_valid,y_valid=x_test[:n],y_test[:n]\nx_test,y_test=x_test[n:],y_test[n:]\ndel images,targets\n[x_train.shape,x_valid.shape,x_test.shape,\n y_train.shape,y_valid.shape,y_test.shape]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nn=np.random.randint(0,int(.8*T*N),3)\nll=labels[int(y_train[nn[0]])]+\\\n   ', '+labels[int(y_train[nn[1]])]+\\\n   ', '+labels[int(y_train[nn[2]])]\npl.figure(figsize=(10,2))\npl.subplot(1,3,1); pl.imshow(x_train[nn[0]].reshape(I,I))\npl.subplot(1,3,2); pl.imshow(x_train[nn[1]].reshape(I,I))\npl.subplot(1,3,3); pl.imshow(x_train[nn[2]].reshape(I,I))\npl.suptitle('Key Points to Lines: %s'%ll);","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"52b84da051fa35da706b68ebc2b6c64bd3440baf"},"cell_type":"markdown","source":"<h1 style=\"color:steelblue; font-family:Ewert; font-size:150%;\" class=\"font-effect-3d\">The Model</h1>"},{"metadata":{"trusted":true,"_uuid":"4dbf8d77977b5d0ba7c5ded81ad1e518f88d317f"},"cell_type":"code","source":"def model():\n    model=Sequential()\n    model.add(Conv2D(32,(5,5),padding='same',\n                     input_shape=x_train.shape[1:]))\n    model.add(LeakyReLU(alpha=.02))   \n    model.add(MaxPooling2D(pool_size=(2,2)))\n    model.add(Dropout(.2))\n    model.add(Conv2D(196,(5,5)))\n    model.add(LeakyReLU(alpha=.02))  \n    model.add(MaxPooling2D(pool_size=(2,2)))\n    model.add(Dropout(.2))\n    model.add(GlobalMaxPooling2D())   \n    model.add(Dense(1024))\n    model.add(LeakyReLU(alpha=.02))\n    model.add(Dropout(.5))   \n    model.add(Dense(T))\n    model.add(Activation('softmax'))\n    model.compile(loss='sparse_categorical_crossentropy',\n                  optimizer='adam',metrics=['accuracy'])\n    return model\nmodel=model()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(set(y_train));\nprint(set(y_train-(S-1)*T))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ba93d941135e6593d5fe33c74c8eea3e57bfe02d","_kg_hide-output":true},"cell_type":"code","source":"fw='weights.best.model.cv001-020.hdf5'\ncheckpointer=\\\nModelCheckpoint(filepath=fw,verbose=2,\n                save_best_only=True)\nlr_reduction=\\\nReduceLROnPlateau(monitor='val_loss',\n                  patience=5,verbose=2,factor=.75)\nhistory=model.fit(x_train,y_train-(S-1)*T,epochs=100,\n                  batch_size=1024,verbose=2,\n                  validation_data=(x_valid,y_valid-(S-1)*T),\n                  callbacks=[checkpointer,lr_reduction])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"10f165929e23ff3fc0749222f18762abfcc669ad"},"cell_type":"markdown","source":"<h1 style=\"color:steelblue; font-family:Ewert; font-size:150%;\" class=\"font-effect-3d\">Evaluation</h1>"},{"metadata":{"trusted":true,"_uuid":"7f07a9fa7b7c2df20b65b0c65e4581e4cdbe6b09"},"cell_type":"code","source":"model.load_weights(fw)\nmodel.evaluate(x_test,y_test-(S-1)*T)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"p_test=model.predict(x_test)\np_test=[np.argmax(x) for x in p_test]\np_test[:10]","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true,"_uuid":"10b173ca5e8fa661c8a01a80b2c3aaeee4d37da1"},"cell_type":"code","source":"well_predicted=[]\nfor p in range(len(x_test)):\n    if (p_test[p]+(S-1)*T==y_test[p]):\n        well_predicted.append(labels[(S-1)*T+p_test[p]])\nu=np.unique(well_predicted,return_counts=True)\npd.DataFrame({'labels':u[0],\n              'correct predictions':u[1]})\\\n.sort_values('correct predictions',ascending=False)\\\n.style.set_properties(**style_dict)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h1 style=\"color:steelblue; font-family:Ewert; font-size:150%;\" class=\"font-effect-3d\">New Versions</h1>\n\n[📓 Quick, Draw! Doodle Recognition OpenCV1](https://www.kaggle.com/olgabelitskaya/quick-draw-doodle-recognition-opencv1)\n\n[📓 Quick, Draw! Doodle Recognition OpenCV2](https://www.kaggle.com/olgabelitskaya/quick-draw-doodle-recognition-opencv2)"}],"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":4,"nbformat_minor":4}