{"cells":[{"metadata":{},"cell_type":"markdown","source":"I hope you will find this notebook useful for understanding how to implement [fastai's tabular model](https://course.fast.ai/videos/?lesson=4). There is a lot of tuning that can still be done, and the only feature that has been engineered is the distance.\n\nI made a slight adjustment to the fastai MAE metric, and I have found that the weighted MAE calculated below seems to give a good approximation of the Public LB.\n\nThanks and please upvote if you find this kernel useful.\n\n* forked. + change mean dist feature"},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport time\nimport datetime\nimport gc\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom IPython.display import HTML\nimport json\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom tqdm import tqdm_notebook\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import NuSVR, SVR\npd.options.display.precision = 10\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold, KFold, RepeatedKFold","execution_count":1,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastai import *\nfrom fastai.imports import *\nfrom fastai.tabular import *\nfrom fastai.metrics import *\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, mean_absolute_error","execution_count":2,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))","execution_count":3,"outputs":[{"output_type":"stream","text":"['test.csv', 'mulliken_charges.csv', 'dipole_moments.csv', 'train.csv', 'structures.csv', 'magnetic_shielding_tensors.csv', 'potential_energy.csv', 'sample_submission.csv', 'scalar_coupling_contributions.csv', 'structures']\n","name":"stdout"}]},{"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')\nsub = pd.read_csv('../input/sample_submission.csv')","execution_count":4,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":5,"outputs":[{"output_type":"execute_result","execution_count":5,"data":{"text/plain":"   id           ...            scalar_coupling_constant\n0   0           ...                             84.8076\n1   1           ...                            -11.2570\n2   2           ...                            -11.2548\n3   3           ...                            -11.2543\n4   4           ...                             84.8074\n\n[5 rows x 6 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>id</th>\n      <th>molecule_name</th>\n      <th>atom_index_0</th>\n      <th>atom_index_1</th>\n      <th>type</th>\n      <th>scalar_coupling_constant</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0</td>\n      <td>dsgdb9nsd_000001</td>\n      <td>1</td>\n      <td>0</td>\n      <td>1JHC</td>\n      <td>84.8076</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>1</td>\n      <td>dsgdb9nsd_000001</td>\n      <td>1</td>\n      <td>2</td>\n      <td>2JHH</td>\n      <td>-11.2570</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>dsgdb9nsd_000001</td>\n      <td>1</td>\n      <td>3</td>\n      <td>2JHH</td>\n      <td>-11.2548</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>dsgdb9nsd_000001</td>\n      <td>1</td>\n      <td>4</td>\n      <td>2JHH</td>\n      <td>-11.2543</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>4</td>\n      <td>dsgdb9nsd_000001</td>\n      <td>2</td>\n      <td>0</td>\n      <td>1JHC</td>\n      <td>84.8074</td>\n    </tr>\n  </tbody>\n</table>\n</div>"},"metadata":{}}]},{"metadata":{"trusted":true},"cell_type":"code","source":"structures = pd.read_csv('../input/structures.csv')\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":6,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Einsum distance calculation borrowed from: https://www.kaggle.com/rakibilly/faster-distance-calculation-from-benchmark"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\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\ntr_a_min_b = train_p_0 - train_p_1\nte_a_min_b = test_p_0 - test_p_1\n\ntrain['dist'] = np.sqrt(np.einsum('ij,ij->i', tr_a_min_b, tr_a_min_b))\ntest['dist'] = np.sqrt(np.einsum('ij,ij->i', te_a_min_b, te_a_min_b))","execution_count":7,"outputs":[{"output_type":"stream","text":"CPU times: user 196 ms, sys: 104 ms, total: 300 ms\nWall time: 300 ms\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"difference of atom indexes. "},{"metadata":{"trusted":true},"cell_type":"code","source":"train[\"index_diff\"] = np.abs(train[\"atom_index_0\"]-train[\"atom_index_1\"])\ntest[\"index_diff\"] = np.abs(test[\"atom_index_0\"]-test[\"atom_index_1\"])","execution_count":8,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Distance to type mean from : [Molecular Properties EDA and models](https://www.kaggle.com/artgor/molecular-properties-eda-and-models)\n\n* Modified to also use aggregation of relative distance (difference of atom indexes)"},{"metadata":{"trusted":true},"cell_type":"code","source":"train['dist_speedup_to_type_mean'] = train['dist'] / train.groupby(['type',\"index_diff\"])['dist'].transform('mean')\ntest['dist_speedup_to_type_mean'] = test['dist'] / test.groupby(['type',\"index_diff\"])['dist'].transform('mean')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for f in ['type', 'atom_0', 'atom_1']:\n    lbl = LabelEncoder()\n    lbl.fit(list(train[f].values) + list(train[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":{},"cell_type":"markdown","source":"Metric calculation from Abhishek's kernel: https://www.kaggle.com/abhishek/competition-metric"},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Start fastai Tabular Learner"},{"metadata":{"trusted":true},"cell_type":"code","source":"tr = train.drop(['id', 'molecule_name'], axis=1)\nte = test.drop(['id', 'molecule_name'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dep_var = 'scalar_coupling_constant'\ncat_names = ['atom_index_0', 'atom_index_1', 'type', 'atom_0', 'atom_1']\ncont_names = tr.columns.tolist()\ncont_names.remove('scalar_coupling_constant')\ncont_names = [e for e in cont_names if e not in (cat_names)]\nprocs = [Categorify, Normalize]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.random.seed(1984)\nidx = np.random.randint(0, len(tr), size=np.int(.2*len(tr)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bs = 4096 \ndata = (TabularList.from_df(tr, \n                            cat_names=cat_names, \n                            cont_names=cont_names, \n                            procs=procs)\n                           .split_by_idx(idx)\n                           .label_from_df(cols=dep_var)\n                           .add_test(TabularList.from_df(te, \n                                                         cat_names=cat_names, \n                                                         cont_names=cont_names))\n                           .databunch(bs=bs))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.show_batch(rows=5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.show_batch(rows=5, ds_type=DatasetType.Valid)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data.show_batch(rows=5, ds_type=DatasetType.Test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def mean_absolute_error_fastai(pred:Tensor, targ:Tensor)->Rank0Tensor:\n    \"Mean absolute error between `pred` and `targ`.\"\n    pred,targ = flatten_check(pred,targ)\n    return F.l1_loss(pred, targ)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn = tabular_learner(data, \n                        layers=[1000,500,100], \n                        emb_drop=0.05,\n                        ps=(0.001, 0.01, 0.1),\n                        metrics=[mean_absolute_error_fastai, rmse], \n                        wd=1e-2).to_fp16()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr_find(learn, start_lr=1e-4, end_lr=10, num_it=100) #, start_lr=1e-2, end_lr=10, num_it=200\nlearn.recorder.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr = 2e-3\nlearn.fit_one_cycle(1, lr, wd=0.9)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(1, lr/4, wd=0.8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(3, lr/10, wd=0.8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(1, lr/10, wd=0.8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(3, lr/20, wd=0.9)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.fit_one_cycle(3, lr/40, wd=0.8)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Check Metrics"},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"val_preds = learn.get_preds(DatasetType.Valid)\ny_true = tr.iloc[idx].scalar_coupling_constant\ny_preds = val_preds[0][:,0].numpy()\ntypes = tr.iloc[idx].type","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"maes = []\nfor t in types.unique():\n    y_t = pd.Series(y_true[types==t])\n    y_p = pd.Series(y_preds[types==t])\n    mae = np.log(mean_absolute_error(y_t, y_p))\n    maes.append(mae)\n\nnp.mean(maes), np.log(mean_absolute_error(y_true, y_preds)), mean_absolute_error(y_true, y_preds)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predict and Submit"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_preds = learn.get_preds(DatasetType.Test)\npreds = test_preds[0].numpy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv('../input/sample_submission.csv')\n\nbenchmark = sample_submission.copy()\nbenchmark['scalar_coupling_constant'] = preds\nbenchmark.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"benchmark.head()","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}