{"cells":[{"metadata":{},"cell_type":"markdown","source":"# ASHRAE - Great Energy Predictor III\n\n\nSUMMARY: `test.csv` is big data and takes time to load. I will convert competition data to feather format for fast `pandas.DataFrame` loading!"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"import os\nimport random\nimport gc\n\nimport 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 sklearn import preprocessing\nfrom sklearn.model_selection import KFold\nimport lightgbm as lgb\nimport xgboost as xgb\nimport catboost as cb","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# Copy from https://www.kaggle.com/gemartin/load-data-reduce-memory-usage by @gemartin\n# Modified to support timestamp 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\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]):\n            # skip datetime 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\n\n\ndef import_data(file):\n    \"\"\"create a dataframe and optimize its memory usage\"\"\"\n    df = pd.read_csv(file, parse_dates=True, keep_date_col=True)\n    df = reduce_mem_usage(df)\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\n# Read data...\nroot = '../input/ashrae-energy-prediction'\n\ntrain_df = pd.read_csv(os.path.join(root, 'train.csv'))\nweather_train_df = pd.read_csv(os.path.join(root, 'weather_train.csv'))\ntest_df = pd.read_csv(os.path.join(root, 'test.csv'))\nweather_test_df = pd.read_csv(os.path.join(root, 'weather_test.csv'))\nbuilding_meta_df = pd.read_csv(os.path.join(root, 'building_metadata.csv'))\nsample_submission = pd.read_csv(os.path.join(root, 'sample_submission.csv'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['timestamp'] = pd.to_datetime(train_df['timestamp'])\ntest_df['timestamp'] = pd.to_datetime(test_df['timestamp'])\nweather_train_df['timestamp'] = pd.to_datetime(weather_train_df['timestamp'])\nweather_test_df['timestamp'] = pd.to_datetime(weather_test_df['timestamp'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"# # categorize primary_use column to reduce memory on merge...\n\n# primary_use_dict = {key: value for value, key in enumerate(primary_use_list)} \n# print('primary_use_dict: ', primary_use_dict)\n# building_meta_df['primary_use'] = building_meta_df['primary_use'].map(primary_use_dict)\n\n# gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"reduce_mem_usage(train_df)\nreduce_mem_usage(test_df)\nreduce_mem_usage(building_meta_df)\nreduce_mem_usage(weather_train_df)\nreduce_mem_usage(weather_test_df)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Save data in feather format"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\ntrain_df.to_feather('train.feather')\ntest_df.to_feather('test.feather')\nweather_train_df.to_feather('weather_train.feather')\nweather_test_df.to_feather('weather_test.feather')\nbuilding_meta_df.to_feather('building_metadata.feather')\nsample_submission.to_feather('sample_submission.feather')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# Read data in feather format\n\nYou can see \"+ Add data\" button on top-right of notebook, press this button and add output of this kernel, then you can use above saved feather data frame for fast loading!\n\nLet's see how fast it is."},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\ntrain_df = pd.read_feather('train.feather')\nweather_train_df = pd.read_feather('weather_train.feather')\ntest_df = pd.read_feather('test.feather')\nweather_test_df = pd.read_feather('weather_test.feather')\nbuilding_meta_df = pd.read_feather('building_metadata.feather')\nsample_submission = pd.read_feather('sample_submission.feather')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"Reduced 37.1 sec to 1.51 sec!! 😄😄😄"},{"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}