{"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# Suppress warnings \nimport warnings\nwarnings.filterwarnings('ignore')\nimport gc\n\n# matplotlib and seaborn for plotting\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nimport seaborn as sns\nimport matplotlib.patches as patches\n\nfrom plotly import tools, subplots\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.express as px\npd.set_option('max_columns', 100)\n\npy.init_notebook_mode(connected=True)\nfrom plotly.offline import init_notebook_mode, iplot\ninit_notebook_mode(connected=True)\nimport plotly.graph_objs as go\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,random, math, psutil, pickle\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nprint(os.listdir(\"../input/ashrae-energy-prediction/\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nroot = '../input/ashrae-energy-prediction/'\ntrain_df = pd.read_csv(root + 'train.csv')\ntrain_df[\"timestamp\"] = pd.to_datetime(train_df[\"timestamp\"], format='%Y-%m-%d %H:%M:%S')\n\nweather_train_df = pd.read_csv(root + 'weather_train.csv')\ntest_df = pd.read_csv(root + 'test.csv')\nweather_test_df = pd.read_csv(root + 'weather_test.csv')\nbuilding_meta_df = pd.read_csv(root + 'building_metadata.csv')\nsample_submission = pd.read_csv(root + 'sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Size of train_df data', train_df.shape)\nprint('Size of weather_train_df data', weather_train_df.shape)\nprint('Size of weather_test_df data', weather_test_df.shape)\nprint('Size of building_meta_df data', building_meta_df.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Function to reduce the DF size\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":"## REducing memory\ntrain_df = reduce_mem_usage(train_df)\ntest_df = reduce_mem_usage(test_df)\n\nweather_train_df = reduce_mem_usage(weather_train_df)\nweather_test_df = reduce_mem_usage(weather_test_df)\nbuilding_meta_df = reduce_mem_usage(building_meta_df)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain_df.columns.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nweather_train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nweather_train_df.columns.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nweather_test_df.columns.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"building_meta_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"building_meta_df.columns.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfor key, d in train_df.groupby('meter_reading'):\n    break\n    d.head()\nplt.figure(figsize = (20,5))\nd['meter'].plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (15,5))\ntrain_df['meter_reading'].plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain_df['meter_reading'].plot(kind='hist',\n                            bins=25,\n                            figsize=(15, 5),\n                           title='Distribution of Target Variable (meter_reading)')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Missing Values\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntotal = train_df.isnull().sum().sort_values(ascending = False)\npercent = (train_df.isnull().sum()/train_df.isnull().count()*100).sort_values(ascending = False)\nmissing__train_data  = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing__train_data.head(4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# checking missing data\ntotal = weather_train_df.isnull().sum().sort_values(ascending = False)\npercent = (weather_train_df.isnull().sum()/weather_train_df.isnull().count()*100).sort_values(ascending = False)\nmissing_weather_data  = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_weather_data.head(9)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train_df['cloud_coverage']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train_df.drop(['cloud_coverage','precip_depth_1_hr', 'sea_level_pressure'],axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total = weather_test_df.isnull().sum().sort_values(ascending = False)\npercent = (weather_test_df.isnull().sum()/weather_test_df.isnull().count()*100).sort_values(ascending = False)\nmissing_weather_test_data  = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_weather_test_data.head(9)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_test_df.drop(['cloud_coverage','precip_depth_1_hr', 'sea_level_pressure'],axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total = building_meta_df.isnull().sum().sort_values(ascending = False)\npercent = (building_meta_df.isnull().sum()/building_meta_df.isnull().count()*100).sort_values(ascending = False)\nmissing_building_meta_df  = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_building_meta_df.head(6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.dtypes.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.select_dtypes('object').apply(pd.Series.nunique, axis = 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"correlations = train_df.corr()['meter_reading'].sort_values()\n\n# Display correlations\nprint('Most Positive Correlations:\\n', correlations.tail(15))\nprint('\\nMost Negative Correlations:\\n', correlations.head(15))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# weather correlation\nw_correlations = weather_train_df.corr()['wind_speed'].sort_values()\n\n# Display correlations\nprint('Most Positive Correlations:\\n', w_correlations.tail(15))\nprint('\\nMost Negative Correlations:\\n',w_correlations.head(15))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"corrs = train_df.corr()\ncorrs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"w_corrs = weather_train_df.corr()\nw_corrs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.building_id.nunique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (20, 8))\n\n# Heatmap of correlations\nsns.heatmap(corrs, cmap = plt.cm.RdYlBu_r, vmin = -0.25, annot = True, vmax = 0.6)\nplt.title('Correlation Heatmap');","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_squared_error\nimport lightgbm as lgb\nfrom sklearn.preprocessing import LabelEncoder\nfrom tqdm import tqdm   # 进度条工具\n\nimport os\n\nfor dirname, _, filenames in os.walk('data_set'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\nroot = '../input/ashrae-energy-prediction/'\nbuilding_df = pd.read_csv(root+\"building_metadata.csv\")\nweather_train = pd.read_csv(root+\"weather_train.csv\")\ntrain = pd.read_csv(root+\"train.csv\")\n\n# 数据关联\ntrain = train.merge(building_df, left_on=\"building_id\", right_on=\"building_id\", how=\"left\")\ntrain = train.merge(weather_train, left_on=[\"site_id\", \"timestamp\"], right_on=[\"site_id\", \"timestamp\"])\n\nprint(train.head(5))\n\n# 特征处理\n# 天气时间字段处理\ntrain[\"timestamp\"] = pd.to_datetime(train[\"timestamp\"])\ntrain[\"hour\"] = train[\"timestamp\"].dt.hour\ntrain[\"day\"] = train[\"timestamp\"].dt.day\ntrain[\"year\"] = train[\"timestamp\"].dt.year\ntrain[\"weekend\"] = train[\"timestamp\"].dt.weekday\ntrain[\"month\"] = train[\"timestamp\"].dt.month\ndel train[\"timestamp\"]\n\n# 建筑数据统一范围\ntrain['year_built'] = train['year_built'] - 1900\ntrain['square_feet'] = np.log(train['square_feet'])\n\n# 特征转换\nle = LabelEncoder()\ntrain[\"primary_use\"] = le.fit_transform(train[\"primary_use\"])\n\n# 特征选取与整理\ncategoricals = [\"site_id\", \"building_id\", \"primary_use\", \"hour\", \"day\", \"weekend\", \"month\", \"meter\"]\ndrop_cols = [\"precip_depth_1_hr\", \"sea_level_pressure\", \"wind_direction\", \"wind_speed\"]\nnumericals = [\"square_feet\", \"year_built\", \"air_temperature\", \"cloud_coverage\", \"dew_temperature\"]\nfeat_cols = categoricals + numericals\ntarget = np.log1p(train[\"meter_reading\"])  # 数据平滑处理\ndel train[\"meter_reading\"]\ntrain = train.drop(drop_cols, axis=1)\n\n# lightbgm参数设置\nparams = {\n    'boosting_type': 'gbdt',\n    'objective': 'regression',\n    'metric': {'rmse'},\n    'subsample': 0.2,\n    'learning_rate': 0.1,\n    'feature_fraction': 0.9,\n    'bagging_fraction': 0.9,\n    'alpha': 0.1,\n    'lambda': 0.1\n}\n\nfolds = 3\nseed = 666\nkf = KFold(n_splits=folds, shuffle=True, random_state=seed)\n\nmodels = []\nfor train_index, val_index in kf.split(train):\n    train_X = train[feat_cols].iloc[train_index]\n    val_X = train[feat_cols].iloc[val_index]\n    train_y = target.iloc[train_index]\n    val_y = target.iloc[val_index]\n    lgb_train = lgb.Dataset(train_X, train_y, categorical_feature=categoricals)\n    lgb_eval = lgb.Dataset(val_X, val_y, categorical_feature=categoricals)\n    gbm = lgb.train(params,\n                    lgb_train,\n                    num_boost_round=300,\n                    valid_sets=(lgb_train, lgb_eval),\n                    early_stopping_rounds=100,\n                    verbose_eval=100)\n    models.append(gbm)\n\n# 垃圾处理机制，collect(),返回释放掉的资源个数\nimport gc\n\ndel train, train_X, val_X, lgb_train, lgb_eval, train_y, val_y, target\ngc.collect()\n\n# 测试集数据处理\ntest = pd.read_csv(root+\"test.csv\")\ntest = test.merge(building_df, left_on=\"building_id\", right_on=\"building_id\", how=\"left\")\ndel building_df\ngc.collect()\ntest[\"primary_use\"] = le.transform(test[\"primary_use\"])\nweather_test = pd.read_csv(root+\"weather_test.csv\")\nweather_test = weather_test.drop(drop_cols, axis=1)\ntest = test.merge(weather_test, left_on=[\"site_id\", \"timestamp\"], right_on=[\"site_id\", \"timestamp\"], how=\"left\")\ndel weather_test\ntest[\"timestamp\"] = pd.to_datetime(test[\"timestamp\"])\ntest[\"hour\"] = test[\"timestamp\"].dt.hour.astype(np.uint8)\ntest[\"year\"] = test[\"timestamp\"].dt.year.astype(np.uint16)\ntest[\"day\"] = test[\"timestamp\"].dt.day.astype(np.uint8)\ntest[\"weekend\"] = test[\"timestamp\"].dt.weekday.astype(np.uint8)\ntest[\"month\"] = test[\"timestamp\"].dt.month.astype(np.uint8)\ntest['year_built'] = test['year_built'] - 1900\ntest['square_feet'] = np.log(test['square_feet'])\n\ntest = test[feat_cols]\n\ni = 0\nres = []\nstep_size = 50000\nfor j in tqdm(range(int(np.ceil(test.shape[0] / 50000)))):\n    res.append(np.expm1(sum([model.predict(test.iloc[i:i + step_size]) for model in models]) / folds))\n    i += step_size\n\nres = np.concatenate(res)\nsubmission = pd.read_csv(root+'sample_submission.csv')\nsubmission['meter_reading'] = res\nsubmission.loc[submission['meter_reading'] < 0, 'meter_reading'] = 0\nsubmission.to_csv('submission.csv', index=False)","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}