{"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":"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-06-01T17:14:55.136358Z","iopub.execute_input":"2022-06-01T17:14:55.137348Z","iopub.status.idle":"2022-06-01T17:14:55.150444Z","shell.execute_reply.started":"2022-06-01T17:14:55.137264Z","shell.execute_reply":"2022-06-01T17:14:55.149329Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1. Importing Libraries","metadata":{}},{"cell_type":"code","source":"# Importing Libraries\nimport numpy as np \nimport pandas as pd\nfrom collections import Counter\nimport math\n# Importing Library for Data Visualization\nimport matplotlib.pyplot as plt\n\nimport sklearn\n# Importing Algorithms for Model Training\nfrom sklearn import svm\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score, classification_report\nfrom sklearn.model_selection import learning_curve","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:14:55.152096Z","iopub.execute_input":"2022-06-01T17:14:55.152591Z","iopub.status.idle":"2022-06-01T17:14:55.162310Z","shell.execute_reply.started":"2022-06-01T17:14:55.152558Z","shell.execute_reply":"2022-06-01T17:14:55.161403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntest = pd.read_csv('../input/digit-recognizer/test.csv')\ntraining_data = pd.read_csv('../input/digit-recognizer/train.csv')","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:14:55.163419Z","iopub.execute_input":"2022-06-01T17:14:55.163828Z","iopub.status.idle":"2022-06-01T17:15:02.263654Z","shell.execute_reply.started":"2022-06-01T17:14:55.163799Z","shell.execute_reply":"2022-06-01T17:15:02.262716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_label = train['label']\ntrain","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:02.265391Z","iopub.execute_input":"2022-06-01T17:15:02.265737Z","iopub.status.idle":"2022-06-01T17:15:02.293688Z","shell.execute_reply.started":"2022-06-01T17:15:02.265707Z","shell.execute_reply":"2022-06-01T17:15:02.292848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# No. of Rows & Columns\ntrain.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:02.294885Z","iopub.execute_input":"2022-06-01T17:15:02.295230Z","iopub.status.idle":"2022-06-01T17:15:02.301105Z","shell.execute_reply.started":"2022-06-01T17:15:02.295201Z","shell.execute_reply":"2022-06-01T17:15:02.300258Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Creation of Pie Chart\ndef create_pie(df, target_variable, figsize=(10, 10)):\n    print(df[target_variable].value_counts())\n    fig, ax = plt.subplots(figsize=figsize)\n    ax.pie(df[target_variable].value_counts().values, labels=df[target_variable].value_counts().index, autopct='%1.2f%%', textprops={'fontsize': 10})\n    ax.axis('equal')\n    plt.title(target_variable)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:02.302410Z","iopub.execute_input":"2022-06-01T17:15:02.302949Z","iopub.status.idle":"2022-06-01T17:15:02.313821Z","shell.execute_reply.started":"2022-06-01T17:15:02.302887Z","shell.execute_reply":"2022-06-01T17:15:02.313078Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(25, 25))\ncreate_pie(train, 'label')","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:02.315176Z","iopub.execute_input":"2022-06-01T17:15:02.315591Z","iopub.status.idle":"2022-06-01T17:15:02.533479Z","shell.execute_reply.started":"2022-06-01T17:15:02.315555Z","shell.execute_reply":"2022-06-01T17:15:02.532519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# drop - for dropping entire columns/row of specific attribute value\ncp = train.drop(['label'], axis=1)\nratio = int(math.sqrt(cp.shape[1]))","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:02.534911Z","iopub.execute_input":"2022-06-01T17:15:02.535697Z","iopub.status.idle":"2022-06-01T17:15:02.627197Z","shell.execute_reply.started":"2022-06-01T17:15:02.535648Z","shell.execute_reply":"2022-06-01T17:15:02.626085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = train.drop(['label'], axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:02.630935Z","iopub.execute_input":"2022-06-01T17:15:02.631356Z","iopub.status.idle":"2022-06-01T17:15:02.720881Z","shell.execute_reply.started":"2022-06-01T17:15:02.631321Z","shell.execute_reply":"2022-06-01T17:15:02.719942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_first=train.iloc[10]\nimage_first=np.array(image_first).reshape(ratio,ratio)\nplt.imshow(image_first)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:02.722100Z","iopub.execute_input":"2022-06-01T17:15:02.722482Z","iopub.status.idle":"2022-06-01T17:15:02.862161Z","shell.execute_reply.started":"2022-06-01T17:15:02.722449Z","shell.execute_reply":"2022-06-01T17:15:02.861206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# trying to see 9 first images\nplt.figure(figsize=(25, 25))\ncolumns = 3\nfirsts_image = train.iloc[:10]\n\n\nfor i in range(0, 9):\n    image = np.array(train.iloc[i]).reshape(ratio, ratio)\n    \n    plt.subplot(int( firsts_image.shape[0]/ columns + 1), columns, i + 1)\n    plt.imshow(image, cmap='Greens')","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:02.863731Z","iopub.execute_input":"2022-06-01T17:15:02.864352Z","iopub.status.idle":"2022-06-01T17:15:03.879887Z","shell.execute_reply.started":"2022-06-01T17:15:02.864304Z","shell.execute_reply":"2022-06-01T17:15:03.878807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3. Model Preparation","metadata":{}},{"cell_type":"code","source":"X = train\ny = train_label.to_list()\nX = train[:1000]\ny = train_label[:1000].to_list()\nX = X / 255.0\n# split our data into train and test\nX_train, X_test, y_train, y_test = train_test_split( X, y,\n                                                    test_size=0.3,\n                                                    random_state=42)\n# and we also need a validation set \nX_test, X_val, y_test, y_val = train_test_split( X_test, y_test,\n                                                    test_size=0.3,\n                                                    random_state=42)\n# Parameter Grid\nparam_grid = {'kernel':['linear', 'poly'],# 'rbf', 'sigmoid'],\n              'degree':[1, 2,],\n              'gamma': [0.01, 0.1],\n              'coef0': [0.5, 1]\n             }\ngrid = GridSearchCV(svm.SVC(), param_grid, cv=3)\ngrid.fit(X_train, y_train)\nmodel = grid.best_estimator_\nx_pred = model.predict(X_test)\nmodel.score(X_test, y_test)\nprint('prediction: \\n', x_pred)\nconfusion_matrix(y_test, model.predict(X_test))","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:03.881563Z","iopub.execute_input":"2022-06-01T17:15:03.882274Z","iopub.status.idle":"2022-06-01T17:15:08.455139Z","shell.execute_reply.started":"2022-06-01T17:15:03.882228Z","shell.execute_reply":"2022-06-01T17:15:08.454290Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## Classsification report","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:08.456384Z","iopub.execute_input":"2022-06-01T17:15:08.456770Z","iopub.status.idle":"2022-06-01T17:15:08.461094Z","shell.execute_reply.started":"2022-06-01T17:15:08.456738Z","shell.execute_reply":"2022-06-01T17:15:08.460184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_prediction = model.predict(X_test)\nprint(f'test accuracy: \\t{accuracy_score(y_test,X_prediction)}')\nprint(f'{classification_report(y_test, X_prediction)}')","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:08.462209Z","iopub.execute_input":"2022-06-01T17:15:08.462505Z","iopub.status.idle":"2022-06-01T17:15:08.520487Z","shell.execute_reply.started":"2022-06-01T17:15:08.462472Z","shell.execute_reply":"2022-06-01T17:15:08.519738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"## better training of model led to good result so i used mniset dataset from keras for training model along with given data to get best accuracy","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Data Expansion\nfrom sklearn.datasets import load_digits\nimport tensorflow as tf\nfrom tensorflow.keras.datasets.mnist import load_data\n\npath = '../input/mnistpy/mnist.npz'\nimport numpy as np\n\nwith np.load(path, allow_pickle=True) as f:\n    X_train, y_train = f['x_train'], f['y_train']\n    X_test, y_test = f['x_test'], f['y_test']","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:08.521394Z","iopub.execute_input":"2022-06-01T17:15:08.522040Z","iopub.status.idle":"2022-06-01T17:15:08.818732Z","shell.execute_reply.started":"2022-06-01T17:15:08.522005Z","shell.execute_reply":"2022-06-01T17:15:08.817959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\n\ntrain_label = train['label']\n","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:08.819699Z","iopub.execute_input":"2022-06-01T17:15:08.820606Z","iopub.status.idle":"2022-06-01T17:15:11.532404Z","shell.execute_reply.started":"2022-06-01T17:15:08.820569Z","shell.execute_reply":"2022-06-01T17:15:11.531459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"digit_data = X_train\ndigit_target = y_train","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:11.533553Z","iopub.execute_input":"2022-06-01T17:15:11.533880Z","iopub.status.idle":"2022-06-01T17:15:11.539330Z","shell.execute_reply.started":"2022-06-01T17:15:11.533850Z","shell.execute_reply":"2022-06-01T17:15:11.538101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(X_train.shape)\nprint(X_test.shape)\n\nX_trainB = np.append(X_train, X_test).reshape(-1, 28 * 28)\nprint(X_trainB.shape)\n\ny_trainB = np.append(y_train, y_test)\nprint(y_trainB.shape)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:11.540706Z","iopub.execute_input":"2022-06-01T17:15:11.541273Z","iopub.status.idle":"2022-06-01T17:15:11.577267Z","shell.execute_reply.started":"2022-06-01T17:15:11.541239Z","shell.execute_reply":"2022-06-01T17:15:11.576479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntrain_label = train['label']\ntrain = train.drop(['label'], axis=1)\n\nX_train = np.append(X_trainB, train).reshape(-1, 28 * 28)\nprint(X_train.shape)\n\ny_train = np.append(y_trainB, train_label)\nprint(y_train.shape)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:11.578210Z","iopub.execute_input":"2022-06-01T17:15:11.579310Z","iopub.status.idle":"2022-06-01T17:15:14.695073Z","shell.execute_reply.started":"2022-06-01T17:15:11.579267Z","shell.execute_reply":"2022-06-01T17:15:14.694042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = X_train\ny = y_train\n\nX = X / 255.0\n","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:14.696351Z","iopub.execute_input":"2022-06-01T17:15:14.696811Z","iopub.status.idle":"2022-06-01T17:15:14.994151Z","shell.execute_reply.started":"2022-06-01T17:15:14.696778Z","shell.execute_reply":"2022-06-01T17:15:14.993197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SVM = svm.SVC(gamma=0.1, coef0=1, kernel='poly', degree=2)\nSVM.fit(X, y) ","metadata":{"execution":{"iopub.status.busy":"2022-06-01T17:15:14.995492Z","iopub.execute_input":"2022-06-01T17:15:14.995803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# trying to see 20 first images\nplt.figure(figsize=(25, 25))\ncolumns = 3\nfirsts_image = test.iloc[:20]\n\n\nfor i in range(0, 20):\n    image = np.array(test.iloc[i]).reshape(ratio, ratio)\n    \n    plt.subplot(int( firsts_image.shape[0]/ columns + 1), columns, i + 1)\n    plt.imshow(image, cmap='Purples')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_submit = test.copy()\nx_submit = x_submit / 255.0","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Submission","metadata":{}},{"cell_type":"code","source":"X_prediction = SVM.predict(x_submit)\nprint('prediction: \\n', X_prediction)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = pd.Series(X_prediction, name='Label')\npred.head()\n\nindex_list = []\n\nfor i, item in enumerate(pred):\n    index_list.append(i+1)\n    \nimage_id = pd.Series(index_list, name='ImageId')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submit = pd.concat([image_id, pred], axis=1)\nsubmit.to_csv('digit_classifier.csv', index=False)\nsubmit.tail()\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}