{"cells":[{"metadata":{},"cell_type":"markdown","source":"ASHRAE - GREAT ENERGY PREDICTOR III \n\nSources: \n- https://www.kaggle.com/kyakovlev/ashrae-data-minification\n- https://www.kaggle.com/hmendonca/starter-eda-and-feature-selection-ashrae3\n- https://www.kaggle.com/chmaxx/ashrae-eda-and-visualization-wip\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"# General imports\nimport numpy as np\nimport pandas as pd\nimport os, warnings, gc, math\n\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\n\nwarnings.filterwarnings('ignore')\nNROWS = None","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Memory reducer function\ndef 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                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    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":"%%time\n# Data load\ntrain_df = pd.read_csv('../input/ashrae-energy-prediction/train.csv', nrows = NROWS)\ntest_df = pd.read_csv('../input/ashrae-energy-prediction/test.csv', nrows = NROWS)\n\nbuilding_df = pd.read_csv('../input/ashrae-energy-prediction/building_metadata.csv', nrows = NROWS)\n\ntrain_weather_df = pd.read_csv('../input/ashrae-energy-prediction/weather_train.csv', nrows = NROWS)\ntest_weather_df = pd.read_csv('../input/ashrae-energy-prediction/weather_test.csv', nrows = NROWS)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Date transformations"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# Date convertions\nfor df in [train_df, test_df, train_weather_df, test_weather_df]:\n    \n    df['timestamp'] = pd.to_datetime(df['timestamp'])\n    \n# for df in [train_df, test_df, train_weather_df, test_weather_df]:\nfor df in [train_df, test_df]:\n    df['hour'] = np.uint8(df['timestamp'].dt.hour)\n    df['day'] = np.uint8(df['timestamp'].dt.day)\n    df['weekday'] = np.uint8(df['timestamp'].dt.weekday)\n    df['month'] = np.uint8(df['timestamp'].dt.month)\n    df['year'] = np.uint8(df['timestamp'].dt.year-2000)\n    \n# Categorical convertions\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Building tranformations"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n# Fill NA\nbuilding_df.rename(columns={\"square_feet\": \"log_square_feet\"}, inplace=True)\nbuilding_df['log_square_feet'] = np.float16(np.log(building_df['log_square_feet']))\nbuilding_df['year_built'] = np.uint8(building_df['year_built']-1900)\nbuilding_df['floor_count'] = np.uint8(building_df['floor_count'])\n\n# Enconding\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\nbuilding_df['primary_use'] = building_df['primary_use'].astype(str)\nbuilding_df['primary_use'] = le.fit_transform(building_df['primary_use']).astype(np.int8)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Weather NA Imputation"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer\n\nfor df in [train_weather_df, test_weather_df]:\n    cols = list(df.columns)\n    cols.remove('timestamp')\n    imp = IterativeImputer(random_state=42)\n    temp = imp.fit_transform(df[cols])\n    df[cols] = pd.DataFrame(temp, columns = cols)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Memory optimization"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfor df in [train_df, test_df, building_df, train_weather_df, test_weather_df]:\n    original = df.copy()\n    df = reduce_mem_usage(df)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Merging building into train dataset\nTemp_df combined with merge it's a faster and smarter whey to do this operation"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntemp_df = train_df[['building_id']]\ntemp_df = temp_df.merge(building_df, on=['building_id'], how='left')\ndel temp_df['building_id']\ntrain_df = pd.concat([train_df, temp_df], axis=1)\ndel temp_df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Merging building into test dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntemp_df = test_df[['building_id']]\ntemp_df = temp_df.merge(building_df, on=['building_id'], how='left')\ndel temp_df['building_id']\ntest_df = pd.concat([test_df, temp_df], axis=1)\ndel temp_df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Merging weather into train dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntemp_df = train_df[['site_id','timestamp']]\ntemp_df = temp_df.merge(train_weather_df, on=['site_id','timestamp'], how='left')\ndel temp_df['site_id'], temp_df['timestamp']\ntrain_df = pd.concat([train_df, temp_df], axis=1)\ndel temp_df","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Merging weather into test dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntemp_df = test_df[['site_id','timestamp']]\ntemp_df = temp_df.merge(test_weather_df, on=['site_id','timestamp'], how='left')\ndel temp_df['site_id'], temp_df['timestamp']\ntest_df = pd.concat([test_df, temp_df], axis=1)\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Cleaning Memory"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ndel train_weather_df, test_weather_df, temp_df\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfor m in train_df.meter.unique():\n#     train_df[train_df.meter == m].to_parquet('train'+ str(m) + '.parquet')\n#     test_df[test_df.meter == m].to_parquet('test'+ str(m) + '.parquet')\n    train_df[train_df.meter == m].to_pickle('train'+ str(m) + '.pkl')\n    test_df[test_df.meter == m].to_pickle('test'+ str(m) + '.pkl')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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.6.8"}},"nbformat":4,"nbformat_minor":1}