{"cells":[{"metadata":{},"cell_type":"markdown","source":"https://www.kaggle.com/vbmokin/very-significant-safe-memory-lightgbm?select=weather_train.csv","execution_count":null},{"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\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 read-only \"../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/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"submission = pd.read_csv(\"../input/ashrae-energy-prediction/sample_submission.csv\")\ntest = pd.read_csv(\"../input/ashrae-energy-prediction/test.csv\")\ntrain = pd.read_csv(\"../input/ashrae-energy-prediction/train.csv\")\nweather_train = pd.read_csv(\"../input/ashrae-energy-prediction/weather_train.csv\")\nweather_test = pd.read_csv(\"../input/ashrae-energy-prediction/weather_test.csv\")\nmetadata = pd.read_csv(\"../input/ashrae-energy-prediction/building_metadata.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = train.merge(metadata, 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\"])\ndel weather_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train[\"timestamp\"] = pd.to_datetime(train[\"timestamp\"])\n\ntrain[\"weekday\"] = train[\"timestamp\"].dt.weekday\ntrain[\"hour\"] = train[\"timestamp\"].dt.hour\n\ntrain[\"weekday\"] = train['weekday'].astype(np.uint8)\ntrain[\"hour\"] = train['hour'].astype(np.uint8)\n\ntrain['year_built'] = train['year_built']-1900\ntrain['square_feet'] = (10*np.log(train['square_feet'])).astype(np.uint8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def average_imputation(df, column_name):\n    imputation = df.groupby(['timestamp'])[column_name].mean()\n    \n    df.loc[df[column_name].isnull(), column_name] = df[df[column_name].isnull()][[column_name]].apply(lambda x: imputation[df['timestamp'][x.index]].values)\n    del imputation\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = average_imputation(train, 'wind_speed')\ntrain = average_imputation(train, 'wind_direction')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"beaufort = [(0, 0, 0.3), (1, 0.3, 1.6), (2, 1.6, 3.4), (3, 3.4, 5.5), (4, 5.5, 8), (5, 8, 10.8), (6, 10.8, 13.9), \n          (7, 13.9, 17.2), (8, 17.2, 20.8), (9, 20.8, 24.5), (10, 24.5, 28.5), (11, 28.5, 33), (12, 33, 200)]\n\nfor item in beaufort:\n    train.loc[(train['wind_speed']>=item[1]) & (train['wind_speed']<item[2]), 'beaufort_scale'] = item[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def degToCompass(num):\n    val=int((num/22.5)+.5)\n    arr=[i for i in range(0,16)]\n    return arr[(val % 16)]\ntrain['wind_direction'] = train['wind_direction'].apply(degToCompass)\n\ntrain['beaufort_scale'] = train['beaufort_scale'].astype(np.uint8)\ntrain[\"wind_direction\"] = train['wind_direction'].astype(np.uint8)\ntrain[\"meter\"] = train['meter'].astype(np.uint8)\ntrain[\"site_id\"] = train['site_id'].astype(np.uint8)\ntrain[\"building_id\"] = train['building_id'].astype(np.uint16)\n\ntrain['air_temperature'] = np.int8(round(2*train['air_temperature'],0)) # store values with precision 0.5\ntrain['cloud_coverage'] = np.uint8(round(5*train['cloud_coverage'],0)) # store values with precision 0.2\ntrain['dew_temperature'] = np.int8(round(5*train['dew_temperature'],0)) # store values with precision 0.2\ntrain['precip_depth_1_hr'] = np.uint8(np.clip(round(train['precip_depth_1_hr'],0),0,255)) # transform [-1,343] to [0,255]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = train.fillna(0)\ntrain['year_built'] = train['year_built'].astype(np.uint8)\ntrain['floor_count'] = train['floor_count'].astype(np.uint8)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\nle = LabelEncoder()\ntrain[\"primary_use\"] = le.fit_transform(train[\"primary_use\"]).astype(np.uint8)\n\ncategoricals = [\"site_id\", \"building_id\", \"primary_use\", \"hour\", \"weekday\", \"meter\",  \"wind_direction\"]\ndrop_cols = [\"sea_level_pressure\", \"wind_speed\"]\nnumericals = [\"square_feet\", \"year_built\", \"air_temperature\", \"cloud_coverage\",\"dew_temperature\", 'precip_depth_1_hr', 'floor_count', 'beaufort_scale']\n\nfeat_cols = categoricals + numericals","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"target = np.log1p(train[\"meter_reading\"]).astype(np.float16)\ntrain = train.drop(drop_cols, axis = 1)\ndel train[\"meter_reading\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import mean_squared_error\nimport lightgbm as lgb\nfrom sklearn.model_selection import KFold, StratifiedKFold\nfrom tqdm import tqdm\n\n\nparams = {\n            'boosting_type': 'gbdt',\n            'objective': 'regression',\n            'metric': {'rmse'},\n            'subsample': 0.25,\n            'subsample_freq': 1,\n            'learning_rate': 0.4,\n            'num_leaves': 17,\n            'feature_fraction': 0.9,\n            'lambda_l1': 1,  \n            'lambda_l2': 1}\n\nfolds = 4\nseed = 666\n\nkf = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed)\n\nmodels = []\nfor train_index, val_index in kf.split(train, train['building_id']):\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=500,\n                valid_sets=(lgb_train, lgb_eval),\n                early_stopping_rounds=100,\n                verbose_eval = 100)\n    models.append(gbm)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\ndel train, train_X, val_X, lgb_train, lgb_eval, train_y, val_y, target\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"s","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test = test.merge(metadata, left_on = \"building_id\", right_on = \"building_id\", how = \"left\")\ndel metadata\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"le = LabelEncoder()\ntest[\"primary_use\"] = le.fit_transform(test[\"primary_use\"]).astype(np.uint8)\ntest = test.merge(weather_test, left_on = [\"site_id\", \"timestamp\"], right_on = [\"site_id\", \"timestamp\"], how = \"left\")\ndel weather_test\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test[\"timestamp\"] = pd.to_datetime(test[\"timestamp\"])\ntest[\"hour\"] = test[\"timestamp\"].dt.hour\ntest[\"weekday\"] = test[\"timestamp\"].dt.weekday\ntest[\"weekday\"] = test['weekday'].astype(np.uint8)\ntest[\"hour\"] = test['hour'].astype(np.uint8)\ntest['year_built'] = test['year_built']-1900\ntest['square_feet'] = (10*np.log(test['square_feet'])).astype(np.uint8)\ntest[\"building_id\"] = test['building_id'].astype(np.uint16)\n\ntest['air_temperature'] = np.int8(round(2*test['air_temperature'],0)) # store values with precision 0.5\ntest['cloud_coverage'] = np.uint8(round(10*test['cloud_coverage'],0)) # store values with precision 0.1\ntest['dew_temperature'] = np.int8(round(5*test['dew_temperature'],0)) # store values with precision 0.2\ntest['precip_depth_1_hr'] = np.uint8(np.clip(round(test['precip_depth_1_hr'],0),0,255)) # transform [-1,343] to [0,255]\n\ntest = average_imputation(test, 'wind_speed')\ntest = average_imputation(test, 'wind_direction')\n\nfor item in beaufort:\n    test.loc[(test['wind_speed']>=item[1]) & (test['wind_speed']<item[2]), 'beaufort_scale'] = item[0]\ntest['wind_direction'] = test['wind_direction'].apply(degToCompass)\n\ntest['wind_direction'] = test['wind_direction'].apply(degToCompass)\ntest['beaufort_scale'] = test['beaufort_scale'].astype(np.uint8)\ntest[\"wind_direction\"] = test['wind_direction'].astype(np.uint8)\ntest[\"meter\"] = test['meter'].astype(np.uint8)\ntest[\"site_id\"] = test['site_id'].astype(np.uint8)\n\ntest = test[feat_cols]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = test.fillna(0)\ntest['year_built'] = test['year_built'].astype(np.uint8)\ntest['floor_count'] = test['floor_count'].astype(np.uint8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res = np.concatenate(res)\nsubmission['meter_reading'] = res\nsubmission.loc[submission['meter_reading']<0, 'meter_reading'] = 0\nsubmission.to_csv('submission_new.csv', index=False)\nsubmission","execution_count":null,"outputs":[]},{"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":4}