{"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 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.\n\n# importing libraries\n%matplotlib inline\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Loading the training and testing datasets and showing some basic statistics using pandas in-built describe() and info() functions."},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# loading the datasets\n\n# loading the dig-minst.csv file\n\ndigit_df = pd.read_csv(\"/kaggle/input/Kannada-MNIST/Dig-MNIST.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# loding the training data\n\ntrain_df = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# loading the testing data\n\ntest_df = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"digit_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"digit_df.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"digit_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# checking the label distribution using sns - barchart\n\ntrain_df['label'].value_counts().plot(\"bar\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"digit_df['label'].value_counts().plot('bar')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# getting all unique labels\n\npd.unique(train_df['label'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.distplot(train_df['label'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Standardising / normalizing the data and then feed the data into to our model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# removing the label from training data\n\ntrain = train_df.drop(['label'], axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# getting the label as our target data\n\ntarget = train_df['label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"target.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# removing the id from the test dataframe\n\ntest = test_df.drop(\"id\", axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# getting some meta information from our training and testing dataframes\n\nprint(\"No.f rows in train data set: {}\".format(len(train)))\nprint(\"No.f rows in test data set: {}\".format(len(test)))\nprint(\"No.f rows in target data set: {}\".format(len(target)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"No.f columns in train data set: {}\".format(len(train.columns)))\nprint(\"No.f columns in test data set: {}\".format(len(test.columns)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Projecting the data into a 2D plan using - PCA"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.decomposition import PCA\n\npca = PCA(n_components=2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"principal_components = pca.fit_transform(train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"principalDF = pd.DataFrame(data = principal_components,\n                                  columns=[\"Principal Component 1\", \"Principal Component 2\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"finalDF = pd.concat([principalDF, target], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"finalDF.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# visualizing the Mnist data using a 2D plot\n\nfig = plt.figure(figsize = (8,8))\nax = fig.add_subplot(1,1,1) \nplt.xlim([-1500, 1500])\nplt.ylim([-1500, 1500])\nax.set_xlabel('Principal Component 1', fontsize = 15)\nax.set_ylabel('Principal Component 2', fontsize = 15)\nax.set_title('2 component PCA', fontsize = 20)\ntargets = [0, 1, 2, 3, 4, 5, 6]\ncolors = [\"b\", \"g\", \"r\", \"c\", \"m\", \"y\", \"k\"]\nfor label, color in zip(targets, colors):\n    indicesToKeep = finalDF['label'] == label\n    ax.scatter(finalDF.loc[indicesToKeep, 'Principal Component 1'], \n               finalDF.loc[indicesToKeep, 'Principal Component 2'], \n               c = color,\n               s = 50)\nax.legend(targets)\nax.grid()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Standardizing the data\n\nfrom sklearn.preprocessing import StandardScaler\n\nstandard_scaler = StandardScaler()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# transform train and test dataset\n\n# tranforming the training dataset\ntrain_transformed = standard_scaler.fit_transform(train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# tranforming the test dataset\n\ntest_tranformed = standard_scaler.fit_transform(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_transformed[:2]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_tranformed[:2]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# importing sklearn, lgb and other libraries\n\nimport sklearn\nimport lightgbm as lgb\nfrom sklearn import metrics\nfrom sklearn import model_selection\n\n# for hyper parameter tuning we are using hypetopt instead of scikit-learn GridSearchCV\nfrom hyperopt import hp, tpe, fmin, STATUS_OK, Trials","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pca = PCA(0.95)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_transformed = pca.fit_transform(train_transformed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_tranformed = pca.fit_transform(test_tranformed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_features, valid_features, y_train, y_valid = model_selection.train_test_split(train_transformed, target, test_size=0.30, random_state=123456789)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Shape of the train_features data: {}\".format(train_features.shape))\nprint(\"Shape of the valid_features data: {}\".format(valid_features.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Shape of the y_train data: {}\".format(y_train.shape))\nprint(\"Shape of the y_valid data: {}\".format(y_valid.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# scoring and optimizatin function for lightgbm\n\ndef lgb_score(space):\n    print(\"Training with params: {}\".format(space))\n    \n    num_leaves = int(space['num_leaves'])\n    bagging_freq = int(space['bagging_freq'])\n    n_estimators = int(space['n_estimators'])\n    min_data_in_leaf = int(space['min_data_in_leaf'])\n\n    del space['num_leaves']\n    del space['bagging_freq']\n    del space['n_estimators']\n    del space['min_data_in_leaf']\n    \n    clf = lgb.LGBMClassifier(n_estimators=n_estimators,\n                             learning_rate=space['learning_rate'],\n                             min_data_in_leaf=min_data_in_leaf,\n                             bagging_freq=bagging_freq,\n                             min_sum_hessian_in_leaf=space['min_sum_hessian_in_leaf'],\n                             feature_fraction=space['feature_fraction'],\n                             bagging_fraction=space['bagging_fraction'],\n                             num_leaves=num_leaves,\n                             boost_from_average=space['boost_from_average'],\n                             boosting_type='gbdt',\n                             max_depth=-1,\n                             num_threads=8,\n                             verbosity=1,\n                             tree_learner='serial',\n                             objective = \"multiclass\")\n    clf.fit(train_features, y_train, eval_set=[(valid_features, y_valid)], verbose=5000, eval_metric='multi_logloss', early_stopping_rounds=2500)\n    predictions = clf.predict_proba(valid_features)[:, 1]\n    score = metrics.roc_auc_score(y_valid, predictions)\n    \n    return {'loss': 1 - score, 'status': STATUS_OK}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# defining the space\n\ndef optimize(evals, random=42):\n    \n    space = {\n        'n_estimators': hp.uniform('n_estimators', 25000, 35000),\n        'learning_rate': hp.quniform('learning_rate', 0.00075, 0.0099, 0.00015),\n        'min_data_in_leaf': hp.uniform('min_data_in_leaf', 50, 50),\n        'bagging_freq': hp.uniform('bagging_freq', 5, 50),\n        'min_sum_hessian_in_leaf': hp.quniform('min_sum_hessian_in_leaf', 5.0, 75.0, 2.5),\n        'feature_fraction': hp.uniform('feature_fraction', 0.010, 0.095),\n        'bagging_fraction': hp.uniform('bagging_fraction', 0.015, 0.995),\n        'num_leaves': hp.uniform('num_leaves', 50, 100),\n        'boost_from_average': hp.choice('boost_from_average', ['true', 'false'])\n    }\n    \n    best = fmin(lgb_score, space=space, algo=tpe.suggest, max_evals=evals)\n    return best","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"params = optimize(10)","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":1}