{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## CNN Activation\nIn this book, I design and test all the experimental CNN models. To design my models, I use the python programming language. To perform the experimental review I use three different datasets, those are- Sign Language MNIST, Digit-Recognizer MNIST, and Skin Cancer MNIST. \nI use 10 epochs for the experimental fold. For the experimental purpose, I use one fold for each model. In this experiment, I used a total of twenty-seven similar types of CNN models. \nIn this book, I analyze the performances of the CNN models for the different activation functions. After analyzing the results, I recommend the activation functions based on the performances for the convolutional layer in neural networks. \nThe goal of this experiment is to help the developer to get a clear concept of the activation functions for the convolutional layers of the networks. ","metadata":{"_cell_guid":"b8f23803-f7c9-c890-22dd-eab6672e749c"}},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix","metadata":{"_cell_guid":"19d8eb6b-9b71-029c-06e1-7e74975ae669","execution":{"iopub.status.busy":"2021-08-28T05:57:32.271217Z","iopub.execute_input":"2021-08-28T05:57:32.271673Z","iopub.status.idle":"2021-08-28T05:57:32.279263Z","shell.execute_reply.started":"2021-08-28T05:57:32.271623Z","shell.execute_reply":"2021-08-28T05:57:32.277917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.utils.np_utils import to_categorical # convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler","metadata":{"_cell_guid":"76adcf6f-d109-e47d-d8f0-c7a26e986df5","execution":{"iopub.status.busy":"2021-08-28T05:57:34.620344Z","iopub.execute_input":"2021-08-28T05:57:34.620797Z","iopub.status.idle":"2021-08-28T05:57:34.627675Z","shell.execute_reply.started":"2021-08-28T05:57:34.620763Z","shell.execute_reply":"2021-08-28T05:57:34.626783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_file = \"../input/train.csv\"\ntest_file = \"../input/test.csv\"\noutput_file = \"submission.csv\"","metadata":{"_cell_guid":"249daad0-7a0d-ad43-2bf9-4861ffac0d90","execution":{"iopub.status.busy":"2021-08-28T05:57:34.632311Z","iopub.execute_input":"2021-08-28T05:57:34.632793Z","iopub.status.idle":"2021-08-28T05:57:34.643178Z","shell.execute_reply.started":"2021-08-28T05:57:34.632753Z","shell.execute_reply":"2021-08-28T05:57:34.642268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"raw_data = np.loadtxt(train_file, skiprows=1, dtype='int', delimiter=',')\nx_train, x_val, y_train, y_val = train_test_split(\n    raw_data[:,1:], raw_data[:,0], test_size=0.1)","metadata":{"_cell_guid":"95cd483d-23ae-fa98-3823-724e41ed4b5b","execution":{"iopub.status.busy":"2021-08-28T05:57:35.409407Z","iopub.execute_input":"2021-08-28T05:57:35.409972Z","iopub.status.idle":"2021-08-28T05:58:32.598003Z","shell.execute_reply.started":"2021-08-28T05:57:35.409935Z","shell.execute_reply":"2021-08-28T05:58:32.597077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, ax = plt.subplots(2, 1, figsize=(12,6))\nax[0].plot(x_train[0])\nax[0].set_title('784x1 data')\nax[1].imshow(x_train[0].reshape(28,28), cmap='gray')\nax[1].set_title('28x28 data')","metadata":{"_cell_guid":"77036419-61ff-a6a5-6b67-fa39f1147d11","execution":{"iopub.status.busy":"2021-08-28T05:58:32.5999Z","iopub.execute_input":"2021-08-28T05:58:32.600501Z","iopub.status.idle":"2021-08-28T05:58:32.877147Z","shell.execute_reply.started":"2021-08-28T05:58:32.600454Z","shell.execute_reply":"2021-08-28T05:58:32.875864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.reshape(-1, 28, 28, 1)\nx_val = x_val.reshape(-1, 28, 28, 1)","metadata":{"_cell_guid":"c32f7260-7973-31a4-3991-1bbac6c36b47","execution":{"iopub.status.busy":"2021-08-28T05:58:32.878573Z","iopub.execute_input":"2021-08-28T05:58:32.878905Z","iopub.status.idle":"2021-08-28T05:58:32.883661Z","shell.execute_reply.started":"2021-08-28T05:58:32.878871Z","shell.execute_reply":"2021-08-28T05:58:32.882577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.astype(\"float32\")/255.\nx_val = x_val.astype(\"float32\")/255.","metadata":{"_cell_guid":"c291c473-5e0e-a947-bea6-22d5feb81797","execution":{"iopub.status.busy":"2021-08-28T05:58:32.88517Z","iopub.execute_input":"2021-08-28T05:58:32.885456Z","iopub.status.idle":"2021-08-28T05:58:32.978016Z","shell.execute_reply.started":"2021-08-28T05:58:32.885427Z","shell.execute_reply":"2021-08-28T05:58:32.977032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = to_categorical(y_train)\ny_val = to_categorical(y_val)\n#example:\nprint(y_train[0])","metadata":{"_cell_guid":"fdc43c64-0655-e91d-0659-ceb97a6f3532","execution":{"iopub.status.busy":"2021-08-28T05:58:32.981987Z","iopub.execute_input":"2021-08-28T05:58:32.982491Z","iopub.status.idle":"2021-08-28T05:58:32.990215Z","shell.execute_reply.started":"2021-08-28T05:58:32.982441Z","shell.execute_reply":"2021-08-28T05:58:32.98894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(filters = 128, kernel_size = (3, 3), activation='tanh', input_shape = (28, 28, 1)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(strides=(2,2)))\nmodel.add(Conv2D(filters = 128, kernel_size = (3, 3), activation='tanh', input_shape = (28, 28, 1)))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(strides=(2,2)))\nmodel.add(Flatten())\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.summary()","metadata":{"_cell_guid":"363e8bc8-a731-01da-9a39-d3914ea7a5c8","execution":{"iopub.status.busy":"2021-08-28T05:58:32.992086Z","iopub.execute_input":"2021-08-28T05:58:32.992387Z","iopub.status.idle":"2021-08-28T05:58:33.065773Z","shell.execute_reply.started":"2021-08-28T05:58:32.992356Z","shell.execute_reply":"2021-08-28T05:58:33.064831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator(zoom_range = 0.1,\n                            height_shift_range = 0.1,\n                            width_shift_range = 0.1,\n                            rotation_range = 10)","metadata":{"_cell_guid":"c34d0682-2777-382d-ab1c-fa0186fc0ae7","execution":{"iopub.status.busy":"2021-08-28T05:58:33.067055Z","iopub.execute_input":"2021-08-28T05:58:33.067364Z","iopub.status.idle":"2021-08-28T05:58:33.07178Z","shell.execute_reply.started":"2021-08-28T05:58:33.067336Z","shell.execute_reply":"2021-08-28T05:58:33.070994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer = Adam(lr=1e-4), metrics=[\"accuracy\"])","metadata":{"_cell_guid":"d0acbcf9-0be3-712f-222d-58e6670dac58","execution":{"iopub.status.busy":"2021-08-28T05:58:33.073067Z","iopub.execute_input":"2021-08-28T05:58:33.073375Z","iopub.status.idle":"2021-08-28T05:58:33.091565Z","shell.execute_reply.started":"2021-08-28T05:58:33.073343Z","shell.execute_reply":"2021-08-28T05:58:33.090539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"annealer = LearningRateScheduler(lambda x: 1e-3 * 0.9 ** x)","metadata":{"_cell_guid":"856a2d69-b0eb-6962-5323-fd2819d0be24","execution":{"iopub.status.busy":"2021-08-28T05:58:33.093242Z","iopub.execute_input":"2021-08-28T05:58:33.093674Z","iopub.status.idle":"2021-08-28T05:58:33.100239Z","shell.execute_reply.started":"2021-08-28T05:58:33.093599Z","shell.execute_reply":"2021-08-28T05:58:33.099245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist = model.fit_generator(datagen.flow(x_train, y_train, batch_size=16),\n                           steps_per_epoch=500,\n                           epochs=10, #Increase this when not on Kaggle kernel\n                           verbose=2,  #1 for ETA, 0 for silent\n                           validation_data=(x_val[:400,:], y_val[:400,:]), #For speed\n                           callbacks=[annealer])","metadata":{"_cell_guid":"b8d960a3-09ed-0802-2b23-4ed583f7492b","execution":{"iopub.status.busy":"2021-08-28T05:58:33.101616Z","iopub.execute_input":"2021-08-28T05:58:33.102092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_loss, final_acc = model.evaluate(x_val, y_val, verbose=0)\nprint(\"Final loss: {0:.4f}, final accuracy: {1:.4f}\".format(final_loss, final_acc))","metadata":{"_cell_guid":"d3a2a555-ef78-1cce-3971-0ea4f7bb0c1d","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(hist.history['loss'], color='b')\nplt.plot(hist.history['val_loss'], color='r')\nplt.show()\nplt.plot(hist.history['acc'], color='b')\nplt.plot(hist.history['val_acc'], color='r')\nplt.show()","metadata":{"_cell_guid":"49fd9696-826d-f95c-3fe6-94fe4d1f0a6c","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_hat = model.predict(x_val)\ny_pred = np.argmax(y_hat, axis=1)\ny_true = np.argmax(y_val, axis=1)\ncm = confusion_matrix(y_true, y_pred)\nprint(cm)","metadata":{"_cell_guid":"0783efce-d6b9-6d98-3824-0b45260a0f23","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mnist_testset = np.loadtxt(test_file, skiprows=1, dtype='int', delimiter=',')\nx_test = mnist_testset.astype(\"float32\")\nx_test = x_test.reshape(-1, 28, 28, 1)/255.","metadata":{"_cell_guid":"002ce4ad-9a8f-8a1e-c658-40f9c371f91d","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_hat = model.predict(x_test, batch_size=64)","metadata":{"_cell_guid":"7413800d-21c3-654f-8b39-27e3df9c4391","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = np.argmax(y_hat,axis=1)","metadata":{"_cell_guid":"575d9348-99ec-9b8c-f5a5-ceac44c5308d","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open(output_file, 'w') as f :\n    f.write('ImageId,Label\\n')\n    for i in range(len(y_pred)) :\n        f.write(\"\".join([str(i+1),',',str(y_pred[i]),'\\n']))","metadata":{"_cell_guid":"cbf31eb1-2ffd-efb5-e2b2-b4dda99fa1da","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"_cell_guid":"5591673a-99e2-2269-8cc9-55573d49e029","trusted":true},"execution_count":null,"outputs":[]}]}