{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"hist_df = pd.read_csv('../input/historical_transactions.csv')\nhist_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"eba26050c6fd158cf90a1cb1ff522ab9826db257"},"cell_type":"code","source":"hist_df.size","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e1b39cb1cd015b003ec257a9050ce87723238636"},"cell_type":"markdown","source":"### History data file size is quite large. even preview of this file is not supported. \n\n**File size is 2.65 GB**\n\n### How can we preview data? or read just a chunk of data?\n\nLoading through panda dataframe read_csv function , occupies 9.7GB space. it's very costly at the middle of the program when you have already load couple of data and run out of memory.\n\nHere are two options:\n### 1) Read in a chunk \n\nGet idea or preview of data\n\n### 2) Reduce memory usage.\n\n* Load objects as categories\n* Binary values are switched to int8\n* Binary values with missing values are switched to float16 (int does not understand nan)\n* 64 bits encoding are all switched to 32 or 16bits if possible."},{"metadata":{"_uuid":"53ce3b672efb24a74921716e00c29ea54a261f1d"},"cell_type":"markdown","source":"### 1) Read in a chunk"},{"metadata":{"trusted":true,"_uuid":"1ad33a2c9b9d70a44c2f8ee3a8c64e3a583ad18c"},"cell_type":"code","source":"history_reader = pd.read_csv('../input/historical_transactions.csv', chunksize = 10)\ntype(history_reader)\n\nhist_chunk = None\nfor chunk in history_reader:\n    hist_chunk = chunk\n    print(hist_chunk)\n    break","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"690a4791b3069ef1ed09992bdb2ca16ba7fa92d7"},"cell_type":"code","source":"type(hist_chunk)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a9f6cdce5ea83e9fc25a494056e29d914a0a6ad0"},"cell_type":"markdown","source":"Wow! with very less memory usage we can preview our data, can read column names. check the data types of each column and can reduce memory to load the whole file."},{"metadata":{"trusted":true,"_uuid":"107de6cd941f780deaf5f4c5a7a0a8af5c237221"},"cell_type":"code","source":"history_columns = list(hist_chunk.columns)\nprint(history_columns)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b2f1ae7395747bbd0dadc0f378febb06349e223b"},"cell_type":"code","source":"hist_chunk.dtypes","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8bc5136418eb32acc709163be53385c13c122037"},"cell_type":"markdown","source":"Ref:[ Ashish Patel's kernel](http://www.kaggle.com/ashishpatel26/lightgbm-goss-dart-parameter-tuning) \n### 2) Reduce memory usage.\n\n* Load objects as categories\n* Binary values are switched to int8\n* Binary values with missing values are switched to float16 (int does not understand nan)\n* 64 bits encoding are all switched to 32 or 16bits if possible."},{"metadata":{"trusted":true,"_uuid":"3a8e0082c4d66b220963310785b430bf211f21f7"},"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 df[col].dtypes == 'object':\n            df[col] = df[col].astype('category')\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,"_uuid":"fee7f5e5d949614f4e2092ae7600f96f7eac2a03"},"cell_type":"code","source":"import gc\n\nhistorical_transactions = reduce_mem_usage(hist_df)\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3aea42ee8467ec4bc62d487cd093ba5e873afc89"},"cell_type":"markdown","source":"Wow!  Reading the same file just took 1GB memory space instad of reading original file took 9GB space. That is a magic of converting data types."},{"metadata":{"trusted":true,"_uuid":"3e4c78b2318e921462e457b353dce1e31a8bd3cf"},"cell_type":"code","source":"historical_transactions.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bee2799007bcefc52aa9f5fa47e0d9e0507f086d"},"cell_type":"code","source":"historical_transactions.head()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}