{"cells":[{"metadata":{},"cell_type":"markdown","source":"### Based on Kernels: \n\nhttps://www.kaggle.com/khoongweihao/ashrae-leak-validation-bruteforce-heuristic-search\n\nhttps://www.kaggle.com/roydatascience/ashrae-stratified-kfold-lightgbm\n"},{"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 \nimport pandas as pd \n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\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\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_squared_error","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 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')\ntrain_df = pd.read_feather(root/'train.feather')\ntest_df = pd.read_feather(root/'test.feather')\nbuilding_meta_df = pd.read_feather(root/'building_metadata.feather')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_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 \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 without leaks"},{"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)\nsample_submission4 = pd.read_csv('../input/stratifiedkfoldlgbxopy/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\ntest_df['pred4'] = sample_submission4.meter_reading\n\ntest_df.loc[test_df.pred3<0, 'pred3'] = 0 \ntest_df.loc[test_df.pred3<0, 'pred4'] = 0 \n\ndel  sample_submission1,  sample_submission2,  sample_submission3, sample_submission4\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', 'pred4', '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['pred4_l1p'] = np.log1p(leak_df.pred4)\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":"# kfold lgbm\nsns.distplot(leak_df.pred4_l1p)\nsns.distplot(leak_df.meter_reading_l1p)\n\nleak_score = np.sqrt(mean_squared_error(leak_df.pred4_l1p, leak_df.meter_reading_l1p))\nprint ('score4=', leak_score)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Leak Validation for Blending"},{"metadata":{"trusted":true},"cell_type":"code","source":"leak_df['mean_pred'] = np.mean(leak_df[['pred1', 'pred2', 'pred3', 'pred4']].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\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":{},"cell_type":"markdown","source":"# Genetic Algorithm"},{"metadata":{"trusted":true},"cell_type":"code","source":"class GAOptimizer:\n    def __init__(self, function, min_value=0.2, max_value=0.8, population_size=50, dimention=4):\n        self.function = function\n        self.population = np.random.uniform(min_value, max_value, (population_size, dimention))\n        self.population_size = population_size\n        self.dimention = dimention\n        half_dim1 = int(dimention/2)\n        half_dim2 = int(dimention/2) + 1 if dimention%2 else int(dimention/2)\n        self.co_weights = np.hstack([np.ones((population_size, half_dim1)), np.zeros((population_size, half_dim2))])\n        \n    def crossover(self):\n        old_population = np.copy(self.population)\n        population = np.copy(self.population)\n        np.random.shuffle(population)\n        new_population = old_population*self.co_weights + population*(1 - self.co_weights) + np.random.normal(0, 0.1, (self.population_size, self.dimention))\n        \n        return np.vstack([old_population, new_population])\n    \n    def selector(self, n=None):\n        f_values = self.function(self.population)\n        self.population = self.population[np.argsort(f_values)[:self.population_size]]\n        if n:\n            return self.population[np.argsort(f_values)[:n]], self.function(self.population[np.argsort(f_values)[:n]])\n        \n\n    def fit(self, iters):\n        for i in range(iters):\n            self.population = self.crossover()\n            self.selector()\n        return self.selector(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def func_to_opt(scores):\n    score = []\n    for x in scores:\n        v = x[0] * leak_df['pred1'].values + x[1] * leak_df['pred2'].values + \\\n        x[2] * leak_df['pred3'].values + x[3] * leak_df['pred4'].values\n        val  = (v > 0).astype(int)*v\n        vl1p = np.log1p(val)\n        curr_score = np.sqrt(mean_squared_error(vl1p, leak_df.meter_reading_l1p)) \n        score.append(curr_score)\n    return np.array(score)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nga_holder = GAOptimizer(function=lambda l: func_to_opt(l))\nresult = ga_holder.fit(40)  \nprint(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final = result[0].flatten()/result[0].flatten().sum()\nprint(final)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"func_to_opt(np.array([final]))","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\nw1 = final[0]\nw2 = final[1]\nw3 = final[2]\nw4 = final[3]\n\nsample_submission['meter_reading'] = w1 * test_df.pred1 +  w2 * test_df.pred2  + w3 * test_df.pred3 +\\\nw4 * test_df.pred4\nsample_submission.loc[sample_submission.meter_reading < 0, 'meter_reading'] = 0","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":"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.isna().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.to_csv('submission.csv', index=False, float_format='%.5f')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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}