{"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\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/digit-recognizer'):\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\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC  # Support Vector Classification\nfrom skimage.feature import hog\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score\n\ntrain = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\nX_train_split = train.drop(['label'], axis=1).copy()\nY_train_split = train['label'].copy()\n\nX_train, X_validation, Y_train, Y_validation = train_test_split(X_train_split, Y_train_split, test_size=0.1,\n                                                                random_state=42)\ndel X_train_split, Y_train_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_digit = X_train.iloc[2000]  # a random instance\nsample_digit_image = sample_digit.values.reshape(28, 28)  # reshape it from (784,) to (28,28)\nplt.imshow(sample_digit_image,  # plot it as an image\n           cmap=matplotlib.cm.binary,\n           interpolation=\"nearest\")\nplt.axis(\"off\")\nplt.show()\n\nX_train /= 255.0\nX_validation /= 255.0\ntest /= 255.0","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"code","source":"# Below lines calculate the best value of K to be used in KNN Classifier\nvalue = len(X_validation)\nvalue = int(pow(value, 0.25))\nif value % 2 == 0:\n    value += 1\nprint(value)\n\n# Below lines predict the accuracy of the Digits using KNN Classifier\nkn_clf = KNeighborsClassifier(n_neighbors=value)\nkn_clf.fit(X_train, Y_train)\n\nknn_prediction = kn_clf.predict(X_validation)\nprint(\"KNN Accuracy:\", accuracy_score(y_true=Y_validation, y_pred=knn_prediction))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Below lines predict the accuracy of the Digits using MLP Classifier\nmlp_clf = MLPClassifier(hidden_layer_sizes=(300,), learning_rate_init=0.001, solver='adam',\n                        random_state=42, verbose=True)\nmlp_clf.fit(X_train, Y_train)\n\nmlp_prediction = mlp_clf.predict(X_validation)\nprint(\"MLP Accuracy:\", accuracy_score(y_true=Y_validation, y_pred=mlp_prediction))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Below lines predict the accuracy of the Digits using SVM Classifier\nsvc_clf = SVC(gamma='auto', random_state=42, verbose=True)\nsvc_clf.fit(X_train, Y_train)\n\nsvc_prediction = svc_clf.predict(X_validation)\nprint(\"SVC Accuracy:\", accuracy_score(y_true=Y_validation, y_pred=svc_prediction))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Below lines predict the accuracy of the Digits using SVM-HOG Classifier\nlist_hog_fd = []\nfor feature in X_train.values:\n    fd = hog(feature.reshape((28, 28)), orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1))\n    list_hog_fd.append(fd)\nhog_features = np.array(list_hog_fd, 'float64')\n\nclf = LinearSVC()\nclf.fit(hog_features, y_train)\n\nlist_hog_fd1 = []\nfor feature in X_validation.values:\n    fd = hog(feature.reshape((28, 28)), orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1))\n    list_hog_fd1.append(fd)\nhog_features = np.array(list_hog_fd1, 'float64')\n\nsvc_hog = clf.predict(hog_features)\nprint(\"SVC with HOG Accuracy:\", accuracy_score(y_true=y_validation, y_pred=svc_hog))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"BELOW LINES ARE USED TO PREDICT ACCURACY ON TEST DATA","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Below code creates a csv file for Kaggle submission on Test Data for KNN Classifier\n\nfinal_prediction = kn_clf.predict(test)\nsubmission = pd.DataFrame({\"ImageId\": list(range(1, len(final_prediction) + 1)),\n                         \"Label\": final_prediction})\nsubmission.to_csv(\"/kaggle/working/knn_mnist_submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Below code creates a csv file for Kaggle submission on Test Data for MLP Classifier\n\nfinal_prediction = mlp_clf.predict(test)\nsubmission = pd.DataFrame({\"ImageId\": list(range(1, len(final_prediction) + 1)),\n                          \"Label\": final_prediction})\nsubmission.to_csv(\"/kaggle/working/cnn_mnist_submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Below code creates a csv file for Kaggle submission on Test Data for SVM Classifier\n\nfinal_prediction = svc_clf.predict(test)\nsubmission = pd.DataFrame({\"ImageId\": list(range(1, len(final_prediction) + 1)),\n                          \"Label\": final_prediction})\nsubmission.to_csv(\"/kaggle/working/svm_mnist_submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Below code creates a csv file for Kaggle submission on Test Data for SVM-HOG Classifier\n\nlist_hog_fd2 = []\nfor feature2 in test.values:\n   fd1 = hog(feature2.reshape((28, 28)), orientations=9, pixels_per_cell=(14, 14), cells_per_block=(1, 1))\n   list_hog_fd2.append(fd1)\nhog_features2 = np.array(list_hog_fd2, 'float64')\n\nfinal_prediction = clf.predict(hog_features2)\nsubmission = pd.DataFrame({\"ImageId\": list(range(1, len(final_prediction) + 1)),\n                         \"Label\": final_prediction})\nsubmission.to_csv(\"/kaggle/working/svmHog_mnist_submission.csv\", index=False)","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}