{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport matplotlib.pylab as plt\nimport seaborn as sns\nfrom sklearn import metrics\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\nplt.style.use('ggplot')\ncolor_pal = [x['color'] for x in plt.rcParams['axes.prop_cycle']]\n\nimport os\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('../input/sample_submission.csv')\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"structures = pd.read_csv('../input/structures.csv')\ndisplay(structures.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Distribution of the target\ntrain['scalar_coupling_constant'].plot(kind='hist', figsize=(20, 5), bins=1000, title='Distribution of the target scalar coupling constant')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Number of of atoms in molecule\nfig, ax = plt.subplots(1, 2)\ntrain.groupby('molecule_name').count().sort_values('id')['id'].plot(kind='hist',\n                                                                       bins=25,\n                                                                       color=color_pal[6],\n                                                                      figsize=(20, 5),\n                                                                      title='# of Atoms in Molecule (Train Set)',\n                                                                      ax=ax[0])\ntest.groupby('molecule_name').count().sort_values('id')['id'].plot(kind='hist',\n                                                                       bins=25,\n                                                                       color=color_pal[2],\n                                                                      figsize=(20, 5),\n                                                                      title='# of Atoms in Molecule (Test Set)',\n                                                                     ax=ax[1])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Distance Feature**\n\nThis feature was found from @inversion 's kernel here: https://www.kaggle.com/inversion/atomic-distance-benchmark/output\n\nThe code was then made faster by @seriousran here: https://www.kaggle.com/seriousran/just-speed-up-calculate-distance-from-benchmark\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Map the atom structure data into train and test files\n\ndef map_atom_info(df, atom_idx):\n    df = pd.merge(df, structures, how = 'left',\n                  left_on  = ['molecule_name', f'atom_index_{atom_idx}'],\n                  right_on = ['molecule_name',  'atom_index'])\n    \n    df = df.drop('atom_index', axis=1)\n    df = df.rename(columns={'atom': f'atom_{atom_idx}',\n                            'x': f'x_{atom_idx}',\n                            'y': f'y_{atom_idx}',\n                            'z': f'z_{atom_idx}'})\n    return df\n\ntrain = map_atom_info(train, 0)\ntrain = map_atom_info(train, 1)\n\ntest = map_atom_info(test, 0)\ntest = map_atom_info(test, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# Engineer a single feature: distance vector between atoms\n\ntrain_p_0 = train[['x_0', 'y_0', 'z_0']].values\ntrain_p_1 = train[['x_1', 'y_1', 'z_1']].values\ntest_p_0 = test[['x_0', 'y_0', 'z_0']].values\ntest_p_1 = test[['x_1', 'y_1', 'z_1']].values\n\ntrain['dist'] = np.linalg.norm(train_p_0 - train_p_1, axis=1)\ntest['dist'] = np.linalg.norm(test_p_0 - test_p_1, 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":"# Label Encoding\ntrain = pd.get_dummies(data=train, columns=['type','atom_0','atom_1'])\ntest = pd.get_dummies(data=test, columns=['type','atom_0','atom_1'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"atom_count_dict = structures.groupby('molecule_name').count()['atom_index'].to_dict()\n\ntrain['atom_count'] = train['molecule_name'].map(atom_count_dict)\ntest['atom_count'] = test['molecule_name'].map(atom_count_dict)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = train['scalar_coupling_constant'].values\ntrain_data = train.drop(['id','molecule_name','scalar_coupling_constant'], axis=1)\ntest_data = test.drop(['id','molecule_name'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n#splitting into train and test set\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test=train_test_split(train_data, labels, test_size=0.1, random_state=47)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n#Scaling the data\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nsc.fit(pd.concat([train_data,test_data]))\nx_train = sc.transform(x_train)\nx_test = sc.transform(x_test)\ntest_data = sc.transform(test_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Parameters for LightGBM Model\nparams_lgb = {'num_leaves': 128,\n          'min_child_samples': 79,\n          'objective': 'regression',\n          'max_depth': 9,\n          'learning_rate': 0.1,\n          \"boosting_type\": \"gbdt\",\n          \"subsample_freq\": 1,\n          \"subsample\": 0.9,\n          \"bagging_seed\": 47,\n          \"metric\": 'mae',\n          \"verbosity\": -1,\n          'reg_alpha': 0.1302650970728192,\n          'reg_lambda': 0.3603427518866501,\n          'colsample_bytree': 1.0,\n          'n_estimators':10000\n         }","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n#LightGBM Model\nimport lightgbm as lgb\nlgtrain = lgb.Dataset(x_train, label=y_train)\nlgval = lgb.Dataset(x_test, label=y_test)\nmodel_lgb = lgb.train(params_lgb, lgtrain, 5000, \n                  valid_sets=[lgtrain, lgval], \n                  verbose_eval=500)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Submission for LightGBM Model\nlgb_pred = model_lgb.predict(test_data)\nsubmission['scalar_coupling_constant']=lgb_pred\nsubmission.to_csv('lgb_model.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n#CatBoost Model\nfrom catboost import CatBoostRegressor\n\nmodel_cat = CatBoostRegressor(iterations=5000,\n                             learning_rate=0.03,\n                             depth=2,\n                             eval_metric='MAE',\n                             random_seed = 47,\n                             od_wait=5000)\n\nmodel_cat.fit(x_train,y_train, verbose=500)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Submission for CatBoost Model\ncat_pred = model_cat.predict(test_data)\nsubmission['scalar_coupling_constant']=cat_pred\nsubmission.to_csv('cat_model.csv',index=False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}