{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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 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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"\n#!pip install -q keras\n#!pip install -q keract\n#!pip install -q matplotlib\n#!pip install -q sklearn\n#!pip install -q numpy\n#!pip install  imutils\n#!pip install  Image\n#!apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python\n\n#%matplotlib inline \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Conv2D, Dense,MaxPooling2D,Dropout,Flatten\nfrom keras.models import Sequential\nimport keras","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"treinamento=pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')\nteste=pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def ConvertCSVImage(frame):\n  Y=frame['label']\n  Y=np.array(Y)\n  X=frame\n  X=X.drop('label',axis=1)\n  #del X['label']\n  X=np.array(X)\n  #print(X.shape)\n  X=np.reshape(X, (X.shape[0], 28,28)) # C-like index ordering\n  X=X/255\n  Y=keras.utils.to_categorical(Y)\n\n  return X,Y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train,Y_train=ConvertCSVImage(treinamento)\n#X_test,Y_test=ConvertCSVImage(validacao)\nX_test=X_train[50000:60000,]\nY_test=Y_train[50000:60000,]\nX_train=X_train[0:50000,]\nY_train=Y_train[0:50000,]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"input_shape=(28,28,1)\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs=10\nbatch_size=32\nnum_classes=10\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n                 activation='relu',\n                 input_shape=input_shape))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n              optimizer=keras.optimizers.Adadelta(),\n              metrics=['accuracy'])\n\nmodel.fit(X_train, Y_train,\n          batch_size=batch_size,\n          epochs=epochs,\n          verbose=1,\n          validation_data=(X_test, Y_test))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def GradCAM(model,imagearray,NClasses=1):\n  #from keras.preprocessing import image\n  import cv2 \n  from PIL import Image\n  #from keras.models import load_model\n  import numpy as np\n  #model=load_model(model)\n  #img_size=img_size\n  #img_size=img_size\n  #img_size=list(img_size)\n  #for j in range(0,(len(img_size)) ):\n  #  img_size[j]=int(img_size[j])\n  #img_size=tuple(img_size)  \n  #Data = image.load_img(img_path, target_size=img_size) #(224,224)\n  #Data = image.img_to_array(Data)\n  #Data = np.expand_dims(Data, axis=0)\n # Data = preprocess_input(Data)\n\n  #x=Data\n  x=imagearray\n  #x=x/255\n\n  layer_names=[]\n  cont=0\n  Indices=[]\n  for layers in model.layers:\n    aux=type(layers)\n    aux=str(aux)\n    if \"Conv2D\" in aux:\n      layer_names.append(layers.name)\n      Indices.append(cont)\n    cont=cont+1\n  Indices=Indices[-1]\n\n  preds = model.predict(x)\n  class_idx = np.argmax(preds[0,])\n  class_output = model.output[:, class_idx]\n  last_conv_layer = model.layers[Indices]#model.get_layer(\"block5_conv3\")\n\n  import keras.backend as K\n  grads = K.gradients(class_output, last_conv_layer.output)[0]\n  pooled_grads = K.mean(grads, axis=(0, 1, 2))\n  iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])\n  pooled_grads_value, conv_layer_output_value = iterate([x])\n  #print(len(conv_layer_output_value[1,1,:]))\n  for i in range(len(conv_layer_output_value[1,1,:])):\n    conv_layer_output_value[:, :, i] *= pooled_grads_value[i]\n  heatmap = np.mean(conv_layer_output_value, axis=-1)\n  heatmap = np.maximum(heatmap, 0)\n  heatmap /= np.max(heatmap)\n\n # from google.colab.patches import cv2_imshow\n\n  #img = cv2.imread(img_path)\n  heatmap = cv2.resize(heatmap, (28, 28))\n  heatmap = np.uint8(255 * heatmap)\n  heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)\n  superimposed_img=0.6*imagearray + 0.4*heatmap\n  #superimposed_img = cv2.addWeighted(imagearray, 0.6, heatmap, 0.4, 0)\n  #cv2.imshow('Original',img)\n  print(superimposed_img.shape)\n  img=np.reshape(superimposed_img,(28,28,3))\n  imagearray=np.reshape(imagearray,(28,28))\n  #img = Image.fromarray(superimposed_img, 'RGB')\n # print(\"A classe Predita foi\",class_idx)\n  return(img,imagearray)\n  #cv2_imshow(superimposed_img)\n  #cv2.waitKey(0)\n  #return(superimposed_img)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nTesteX=teste\nTesteX=TesteX.drop('id',axis=1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TesteX=np.array(TesteX)\nTesteX=np.reshape(TesteX, (TesteX.shape[0], 28,28,1)) # C-like index orderin","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"previsoes=model.predict(TesteX)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=[]\nfor i in range(0,previsoes.shape[0]):\n  labels.append(np.argmax(previsoes[i,]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PrevisoesFinais=pd.DataFrame([teste['id'].values,labels])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PrevisoesFinais=PrevisoesFinais.transpose()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PrevisoesFinais.columns = ['id', 'label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PrevisoesFinais.to_csv('submission.csv', index=False)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Well we then trained a model and found our predictions but we can wonder why does the neural network tough of this answer?\n\nTo do so we utilize GradCam as defined above to vizualize which pixels were important in the image for top 1 classification"},{"metadata":{"trusted":true},"cell_type":"code","source":"Indice=43\naux=TesteX[Indice,]\naux=np.reshape(aux,(1,aux.shape[0],aux.shape[1],aux.shape[2] ) )\naux.shape\nNovo,Antigo=GradCAM(model,aux,1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(Antigo,cmap='gray')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(Novo, interpolation='nearest')\n\nplt.show()","execution_count":null,"outputs":[]}],"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":1}