{"cells":[{"metadata":{},"cell_type":"markdown","source":"We're gonna start with a simple solution, LGBM, without much data cleaning or even analysis, just to establish a primary pipeline. There can be trouble with returning values in correct intervals. I will probably begin by synthesizing train with metadata with weather, divide it by meter and index it by building_id, then by date. Ye, seems legit."},{"metadata":{},"cell_type":"markdown","source":"Ok, some word of commentary from the middle of the work, so far I've established an almost full pipeline, the last obstacle being setting an appropriate number of observations for a training set. After merging data I've created variables accounting for day of the week etc. Now there's an issue - time doesn't seem to be local for certain regions. I will need to correct this. Apart from that, I've encountered a problem LGBM, previously, the algorithm doesnt seem to be very efficient on bigger samples. Because of that, for now im limiting sets im working on."},{"metadata":{},"cell_type":"markdown","source":"Ok, just checked average air temp with regards to hour of the day for different site_id's, result implies, that it indeed isn't the local time, I will be calculating the offset by assuming the lowest temperature point represents the same hour at different sites."},{"metadata":{},"cell_type":"markdown","source":"1. prepare training dataset\n*     a. download data\n*     b. merge data into single df\n*     c. retype columns and do really minor fe (change datetime)\n2. prepare algo\n3. validate algo \n4. algo accepted? at first it was way too slow\n5. prepare testing dataset\n6. predict"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# just importing stuff\n\n# 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)\nimport matplotlib.pyplot as plt # plots <3\nimport lightgbm as lgb\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import mean_squared_log_error\nimport gc\nimport time\n\n\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/input'):\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":{},"cell_type":"markdown","source":"ok, in the following block, I'm gonna join all of the relevant train data together, using row_id as index"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/ashrae-energy-prediction/train.csv')\nmeta = pd.read_csv('/kaggle/input/ashrae-energy-prediction/building_metadata.csv')\nweath = pd.read_csv('/kaggle/input/ashrae-energy-prediction/weather_train.csv')\nweath2 = pd.read_csv('/kaggle/input/ashrae-energy-prediction/weather_test.csv')\ntest1 = pd.read_csv('/kaggle/input/ashrae-energy-prediction/test.csv')\ntM1 = pd.merge(train, meta, left_on='building_id', right_index=True, how='left', sort=False)\ntestM1 = pd.merge(test1, meta, left_on='building_id', right_index=True, how='left', sort=False)\nprint(tM1.head())\ntestM1.drop('building_id_y', axis=1, inplace=True)\ntestM1.rename(columns = {'building_id_x':'building_id'}, inplace=True)\ntM1.drop('building_id_y', axis=1, inplace=True)\ntM1.rename(columns = {'building_id_x':'building_id'}, inplace=True)\ntM1[tM1['building_id']==1].head()\ndel train, meta, test1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"ok, above we have a merger of train and meta with quite a lot of redundancy also, the data takes waaay too much space, that's why I'll need to heavily limit it, although i won't give up on the redundant approach, but I'll retype columns and delete useless variables(especially since they get heavy)"},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()\nweath.reindex(index=['site_id', 'timestamp'])\nweath2.reindex(index=['site_id', 'timestamp'])\nw2 = weath.set_index(['site_id', 'timestamp'])\nwTest2 = weath.set_index(['site_id', 'timestamp'])\ntM2 = pd.merge(tM1, w2, left_on=['site_id', 'timestamp'], right_on=['site_id', 'timestamp'], right_index=True, how='left', sort=False)\ntestM2 = pd.merge(testM1, wTest2, left_on=['site_id', 'timestamp'], right_on=['site_id', 'timestamp'], right_index=True, how='left', sort=False)\nprint(tM2.head())\ndel weath, weath2, testM1, tM1, w2, wTest2","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"ok, now we have a merged table that can be used to train our algo, but before that, I'd like to change timestamp into something more usefull and delete minutes and seconds from it, also, I will use a format reducing function"},{"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\ntM2 = reduce_mem_usage(tM2)\ntestM2 = reduce_mem_usage(testM2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import math\nfor df in [tM2, testM2]:\n    df['timestamp'] = pd.to_datetime(df['timestamp'])\n    df['DT_M'] = df['timestamp'].dt.month.astype(np.int8)\n    df['DT_W'] = df['timestamp'].dt.weekofyear.astype(np.int8)\n    df['DT_D'] = df['timestamp'].dt.dayofyear.astype(np.int16)\n    \n    df['DT_hour'] = df['timestamp'].dt.hour.astype(np.int8)\n    df['DT_day_week'] = df['timestamp'].dt.dayofweek.astype(np.int8)\n    df['DT_day_month'] = df['timestamp'].dt.day.astype(np.int8)\n    df['DT_week_month'] = df['timestamp'].dt.day/7\n    df['DT_week_month'] = df['DT_week_month'].apply(lambda x: math.ceil(x)).astype(np.int8)\ntM2['primary_use'] = tM2['primary_use'].astype('category')\ntestM2['primary_use'] = testM2['primary_use'].astype('category')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"aight, by now we have our dataset kinda reduced memory-wise, and so we can train our model"},{"metadata":{},"cell_type":"markdown","source":"now we gonna get appropriate dataset division for evaluating purposes"},{"metadata":{"trusted":true},"cell_type":"code","source":"tM2.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"d_of_w = tM2[['DT_hour', 'site_id', 'air_temperature']]\nlowestT = []\nfor i in tM2.site_id.unique():\n    site_tm = d_of_w[d_of_w['site_id']==i].drop('site_id', axis=1).groupby('DT_hour').mean()\n    lowestT.append(site_tm.idxmin()[0])\ndel d_of_w, site_tm\nfor i in range(16):\n    tM2.loc[tM2['site_id']==i,'DT_hour'] = tM2[tM2['site_id']==i].loc[:,'DT_hour'] - lowestT[i]\n    testM2.loc[testM2['site_id']==i,'DT_hour'] = testM2[testM2['site_id']==i].loc[:,'DT_hour'] - lowestT[i]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"aight, hours of the day are quasi-corrected now, lets see if it changes a thing"},{"metadata":{"trusted":true},"cell_type":"code","source":"features = [col for col in tM2.columns if col not in ['meter_reading', 'timestamp']]\nfull_train_df = tM2[features]\ntarget = tM2['meter_reading']\ndel tM2, \nfull_test_df = testM2[features]\ndel testM2\n#tr_data = tM2.iloc[2000:100000][features]\n#tr_target = tM2.iloc[2000:100000]['meter_reading']\n#vl_data = tM2.iloc[100000:120000][features]\n#vl_target = tM2.iloc[100000:120000]['meter_reading']\n#tr_target = np.log1p(tM2.iloc[2000:10000]['meter_reading'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"params = {\n                    'objective':'regression',\n                    'boosting_type':'gbdt',\n                    'metric':'rmse',\n                    'n_jobs':-1,\n                    'learning_rate':0.05,\n                    'num_leaves': 2**8,\n                    'max_depth':-1,\n                    'tree_learner':'serial',\n                    'colsample_bytree': 0.7,\n                    'subsample_freq':1,\n                    'subsample':0.7,\n                    'n_estimators':800,\n                    'max_bin':255,\n                    'verbose':-1,\n                    'seed': 42,\n                    'early_stopping_rounds':100, \n                } ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"full_train_df.to_pickle('full_train_df.pkl')\ndel full_train_df\ngc.collect()\nfull_test_df.to_pickle('full_test_df.pkl')\ndel full_test_df\ngc.collect()\nfull_train_df = pd.read_pickle('full_train_df.pkl')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()\nfrom sklearn.model_selection import KFold, StratifiedKFold\ntest_fold = StratifiedKFold(n_splits=2, shuffle=False, random_state=42)\nmodels = []\nfor train_index, val_index in test_fold.split(full_train_df, full_train_df['building_id']):\n    train_X = full_train_df.iloc[train_index]\n    val_X = full_train_df.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)\n    lgb_eval = lgb.Dataset(val_X, val_y)\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)\ndel full_train_df, target","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()\nfrom tqdm import tqdm\nfull_test_df = pd.read_pickle('full_test_df.pkl')\ni=0\nres=[]\nstep_size = 50000\nfor j in tqdm(range(int(np.ceil(full_test_df.shape[0]/50000)))):\n    res.append(sum([model.predict(full_test_df.iloc[i:i+step_size]) for model in models])/2)\n    i+=step_size\ndel full_test_df\ngc.collect\nres = np.concatenate(res)\nres[res < 0] = 0\nsubmission = pd.read_csv('/kaggle/input/ashrae-energy-prediction/sample_submission.csv')\nsubmission['meter_reading'] = res\nsubmission.loc[submission['meter_reading']<0, 'meter_reading'] = 0\nsubmission.to_csv('submission_fe_lgbm.csv', index=False)\nsubmission","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Below is the early version - it was extremely ineffective, so I've decided to change paramaters. I keep the code to maybe use it later."},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\ngc.collect()\n\nlgb_train = lgb.Dataset(tr_data, tr_target)\nlgb_eval = lgb.Dataset(vl_data, vl_target)\ngbm = 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'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\ngc.collect()\n\nclf = lgb.LGBMClassifier(class_weight='balanced',drop_rate=0.8, min_data_in_leaf=100, max_bin=255,\n                                 n_estimators=500,min_sum_hessian_in_leaf=1,importance_type='gain',learning_rate=0.1,bagging_fraction = 0.85,\n                                 colsample_bytree = 1.0,feature_fraction = 0.1,lambda_l1 = 5.0,lambda_l2 = 3.0,max_depth =  9,\n                                 min_child_samples = 55,min_child_weight = 5.0,min_split_gain = 0.1,num_leaves = 45,subsample = 0.75) \n\nlab_enc = LabelEncoder()\nobs_count = []\na_time = []\nscore = []\nfor i in range(1):\n    num = i*3000\n    training_scores_encoded2 = lab_enc.fit_transform(tr_target)\n    training_scores_encoded3 = lab_enc.fit_transform(vl_target)\n    time1 = time.time()\n    clf.fit(tr_data, training_scores_encoded2)\n    time2 = time.time()\n    a_time.append(time2-time1)\n    #obs_count.append(400 + num)\n    pred = clf.predict(vl_data)\n    pred_score = np.sqrt(mean_squared_log_error(training_scores_encoded3, pred))\n    print(pred_score)\n    score.append(pred_score)\n#print(a_time)\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\n#tM2[tM2['building_id']==50].head()\nplt.plot(obs_count, a_time)\nplt.show()\nplt.plot(a_time, score)\nplt.show()\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\nimport time\ntime1 = time.time()\nfor i in range(10):\n    il = 10*i\n    badane = tM2[tM2['building_id']==il].loc[:, ['meter_reading', 'DT_day_week']]\n    badane2 = badane.groupby('DT_day_week').sum()\n    #badane2.plot(kind='bar')\n    #plt.show()\ntime2=time.time()\ntimedif=time2-time1\nprint(timedif)\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\n# I'll be using this once I reach training phase\nimport lightgbm as lgb\nlgb_params = {\n                    'objective':'regression',\n                    'boosting_type':'gbdt',\n                    'metric':'rmse',\n                    'n_jobs':-1,\n                    'learning_rate':0.05,\n                    'num_leaves': 2**8,\n                    'max_depth':-1,\n                    'tree_learner':'serial',\n                    'colsample_bytree': 0.7,\n                    'subsample_freq':1,\n                    'subsample':0.7,\n                    'n_estimators':800,\n                    'max_bin':255,\n                    'verbose':-1,\n                    'seed': 42,\n                    'early_stopping_rounds':100, \n                } \n'''","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}