{"cells":[{"metadata":{},"cell_type":"markdown","source":"In my two previous kernels I created distance features and imputed molecular features on the test data. I now combine these with estimated Mulliken charges computed using Open Babel in a third-party kernel. There is an incremental improvement in predictive performance. "},{"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 the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"cell_type":"code","source":"from numpy.random import permutation\nfrom sklearn import metrics\nimport lightgbm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/champs-scalar-coupling/train.csv')\ntest = pd.read_csv('../input/champs-scalar-coupling/test.csv')\nsub = pd.read_csv('../input/champs-scalar-coupling/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# previously constructed distance features\n# https://www.kaggle.com/robertburbidge/distance-features\ntrain_dist = pd.read_csv('../input/distance-features/train_dist.csv')\ntest_dist = pd.read_csv('../input/distance-features/test_dist.csv')\ntrain = pd.merge(train.drop(['atom_index_0', 'atom_index_1', 'type'], axis=1), train_dist, how='left', on='id')\ntest = pd.merge(test.drop(['atom_index_0', 'atom_index_1', 'type'], axis=1), test_dist, how='left', on='id')\ndel train_dist, test_dist","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# previously imputed molecular features\n# https://www.kaggle.com/robertburbidge/imputing-molecular-features\ntrain_dipole_moment = pd.read_csv('../input/imputing-molecular-features/train_dipole_moment.csv')\ntest_dipole_moment = pd.read_csv('../input/imputing-molecular-features/test_dipole_moment.csv')\ntrain = pd.merge(train, train_dipole_moment, how='left', on='molecule_name')\ntest = pd.merge(test, test_dipole_moment, how='left', on='molecule_name')\ntrain_potential_energy = pd.read_csv('../input/imputing-molecular-features/train_potential_energy.csv')\ntest_potential_energy = pd.read_csv('../input/imputing-molecular-features/test_potential_energy.csv')\ntrain = pd.merge(train, train_potential_energy, how='left', on='molecule_name')\ntest = pd.merge(test, test_potential_energy, how='left', on='molecule_name')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# mulliken charges with Open Babel\n# https://www.kaggle.com/asauve/v7-estimation-of-mulliken-charges-with-open-babel\ntrain_ob_charges = pd.read_csv('../input/v7-estimation-of-mulliken-charges-with-open-babel/train_ob_charges.csv')\ntest_ob_charges = pd.read_csv('../input/v7-estimation-of-mulliken-charges-with-open-babel/test_ob_charges.csv')\ntrain = pd.merge(train, train_ob_charges[['molecule_name', 'atom_index', 'eem']], how='left',\n         left_on=['molecule_name', 'atom_index_0'], right_on=['molecule_name', 'atom_index']).\\\n    rename({'eem': 'eem0'}, axis=1)\ntrain = pd.merge(train, train_ob_charges[['molecule_name', 'atom_index', 'eem']], how='left',\n         left_on=['molecule_name', 'atom_index_1'], right_on=['molecule_name', 'atom_index']).\\\n    rename({'eem': 'eem1'}, axis=1)\ntest = pd.merge(test, test_ob_charges[['molecule_name', 'atom_index', 'eem']], how='left',\n         left_on=['molecule_name', 'atom_index_0'], right_on=['molecule_name', 'atom_index']).\\\n    rename({'eem': 'eem0'}, axis=1)\ntest = pd.merge(test, test_ob_charges[['molecule_name', 'atom_index', 'eem']], how='left',\n         left_on=['molecule_name', 'atom_index_1'], right_on=['molecule_name', 'atom_index']).\\\n    rename({'eem': 'eem1'}, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# https://www.kaggle.com/artgor/artgor-utils\ndef reduce_mem_usage(df, verbose=True):\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() / 1024 ** 2\n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col_type in numerics:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)\n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n    end_mem = df.memory_usage().sum() / 1024 ** 2\n    if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (\n                start_mem - end_mem) / start_mem))\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = reduce_mem_usage(train)\ntest = reduce_mem_usage(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# features for prediction\npred_vars = [v for v in train.columns if v not in ['id', 'molecule_name', 'scalar_coupling_constant',\n                                                   'atom_index_x', 'atom_index_y']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train-val split by molecule_name\nmolecule_names = pd.DataFrame(permutation(train['molecule_name'].unique()),columns=['molecule_name'])\nnm = molecule_names.shape[0]\nntrn = int(0.9*nm)\nnval = int(0.1*nm)\n\ntmp_train = pd.merge(train, molecule_names[0:ntrn], how='right', on='molecule_name')\ntmp_val = pd.merge(train, molecule_names[ntrn:nm], how='right', on='molecule_name')\n\nX_train = tmp_train[pred_vars]\nX_val = tmp_val[pred_vars]\ny_train = tmp_train['scalar_coupling_constant']\ny_val = tmp_val['scalar_coupling_constant']\ndel tmp_train, tmp_val","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# heuristic parameters for LightGBM\nparams = { 'objective': 'regression_l1',\n           'learning_rate': 0.1,\n           'num_leaves': 1023,\n           'num_threads': -1,\n           'bagging_fraction': 0.5,\n           'bagging_freq': 1,\n           'feature_fraction': 0.9,\n           'lambda_l1': 10.0,\n           'max_bin': 255,\n           'min_child_samples': 15,\n           }","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# categorical features picked up from train_dist, already integer-encoded\ncat_feats = ['type', 'type_0', 'type_1', 'atom_0l', 'atom_0r', 'atom_1l', 'atom_1r']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# data for lightgbm\ntrain_data = lightgbm.Dataset(X_train, label=y_train, categorical_feature=cat_feats)\nval_data = lightgbm.Dataset(X_val, label=y_val, categorical_feature=cat_feats)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# training\nmodel = lightgbm.train(params,\n                       train_data,\n                       valid_sets=[train_data, val_data], verbose_eval=500,\n                       num_boost_round=4000,\n                       early_stopping_rounds=100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# evaluation metric for validation\n# https://www.kaggle.com/abhishek/competition-metric\ndef metric(df, preds):\n    df[\"prediction\"] = preds\n    maes = []\n    for t in df.type.unique():\n        y_true = df[df.type==t].scalar_coupling_constant.values \n        y_pred = df[df.type==t].prediction.values\n        mae = np.log(metrics.mean_absolute_error(y_true, y_pred))\n        maes.append(mae)\n    return np.mean(maes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# validation\npreds = model.predict(X_val)\nmetric(pd.concat([X_val, y_val], axis=1), preds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# submission\npreds_sub = model.predict(test[pred_vars])\nsub['scalar_coupling_constant'] = preds_sub\nsub.to_csv('submission_feats_dist_mol_mc01.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}