{"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 all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\nimport matplotlib.pyplot as plt\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import IsolationForest","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                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":"def plot_outliers(x,f,t):\n    fig, ax = plt.subplots(figsize=(10, 10))\n    ax.set_title(t)\n    ax.scatter(x=x[f[0]], y=x[f[1]],c=x['outlier'])\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def predict(x, contamination= 0.01):\n    sklIF = IsolationForest(behaviour= \"new\",\n                            contamination = contamination,\n                            random_state = np.random.RandomState(42))\n    return sklIF.fit_predict(x)\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"","_uuid":"","trusted":true},"cell_type":"code","source":"building_metadata = pd.read_csv(\"../input/ashrae-energy-prediction/building_metadata.csv\")\nbuilding_metadata = reduce_mem_usage(building_metadata)\n\ntrain = pd.read_csv(\"../input/ashrae-energy-prediction/train.csv\",parse_dates=['timestamp'])\ntrain = reduce_mem_usage(train)\n\nweather_train = pd.read_csv(\"../input/ashrae-energy-prediction/weather_train.csv\",parse_dates=['timestamp'])\nweather_train = reduce_mem_usage(weather_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Data Cleaning"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = train.query('not (building_id <= 104 & meter == 0 & timestamp <= \"2016-05-20\")')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Feature Engineering"},{"metadata":{"trusted":true},"cell_type":"code","source":"building_metadata[\"year_built_fe\"] = building_metadata[\"year_built\"].fillna(1960) - 1900\nbuilding_metadata[\"year_built_fe\"] = building_metadata[\"year_built_fe\"] // 10","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"le = LabelEncoder()\nbuilding_metadata[\"primary_use\"] = le.fit_transform(building_metadata[\"primary_use\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"t = train.merge(building_metadata, on='building_id', how='left')\nt = t.merge(weather_train, on=['site_id', 'timestamp'], how='left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"t[\"date\"]    = t[\"timestamp\"].dt.floor('D')\nt['week']    = t['timestamp'].dt.week\nt['weekday'] = t['timestamp'].dt.weekday\nt[\"hour\"]    = t[\"timestamp\"].dt.hour\nt[\"log_meter_reading\"] = np.log1p(t['meter_reading'])\n\nt['air_temperature'] = t['air_temperature'].interpolate(method='linear')\nt['dew_temperature'] = t['dew_temperature'].interpolate(method='linear')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### dew_temperature vs air_temperature outliers"},{"metadata":{"trusted":true},"cell_type":"code","source":"cont_features = ['dew_temperature',\n                 'air_temperature' ]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(16):\n    x = t[t.site_id == i].copy()\n    x['outlier'] = predict(x[cont_features])\n    plot_outliers(x,cont_features,f'site_id = {i}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### square_feet vs log_meter_reading outliers"},{"metadata":{"trusted":true},"cell_type":"code","source":"cont_features = ['square_feet', 'log_meter_reading' ]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(4):\n    x = t[t.meter == i].copy() \n    x['outlier'] = predict(x[cont_features], contamination=0.05)\n    plot_outliers(x,cont_features,f'meter = {i}') ","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}