{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Acknowledgements\n\nOriginal Kernel: https://www.kaggle.com/yamsam/ashrae-leak-validation-and-more/notebook#Leak-Validation-for-public-kernels(not-used-leak-data),\n\nhttps://www.kaggle.com/khoongweihao/ashrae-leak-validation-bruteforce-heuristic-search\n\nAdditions: Added a search method based on gradient update"},{"metadata":{},"cell_type":"markdown","source":"# All we need is Leak Validation(LV) ?\n\n* **if you like this kernel, please upvote original kernels.**\n* update site-4 and site-15\n* Turn GPU on for better performance"},{"metadata":{},"cell_type":"markdown","source":"this kernel is still work in progress, but i hope you can find something usefull from this."},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import gc\nimport os\nfrom pathlib import Path\nimport random\nimport sys\n\nfrom tqdm import tqdm_notebook as tqdm\nimport 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\n\nfrom IPython.core.display import display, HTML\n\n# --- plotly ---\nfrom plotly import tools, subplots\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.express as px\nimport plotly.figure_factory as ff\n\n# --- models ---\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import KFold\nimport lightgbm as lgb\nimport xgboost as xgb\nimport catboost as cb\n\nfrom sklearn.metrics import mean_squared_error","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# Original code from https://www.kaggle.com/gemartin/load-data-reduce-memory-usage by @gemartin\n# Modified to support timestamp type, categorical type\n# Modified to add option to use float16 or not. feather format does not support float16.\nfrom pandas.api.types import is_datetime64_any_dtype as is_datetime\nfrom pandas.api.types import is_categorical_dtype\n\ndef reduce_mem_usage(df, use_float16=False):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        if is_datetime(df[col]) or is_categorical_dtype(df[col]):\n            # skip datetime type or categorical type\n            continue\n        col_type = df[col].dtype\n        \n        if col_type != object:\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 use_float16 and 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        else:\n            df[col] = df[col].astype('category')\n\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nroot = Path('../input/ashrae-feather-format-for-fast-loading')\n\ntrain_df = pd.read_feather(root/'train.feather')\ntest_df = pd.read_feather(root/'test.feather')\n#weather_train_df = pd.read_feather(root/'weather_train.feather')\n#weather_test_df = pd.read_feather(root/'weather_test.feather')\nbuilding_meta_df = pd.read_feather(root/'building_metadata.feather')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# i'm now using my leak data station kernel to shortcut.\nleak_df = pd.read_feather('../input/ashrae-leak-data-station/leak.feather')\n\nleak_df.fillna(0, inplace=True)\nleak_df = leak_df[(leak_df.timestamp.dt.year > 2016) & (leak_df.timestamp.dt.year < 2019)]\nleak_df.loc[leak_df.meter_reading < 0, 'meter_reading'] = 0 # remove large negative values\nleak_df = leak_df[leak_df.building_id!=245]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df.meter.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print (leak_df.duplicated().sum())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print (len(leak_df) / len(train_df))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"! ls ../input","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train_df\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Leak Validation for public kernels(not used leak data)"},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission1 = pd.read_csv('../input/ashrae-kfold-lightgbm-without-leak-1-08/submission.csv', index_col=0)\nsample_submission2 = pd.read_csv('../input/ashrae-half-and-half/submission.csv', index_col=0)\nsample_submission3 = pd.read_csv('../input/ashrae-highway-kernel-route4/submission.csv', index_col=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['pred1'] = sample_submission1.meter_reading\ntest_df['pred2'] = sample_submission2.meter_reading\ntest_df['pred3'] = sample_submission3.meter_reading\n\ntest_df.loc[test_df.pred3<0, 'pred3'] = 0 \n\ndel  sample_submission1,  sample_submission2,  sample_submission3\ngc.collect()\n\ntest_df = reduce_mem_usage(test_df)\nleak_df = reduce_mem_usage(leak_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df = leak_df.merge(test_df[['building_id', 'meter', 'timestamp', 'pred1', 'pred2', 'pred3', 'row_id']], left_on = ['building_id', 'meter', 'timestamp'], right_on = ['building_id', 'meter', 'timestamp'], how = \"left\")\nleak_df = leak_df.merge(building_meta_df[['building_id', 'site_id']], on='building_id', how='left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df['pred1_l1p'] = np.log1p(leak_df.pred1)\nleak_df['pred2_l1p'] = np.log1p(leak_df.pred2)\nleak_df['pred3_l1p'] = np.log1p(leak_df.pred3)\nleak_df['meter_reading_l1p'] = np.log1p(leak_df.meter_reading)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df[leak_df.pred1_l1p.isnull()]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ashrae-kfold-lightgbm-without-leak-1-08\nsns.distplot(leak_df.pred1_l1p)\nsns.distplot(leak_df.meter_reading_l1p)\n\nleak_score = np.sqrt(mean_squared_error(leak_df.pred1_l1p, leak_df.meter_reading_l1p))\nprint ('score1=', leak_score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ashrae-half-and-half\nsns.distplot(leak_df.pred2_l1p)\nsns.distplot(leak_df.meter_reading_l1p)\n\nleak_score = np.sqrt(mean_squared_error(leak_df.pred2_l1p, leak_df.meter_reading_l1p))\nprint ('score2=', leak_score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# meter split based\nsns.distplot(leak_df.pred3_l1p)\nsns.distplot(leak_df.meter_reading_l1p)\n\nleak_score = np.sqrt(mean_squared_error(leak_df.pred3_l1p, leak_df.meter_reading_l1p))\nprint ('score3=', leak_score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# ashrae-kfold-lightgbm-without-leak-1-08 looks best","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Leak Validation for Blending"},{"metadata":{},"cell_type":"markdown","source":"A one idea how we can use LV usefull is blending. We probably can find best blending method without LB probing and it's means we can save our submission."},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df['mean_pred'] = np.mean(leak_df[['pred1', 'pred2', 'pred3']].values, axis=1)\nleak_df['mean_pred_l1p'] = np.log1p(leak_df.mean_pred)\nleak_score = np.sqrt(mean_squared_error(leak_df.mean_pred_l1p, leak_df.meter_reading_l1p))\n\n\nsns.distplot(leak_df.mean_pred_l1p)\nsns.distplot(leak_df.meter_reading_l1p)\n\nprint ('mean score=', leak_score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df['median_pred'] = np.median(leak_df[['pred1', 'pred2', 'pred3']].values, axis=1)\nleak_df['median_pred_l1p'] = np.log1p(leak_df.median_pred)\nleak_score = np.sqrt(mean_squared_error(leak_df.median_pred_l1p, leak_df.meter_reading_l1p))\n\nsns.distplot(leak_df.median_pred_l1p)\nsns.distplot(leak_df.meter_reading_l1p)\n\nprint ('meadian score=', leak_score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"Ummm... it looks mean blending is beter than median blending"},{"metadata":{},"cell_type":"markdown","source":"# Find Best Weight"},{"metadata":{"trusted":true},"cell_type":"code","source":"N = 10\nscores = np.zeros(N,)\nfor i in range(N):\n    p = i * 1./N\n    v = p * leak_df['pred1'].values + (1.-p) * leak_df ['pred3'].values\n    vl1p = np.log1p(v)\n    scores[i] = np.sqrt(mean_squared_error(vl1p, leak_df.meter_reading_l1p))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(scores)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_weight = np.argmin(scores) *  1./N\nprint (scores.min(), best_weight)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# and more\nscores = np.zeros(N,)\nfor i in range(N):\n    p = i * 1./N\n    v =  p * (best_weight * leak_df['pred1'].values + (1.-best_weight) * leak_df ['pred3'].values) + (1.-p) * leak_df ['pred2'].values\n    vl1p = np.log1p(v)\n    scores[i] = np.sqrt(mean_squared_error(vl1p, leak_df.meter_reading_l1p))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(scores)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_weight2 = np.argmin(scores) *  1./N\nprint (scores.min(), best_weight2)\n# its seams better than simple mean 0.92079717","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Combination Search by using gradient descent"},{"metadata":{},"cell_type":"markdown","source":"$x$ \\- input \n\n$y$ \\- target\n\n$w$ \\- weights\n\nLet $f(x)=w^\\top x$, we want to minimize\n\n$$L(x,y)=(\\log(f(x)+1)-\\log(y+1))^2$$"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Prepare data\n\nX_train = np.array([leak_df['pred1'].values,leak_df['pred2'].values, leak_df['pred3'].values]).T\ny_train = leak_df.meter_reading_l1p","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"import tensorflow as tf\n\nweights = tf.Variable([[0.3],[0.3],[0.3]])\nsteps = 1000\n\nlr = 0.1\n\nopt = tf.optimizers.SGD(lr)\n\n#Speed up the train step by precompiling\n@tf.function()\ndef train_step(opt):\n    with tf.GradientTape() as tape:\n        y  = tf.matmul(X_train, weights)[:,0]\n        loss = tf.reduce_mean((tf.math.log1p(y) - y_train) ** 2)\n    grads = tape.gradient(loss, weights)\n    opt.apply_gradients([(grads, weights)])\n    \n    return loss\n\nprev_loss = 9999\nfor i in range(steps):\n    loss = train_step(opt)\n    if loss > prev_loss:\n        lr /= 2\n        opt.lr = lr\n        \n    prev_loss = loss\n    print(f'step: {i} {loss.numpy()}')   \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# MSE\nnp.sqrt(loss)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submit"},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_feather(os.path.join(root, 'sample_submission.feather'))\n\nws = weights.numpy()\n\nw1 = ws[0,0]\nw2 = ws[1,0]\nw3 = ws[2,0]\nprint(\"The weights are: w1=\" + str(w1) + \", w2=\" + str(w2) + \", w3=\" + str(w3))\n\nsample_submission['meter_reading'] = w1 * test_df.pred1 +  w2 * test_df.pred2  + w3 * test_df.pred3\nsample_submission.loc[sample_submission.meter_reading < 0, 'meter_reading'] = 0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.distplot(np.log1p(sample_submission.meter_reading))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df = leak_df[['meter_reading', 'row_id']].set_index('row_id').dropna()\nsample_submission.loc[leak_df.index, 'meter_reading'] = leak_df['meter_reading']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.distplot(np.log1p(sample_submission.meter_reading))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.to_csv('submission.csv', index=False, float_format='%.4f')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Future Work\n\n- Do cross-validation on leak data?"}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}