{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"# This kernel may help you how to build and and train more than one single model and re-use weights.\n# Additionally I try to show why to use more that one CNN to chase higher accuracy points and \n# to reduce stochastic effect of the training process. \n\n# Version 1 is the original kernel training three CNNs. \n# Run time is approx 2800 sec using GPU.\n# Submitted accuracy against test set is 0.9888.\n\n# Version 4 is a 2nd training of the three CNNs and it was not submitted, weights were saved instead. \n# Run time is approx 2800 sec using GPU.\n\n# GPU was switched off at this point.\n# Run time for commits below are between 30-60 seconds.\n\n# Version 5 is a no training kernel, it loads weight sets saved in Kernel 4 and creates submission \n# file using all three CNNs.\n# Submitted ensemble accuracy against test set is 0.9878.\n\n# Version 6-8 are kernels using single CNN weight sets which were determined in kernel Version 4.\n# Single CNN submission accuracies are 0.985 0.9842 and 0.9862.\n\n# Please note variance of single CNN accuracies. \n# Difference between minimum and maximum accuracy is 0.0020 for this model with these hyper parameters. \n# Please also note that ensemble CNN accuracy is significantly higher than any of the accuracies for \n# single CNN ones.\n\n# There is a variance in accuracy even in the case when more than one single CNN is used for prediction. \n# See kernels Version 1 and Version 5 with accucacies of 0.9888 vs 0.9878.","execution_count":null,"outputs":[]},{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\ntest5000 = pd.read_csv(\"../input/Kannada-MNIST/test.csv\")\ntrain = pd.read_csv(\"../input/Kannada-MNIST/train.csv\")\nprint(train.shape)\nprint(test5000.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\n\nX_train = train.drop(labels = [\"label\"],axis = 1)\nX_train = X_train / 255.0\nX_train = X_train.values.reshape(-1,28,28,1)\n\nY_trainlabel = train[\"label\"]\nY_train = to_categorical(Y_trainlabel, num_classes = 10)\n\nX_test5000 = test5000.drop(labels = [\"id\"],axis = 1)\nX_test5000 = X_test5000 / 255.0\nX_test5000 = X_test5000.values.reshape(-1,28,28,1)\n\nx_train = X_train\ny_train = Y_train\n\nprint(x_train.shape)\nprint(y_train.shape)\nprint(X_test5000.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, BatchNormalization\nfrom keras.initializers import he_normal\nfrom keras.optimizers import Adam\n\ninit = he_normal(seed=82)\nnets = 3\n\nmodel = [0] *(nets+1)\n\nfor j in range(nets+1):\n    model[j] = Sequential()\n\n    model[j].add(Conv2D(32, kernel_size=3, activation='relu' , kernel_initializer=init, input_shape=(28, 28, 1)))\n    model[j].add(BatchNormalization())\n    model[j].add(Conv2D(32, kernel_size=3, activation='relu' , kernel_initializer=init ))\n    model[j].add(BatchNormalization())\n\n    model[j].add(Conv2D(32, kernel_size=5, activation='relu', kernel_initializer=init ))\n    model[j].add(BatchNormalization())\n    model[j].add(Dropout(0.4))\n    model[j].add(Conv2D(64, kernel_size=5, activation='relu', kernel_initializer=init ))\n    model[j].add(BatchNormalization())\n\n    model[j].add(Conv2D(64, kernel_size=7, activation='relu', kernel_initializer=init ))\n    model[j].add(BatchNormalization())\n    model[j].add(Conv2D(64, kernel_size=7, activation='relu', kernel_initializer=init ))\n    model[j].add(BatchNormalization())\n    model[j].add(Dropout(0.4))\n\n    model[j].add(Conv2D(128, kernel_size=4, activation='relu', kernel_initializer=init ))\n    model[j].add(BatchNormalization())\n    model[j].add(Flatten())\n    model[j].add(Dropout(0.4))\n    model[j].add(Dense(10, activation='softmax'))\n\n    model[j].compile(optimizer=\"adam\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\n\nmodel[0].summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for j in range(nets):\n    loadmodelname = \"../input/kmnist-trio/weights_N\" + str(j)\n    model[j].load_weights(loadmodelname)\n    savemodelname = \"weights_N\" + str(j)\n    model[j].save_weights(savemodelname)\n    print(\"Saving\", loadmodelname, \"back to\", savemodelname)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing. image import ImageDataGenerator\ndatagen = ImageDataGenerator(rotation_range=10, zoom_range = 0.1, width_shift_range=0.1, height_shift_range=0.1)\nfrom sklearn.model_selection import train_test_split\n#from keras.callbacks import *\nfrom keras.callbacks import LearningRateScheduler, ModelCheckpoint\nannealer = LearningRateScheduler(lambda x: 1e-3 * 0.95 ** x, verbose=0)\n\nnets2train = 0\nhistory = [0] * nets2train\nepoks = 35\n\nfor j in range(nets2train):\n    rs = 10 * j + 1\n    X_train2, X_val2, Y_train2, Y_val2 = train_test_split(x_train, y_train, train_size = 0.95, random_state = rs)\n    print (X_train2.shape,Y_train2.shape, X_val2.shape, Y_val2.shape)\n    modelfilename = \"weights_N\" + str(j)\n    checkpoint = ModelCheckpoint(modelfilename, monitor='val_acc', verbose=0, save_best_only=False, save_weights_only=False, period=epoks)\n    history[j] = model[j].fit_generator(datagen.flow(X_train2,Y_train2, batch_size = 64), epochs = epoks, steps_per_epoch = X_train2.shape[0]//64, validation_data = (X_val2, Y_val2), callbacks=[annealer, checkpoint], verbose=0)\n    print(\"CNN\", j,\": Training done.\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results5000 = np.zeros( (X_test5000.shape[0], 10) ) \nnets4predict = 3\nallthree = False\nfor j in range(nets4predict):\n    if allthree or j== 2:\n        print(\"CNN\",j)\n        loadmodelname = \"weights_N\" + str(j)\n        model[j].load_weights(loadmodelname)\n        results5000 = results5000 + model[j].predict(X_test5000)\nresults5000 = np.argmax(results5000,axis = 1)\n\nsubmission = pd.read_csv(\"../input/Kannada-MNIST/sample_submission.csv\")\nsubmission['label'] = results5000\nsubmission.to_csv(\"submission.csv\",index=False)\n\nprint(\"DONE.\")","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}