{"cells":[{"metadata":{},"cell_type":"markdown","source":"Hello All!\nThis is my first competition on Kaggle, please leave comments and let me know what should be improved.\nThank you!","execution_count":null},{"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\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 read-only \"../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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport keras\nfrom tensorflow.keras.optimizers import Adam,RMSprop\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\nfrom tensorflow.keras.regularizers import l2\nfrom sklearn.svm import SVC","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv(\"../input/digit-recognizer/train.csv\")  #read the training data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.head()       #see the data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.info()           #see how many entries and type of data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_y = data['label']                               # get dependent variable \ndata.drop(['label'],axis=1,inplace=True)             # drop it from original dataframe\ndata_x = data                                        # store all independent variables separately\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_y.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_x = data_x.values.reshape(-1,28,28,1)                     # reshape to proper shape\ndata_y = data_y.values\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical               # turn individual numbers into categorical data\ndata_y = to_categorical(data_y)                               # Ex : [2] -> [0,0,1,0,0,0,0,0,0,0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_x = data_x / 255.0                        # since values are between 0 and 255, divide by 255 to make them between 0 to 1, easier for processing","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n        \n        tf.keras.layers.Conv2D(64,(3,3),activation='relu',input_shape=(28,28,1)),       # adding convolution layer with input size (28,28,1) , 1 means the images are in greyscale not rgb\n        tf.keras.layers.Conv2D(64,(3,3),activation='relu'),\n        tf.keras.layers.MaxPooling2D(2,2),                                              # adding pooling layer\n        tf.keras.layers.Dropout(0.5),\n    \n        tf.keras.layers.Conv2D(128,(3,3),activation='relu'),  \n        tf.keras.layers.Conv2D(192,(3,3),activation='relu'),\n        tf.keras.layers.MaxPooling2D(2,2),\n        tf.keras.layers.Dropout(0.5),\n    \n    \n        tf.keras.layers.Flatten(),                                                      # flatten will flatten the input (28,28,1) to a single array\n        #tf.keras.layers.Dropout(0.25),\n        tf.keras.layers.Dense(512,activation='relu',kernel_regularizer=l2(0.01)),                                   # hidden layer with 256 units\n        #tf.keras.layers.Dropout(0.25),\n        tf.keras.layers.Dense(10,activation='softmax')                                  # output layer with 10 units, each representing the corresponding output\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(Adam(lr=0.001),loss=\"categorical_crossentropy\",metrics=['accuracy'])          ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', patience=3, verbose=1, \n                                            factor=0.5, min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator                #for Data Augmentation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain_x, test_x, train_y, test_y = train_test_split(data_x,data_y,test_size=0.2,random_state=0)         # splitting data into train and test for validation later on","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(rotation_range=10,                                    # rotate image by 10 degrees\n      width_shift_range=0.1,                                                       # shift width focus randomly by 0.1\n      height_shift_range=0.1,                                                      #shift height focus randomly by 0.1\n      shear_range=0.1,                                                             # shear the image by a factor of 0.15\n      zoom_range=0.2,                                                              # zoom into the image by a factor of 0.25\n      fill_mode='nearest')                                                         # if pixels are missings fill them by taking their nearest pixels\n\ntrain_datagen = datagen.flow(train_x,train_y,batch_size=50)                        # flow training data in batches of 50 to the model\n\nvalidation_datagen = datagen.flow(test_x,test_y,batch_size=50)                     # flow validation data in batches of 50","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_datagen,\n          validation_data = validation_datagen,\n          steps_per_epoch=500,\n          epochs=50\n         )                                                                       # fit the model with training and validation generators\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('digitrec.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cur_model = tf.keras.models.load_model('/kaggle/input/digitrec/ogdigitrec1.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cur_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_model = tf.keras.Model(inputs=cur_model.input,outputs=cur_model.get_layer('dense_1').output)\nnew_model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(\"../input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = test.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = test/255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = cur_model.predict(test)                    # use model to predict for all test values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_labels = cur_model.predict_classes(test)\npred_labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = np.argmax(preds,axis=1)                               # since results are in categorical form, choose the highest in each and store them \nsubmission                                                         # the above cell also gives the same output, you can use either one","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_submission = pd.DataFrame({'ImageId': range(1,len(test)+1) ,'Label':submission })               # make dataframe with the column headders and predicted values\n\nmy_submission.to_csv(\"results.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nsubmission = pd.read_csv('../input/digitrec/newresults1.csv')\nsubmission.to_csv('newresults.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"svm_train = new_model.predict(train_x)\nsvm_val = new_model.predict(test_x)\nsvm_test = new_model.predict(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"svm = SVC(kernel='rbf')\n\nsvm.fit(svm_train,np.argmax(train_y,axis=1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"svm.score(svm_train,np.argmax(train_y,axis=1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"svm.score(svm_val,np.argmax(test_y,axis=1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"svm_pred = svm.predict(svm_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_submission = pd.DataFrame({'ImageId': range(1,len(test)+1) ,'Label':svm_pred })               # make dataframe with the column headders and predicted values\n\nmy_submission.to_csv(\"results.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import xgboost as xgb\n\nxb = xgb.XGBClassifier()\n\nxb.fit(svm_train,np.argmax(train_y,axis=1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xb.score(svm_train,np.argmax(train_y,axis=1))\nxb.score(svm_val,np.argmax(test_y,axis=1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xb_pred = xb.predict(svm_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xb_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"my_submission = pd.DataFrame({'ImageId': range(1,len(test)+1) ,'Label':xb_pred })               # make dataframe with the column headders and predicted values\n\nmy_submission.to_csv(\"fin_results.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":4}