{"cells":[{"metadata":{},"cell_type":"markdown","source":"# A Simple Linear Regression Model\nThe idea is from @abednadir 's great R code. I translate it into a Python one and change a little.\n\n\nIt is not as powerful as a lightgbm model but it still works not so bad! We can use it for model ensembling. \n\n\nHope you never forget this simple model.\n\nData imputation of weather is from [this kernel](https://www.kaggle.com/hmendonca/clean-weather-data-eda).Thanks for sharing!"},{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport datetime\nimport holidays\nimport time\nfrom tqdm.notebook import tqdm\npd.set_option('display.max_columns', None)\nimport gc\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LinearRegression\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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                if 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 * (start_mem - end_mem) / start_mem))\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bd_df = reduce_mem_usage(pd.read_csv(\"/kaggle/input/ashrae/building_metadata.csv\"))\nwt_trn = reduce_mem_usage(pd.read_csv(\"/kaggle/input/ashrae/weather_train.csv\"))\ntrn = reduce_mem_usage(pd.read_csv(\"/kaggle/input/ashrae/train.csv\"))\nts = reduce_mem_usage(pd.read_csv(\"/kaggle/input/ashrae/test.csv\"))\nwt_ts = reduce_mem_usage(pd.read_csv(\"/kaggle/input/ashrae/weather_test.csv\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def add_time(df):\n    df[\"timestamp\"] = pd.to_datetime(df[\"timestamp\"])\n    df[\"hour\"] = df[\"timestamp\"].dt.hour.astype(np.int8)\n    df[\"month\"] = df[\"timestamp\"].dt.month.astype(np.int8)\n    df[\"weekday\"] = df[\"timestamp\"].dt.weekday.astype(np.int8)\n    return df\ntrn = add_time(trn)\nts = add_time(ts)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def add_diff(df):\n    df['tem_diff'] = df['air_temperature'] - df['dew_temperature']\n    return df\nwt_trn = add_diff(wt_trn)\nwt_ts = add_diff(wt_ts)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def tran_pca(df):\n    pca = PCA(n_components = 2)\n    tmp = pca.fit_transform(df[['air_temperature', 'cloud_coverage', 'precip_depth_1_hr', 'wind_speed', 'wind_direction', 'tem_diff']])\n    tmp = pd.DataFrame(tmp, columns = ['component1', 'component2'])\n    df = pd.concat([df, tmp], axis=1, sort=False)\n    return df\nwt_trn = tran_pca(wt_trn)\nwt_ts = tran_pca(wt_ts)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"wt_trn[\"timestamp\"] = wt_trn[\"timestamp\"].astype(str)\nwt_ts[\"timestamp\"] = wt_ts[\"timestamp\"].astype(str)\ntrn[\"timestamp\"] = trn[\"timestamp\"].astype(str)\nts[\"timestamp\"] = ts[\"timestamp\"].astype(str)\n\ntrn = pd.merge(trn, bd_df, how='left', on=['building_id'], suffixes=(False,False))\ntrn = pd.merge(trn, wt_trn, on = ['site_id', 'timestamp'], suffixes=(False, False))\n\nts = pd.merge(ts, bd_df, how='left', on=['building_id'], suffixes=(False,False))\nts = pd.merge(ts, wt_ts, on = ['site_id', 'timestamp'], suffixes=(False, False))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def season_encode(df):\n    df['summer'] = 0\n    df.loc[df.query('month in [6,7,8,9]').index,'summer'] = 1\n    df['winter'] = 0\n    df.loc[df.query('month in [11,12,1,2]').index,'winter'] = 1\n    df['summer'] = df['summer'].astype(np.int8)\n    df['winter'] = df['winter'].astype(np.int8)\n    return df\ntrn = season_encode(trn)\nts = season_encode(ts)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def if_weekend(df):\n    df['M_F'] = 0\n    df.loc[df.query('weekday in [5,6]').index, 'M_F'] = 1\n    df['M_F'] = df['M_F'].astype(np.int8)\n    return df\ntrn = if_weekend(trn)\nts = if_weekend(ts)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trn[\"meter_reading\"] = trn[\"meter_reading\"].clip(upper = trn[\"meter_reading\"].quantile(.975))\ntrn['meter_reading'] = np.log1p(trn['meter_reading'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Drop some outliers."},{"metadata":{"trusted":true},"cell_type":"code","source":"trn = trn.query('not (building_id <= 104 & meter == 0 & timestamp <= \"2016-05-20\")')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trn = trn[['building_id', 'meter', 'hour', 'M_F',  'winter', 'component1', 'component2', 'summer', 'meter_reading']]\nts = ts[['building_id', 'meter', 'hour', 'M_F', 'winter', 'component1', 'component2', 'summer']]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The essence is this groupby operation! You can try other ways to divide data into different groups.\n\nChange sample_time and uncomment the if code if you want to sample some training data and get a mean output(like bagging)."},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_time = 1\ny_pred = np.zeros(len(ts))\nscore = 0\nfor i in range(sample_time):\n    models = []\n    trn_group = trn.groupby(['building_id', 'meter', 'hour','M_F'])\n    ts_group = ts.groupby(['building_id', 'meter', 'hour', 'M_F'])\n    for group in tqdm(trn_group.groups.keys()):\n        df = trn_group.get_group(group)\n#         if len(df)>20:\n#             df = df.sample(frac=0.5, random_state=i)\n        X = pd.concat([\n                        df['component1'], \n                        df['component2'],\n                       df['summer'],\n                       df['winter'],\n                       df['component1']*df['summer'], \n                       df['component1']*df['winter']],axis=1)\n        y = df['meter_reading']\n        scaler = MinMaxScaler()\n        scaler.fit(X)\n        X = scaler.transform(X)\n        model = LinearRegression(n_jobs=-1)\n        model.fit(X, y)\n        \n        df = ts_group.get_group(group)\n        X = pd.concat([\n                        df['component1'], \n                        df['component2'],\n                       df['summer'],\n                       df['winter'],\n                       df['component1']*df['summer'], \n                       df['component1']*df['winter']],axis=1)\n        idx = X.index\n        X = scaler.transform(X)\n        tmp = model.predict(X)/sample_time\n        tmp = np.clip(tmp, 0, y.max()*1.3)\n        y_pred[idx] += tmp","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv('/kaggle/input/ashrae/sample_submission.csv')\nsample_submission['meter_reading'] = np.expm1(y_pred)\nsample_submission.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.distplot(np.log1p(sample_submission['meter_reading']))","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.5"}},"nbformat":4,"nbformat_minor":1}