{"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)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\nimport os\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import GroupKFold\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import RandomForestRegressor\n","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', index_col='id')\ntest = pd.read_csv('../input/test.csv', index_col='id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display(train.head())","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":"# 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":"# Engineer a single feature: distance vector between atoms\n#  (there's ways to speed this up!)\n\ndef dist(row):\n    return ( (row['x_1'] - row['x_0'])**2 +\n             (row['y_1'] - row['y_0'])**2 +\n             (row['z_1'] - row['z_0'])**2 ) ** 0.5\n\ntrain['dist'] = train.apply(lambda x: dist(x), axis=1)\ntest['dist'] = test.apply(lambda x: dist(x), axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"molecules = train.pop('molecule_name')\ntest = test.drop('molecule_name', axis=1)\n\ny = train.pop('scalar_coupling_constant')\n\n# Label Encoding\nfor 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":{"trusted":true},"cell_type":"code","source":"yoof = np.zeros(len(train))\nyhat = np.zeros(len(test))\n\nn_splits = 3\ngkf = GroupKFold(n_splits=n_splits) # we're going to split folds by molecules\n\nfold = 0\nfor in_index, oof_index in gkf.split(train, y, groups=molecules):\n    fold += 1\n    print(f'fold {fold} of {n_splits}')\n    X_in, X_oof = train.values[in_index], train.values[oof_index]\n    y_in, y_oof = y.values[in_index], y.values[oof_index]\n    reg = RandomForestRegressor(n_estimators=250,\n                                max_depth=9,\n                                min_samples_leaf=3,\n                                n_jobs=-1)\n    reg.fit(X_in, y_in)\n    yoof[oof_index] = reg.predict(X_oof)\n    yhat += reg.predict(test)\n\nyhat /= n_splits","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv('../input/sample_submission.csv', index_col='id')\n\nbenchmark = sample_submission.copy()\nbenchmark['scalar_coupling_constant'] = yhat\nbenchmark.to_csv('atomic_distance_benchmark.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_data = pd.DataFrame(y)\nplot_data.index.name = 'id'\nplot_data['yhat'] = yoof\nplot_data['type'] = pd.read_csv('../input/train.csv', index_col='id', usecols=['id', 'type'])\n\ndef plot_oof_preds(ctype, llim, ulim):\n        plt.figure(figsize=(6,6))\n        sns.scatterplot(x='scalar_coupling_constant',y='yhat',\n                        data=plot_data.loc[plot_data['type']==ctype,\n                        ['scalar_coupling_constant', 'yhat']]);\n        plt.xlim((llim, ulim))\n        plt.ylim((llim, ulim))\n        plt.plot([llim, ulim], [llim, ulim])\n        plt.xlabel('scalar_coupling_constant')\n        plt.ylabel('predicted')\n        plt.title(f'{ctype}', fontsize=18)\n        plt.show()\n\nplot_oof_preds('1JHC', 0, 250)\nplot_oof_preds('1JHN', 0, 100)\nplot_oof_preds('2JHC', -50, 50)\nplot_oof_preds('2JHH', -50, 50)\nplot_oof_preds('2JHN', -25, 25)\nplot_oof_preds('3JHC', -25, 100)\nplot_oof_preds('3JHH', -20, 20)\nplot_oof_preds('3JHN', -15, 15)","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}