{"cells":[{"metadata":{},"cell_type":"markdown","source":"There are several kernels that use brute force feature engineering that achieve better LB scores than this one but some of the features are not easy to understand from a physical point-of-view. In this kernel I only use distances and atom types to derive features that are easy to visualize n one's head (I hope). Then I use LightGBM to predict the scalar coupling constant. Also, to estimate the LB score I use training and validation sets which do not contain the same molecules."},{"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","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"from scipy.stats import skew, kurtosis\nfrom numpy.random import permutation\nfrom sklearn import metrics\nimport lightgbm\nfrom sklearn.preprocessing import LabelEncoder","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\nsub = pd.read_csv('../input/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# split type\ntrain['type_0'] = train['type'].apply(lambda x: x[0])\ntrain['type_1'] = train['type'].apply(lambda x: x[1:])\ntest['type_0'] = test['type'].apply(lambda x: x[0])\ntest['type_1'] = test['type'].apply(lambda x: x[1:])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import xyz data\nstructures = pd.read_csv('../input/structures.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# map atom_index_{0|1} to x_0, ..., z_1\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# get xyz data for each atom\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":"# (x,y,z) for atom_0 and atom_1 as numpy arrays\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# distance between atom_0 and atom_1\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":"# distances between atom_0 and atom_1 along each axis\ntrain['dist_x'] = (train['x_0'] - train['x_1']) ** 2\ntest['dist_x'] = (test['x_0'] - test['x_1']) ** 2\ntrain['dist_y'] = (train['y_0'] - train['y_1']) ** 2\ntest['dist_y'] = (test['y_0'] - test['y_1']) ** 2\ntrain['dist_z'] = (train['z_0'] - train['z_1']) ** 2\ntest['dist_z'] = (test['z_0'] - test['z_1']) ** 2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# distance/mean(distance) by type\ntrain['dist_to_type_mean'] = train['dist'] / train.groupby('type')['dist'].transform('mean')\ntest['dist_to_type_mean'] = test['dist'] / test.groupby('type')['dist'].transform('mean')\n\n# distance/mean(distance) by type_0\ntrain['dist_to_type_0_mean'] = train['dist'] / train.groupby('type_0')['dist'].transform('mean')\ntest['dist_to_type_0_mean'] = test['dist'] / test.groupby('type_0')['dist'].transform('mean')\n\n# distance/mean(distance) by type_1\ntrain['dist_to_type_1_mean'] = train['dist'] / train.groupby('type_1')['dist'].transform('mean')\ntest['dist_to_type_1_mean'] = test['dist'] / test.groupby('type_1')['dist'].transform('mean')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# statistics of dist by molecule\ndef mol_dist_stats(df):\n    dist_mean = df.groupby('molecule_name')['dist'].apply(np.mean).reset_index()\n    dist_mean.rename({'dist': 'molecule_dist_mean'}, axis=1, inplace=True)\n    df = pd.merge(df, dist_mean, how='left', on='molecule_name')\n    dist_std = df.groupby('molecule_name')['dist'].apply(np.std).reset_index()\n    dist_std.rename({'dist': 'molecule_dist_std'}, axis=1, inplace=True)\n    df = pd.merge(df, dist_std, how='left', on='molecule_name')\n    dist_skew = df.groupby('molecule_name')['dist'].apply(skew).reset_index()\n    dist_skew.rename({'dist': 'molecule_dist_skew'}, axis=1, inplace=True)\n    df = pd.merge(df, dist_skew, how='left', on='molecule_name')\n    dist_kurt = df.groupby('molecule_name')['dist'].apply(kurtosis).reset_index()\n    dist_kurt.rename({'dist': 'molecule_dist_kurt'}, axis=1, inplace=True)\n    df = pd.merge(df, dist_kurt, how='left', on='molecule_name')\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# add distance statistics by molecule\ntrain = mol_dist_stats(train)\ntest = mol_dist_stats(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# distance to centre of molecule\nmeanx = structures.groupby('molecule_name')['x'].apply(np.mean).reset_index()\nmeanx.rename({'x': 'meanx'}, axis=1, inplace=True)\ntrain = pd.merge(train, meanx, how='left', on='molecule_name')\ntest = pd.merge(test, meanx, how='left', on='molecule_name')\n\nmeany = structures.groupby('molecule_name')['y'].apply(np.mean).reset_index()\nmeany.rename({'y': 'meany'}, axis=1, inplace=True)\ntrain = pd.merge(train, meany, how='left', on='molecule_name')\ntest = pd.merge(test, meany, how='left', on='molecule_name')\n\nmeanz = structures.groupby('molecule_name')['z'].apply(np.mean).reset_index()\nmeanz.rename({'z': 'meanz'}, axis=1, inplace=True)\ntrain = pd.merge(train, meanz, how='left', on='molecule_name')\ntest = pd.merge(test, meanz, how='left', on='molecule_name')\n\ntrain_p_m = train[['meanx', 'meany', 'meanz']].values\ntest_p_m = test[['meanx', 'meany', 'meanz']].values\n\ntrain['dist_0tomean'] = np.linalg.norm(train_p_0 - train_p_m, axis=1)\ntrain['dist_1tomean'] = np.linalg.norm(train_p_1 - train_p_m, axis=1)\ntest['dist_0tomean'] = np.linalg.norm(test_p_0 - test_p_m, axis=1)\ntest['dist_1tomean'] = np.linalg.norm(test_p_1 - test_p_m, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# distance to centre of each atom type in molecule\n# this could perhaps be weighted by properties of the respective atoms, such as no. electrons\natoms = ['H', 'C', 'N', 'O', 'F']\nfor atom in atoms:\n    meanx = structures[structures['atom']==atom].groupby('molecule_name')['x'].apply(np.mean).reset_index()\n    meanx.rename({'x': 'meanx' + atom}, axis=1, inplace=True)\n    train = pd.merge(train, meanx, how='left', on='molecule_name')\n    test = pd.merge(test, meanx, how='left', on='molecule_name')\n\n    meany = structures[structures['atom']==atom].groupby('molecule_name')['y'].apply(np.mean).reset_index()\n    meany.rename({'y': 'meany' + atom}, axis=1, inplace=True)\n    train = pd.merge(train, meany, how='left', on='molecule_name')\n    test = pd.merge(test, meany, how='left', on='molecule_name')\n\n    meanz = structures[structures['atom']==atom].groupby('molecule_name')['z'].apply(np.mean).reset_index()\n    meanz.rename({'z': 'meanz' + atom}, axis=1, inplace=True)\n    train = pd.merge(train, meanz, how='left', on='molecule_name')\n    test = pd.merge(test, meanz, how='left', on='molecule_name')\n\n    train_p_m = train[['meanx' + atom, 'meany' + atom, 'meanz' + atom]].values\n    test_p_m = test[['meanx' + atom, 'meany' + atom, 'meanz' + atom]].values\n\n    train['dist_0tomean' + atom] = np.linalg.norm(train_p_0 - train_p_m, axis=1)\n    train['dist_1tomean' + atom] = np.linalg.norm(train_p_1 - train_p_m, axis=1)\n    test['dist_0tomean' + atom] = np.linalg.norm(test_p_0 - test_p_m, axis=1)\n    test['dist_1tomean' + atom] = np.linalg.norm(test_p_1 - test_p_m, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# no. atoms in each molecule (not a distance feature, but needed below)\natom_cnt = structures['molecule_name'].value_counts().reset_index(level=0)\natom_cnt.rename({'index': 'molecule_name', 'molecule_name': 'atom_count'}, axis=1, inplace=True)\ntrain = pd.merge(train, atom_cnt, how='left', on='molecule_name')\ntest = pd.merge(test, atom_cnt, how='left', on='molecule_name')\ndel atom_cnt","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":"# distance to nearest neighbours (by atom_index)\n# if there is no atom to the \"left\" (respectively \"right\") of the atom of interest, then the distance is zero but this could be coded as NA\ndef lrdist(df):\n    # left and right indices - 0\n    df['atom_index_0l'] = df['atom_index_0'].apply(lambda i: max(i - 1, 0))\n    tmp = df[['atom_index_0', 'atom_count']]\n    df['atom_index_0r'] = tmp.apply(lambda row: min(row['atom_index_0'] + 1, row['atom_count']), axis=1)\n    # (x,y,z) of left and right indices\n    df = map_atom_info(df, '0l')\n    df = map_atom_info(df, '0r')\n    # (x,y,z) for atom_0 and atom_1 as numpy arrays\n    df_p_0l = df[['x_0l', 'y_0l', 'z_0l']].values\n    df_p_0r = df[['x_0r', 'y_0r', 'z_0r']].values\n    # distance between atom_0 and atom_1\n    df_p_0 = df[['x_0', 'y_0', 'z_0']].values\n    df['dist_0l'] = np.linalg.norm(df_p_0l - df_p_0, axis=1)\n    df['dist_0r'] = np.linalg.norm(df_p_0r - df_p_0, axis=1)\n    df.drop(['atom_index_0l', 'atom_index_0r'], axis=1, inplace=True)\n    # left and right indices - 1\n    df['atom_index_1l'] = df['atom_index_1'].apply(lambda i: max(i - 1, 0))\n    tmp = df[['atom_index_1', 'atom_count']]\n    df['atom_index_1r'] = tmp.apply(lambda row: min(row['atom_index_1'] + 1, row['atom_count']), axis=1)\n    # (x,y,z) of left and right indices\n    df = map_atom_info(df, '1l')\n    df = map_atom_info(df, '1r')\n    # (x,y,z) for atom_1 and atom_1 as numpy arrays\n    df_p_1l = df[['x_1l', 'y_1l', 'z_1l']].values\n    df_p_1r = df[['x_1r', 'y_1r', 'z_1r']].values\n    # distance between atom_1 and atom_1\n    df_p_1 = df[['x_1', 'y_1', 'z_1']].values\n    df['dist_1l'] = np.linalg.norm(df_p_1l - df_p_1, axis=1)\n    df['dist_1r'] = np.linalg.norm(df_p_1r - df_p_1, axis=1)\n    df.drop(['atom_index_1l', 'atom_index_1r'], axis=1, inplace=True)\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = lrdist(train)\ntest = lrdist(test)","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 (note we have picked up the atom types of the neighbours)\npred_vars = [v for v in train.columns if v not in ['id', 'molecule_name', 'atom_0', 'atom_1',\n                                                   'scalar_coupling_constant']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# encode categorical features as integers for LightGBM\ncat_feats = ['type', 'type_0', 'type_1', 'atom_0l', 'atom_0r', 'atom_1l', 'atom_1r']\nfor f in cat_feats:\n    lbl = LabelEncoder()\n    lbl.fit(list(train[f].values) + list(test[f].values))\n    train[f] = lbl.transform(list(train[f].values))\n    test[f] = lbl.transform(list(test[f].values))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train-val split by molecule_name (since test molecules are disjoint from train molecules)\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":"# 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 & validation\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 performance\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_dist01.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# save features for future use\ntrain[['id'] + pred_vars].to_csv('train_dist.csv', index=False)\ntest[['id'] + pred_vars].to_csv('test_dist.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}