I'm working on this Kaggle competition as the final project for the course I'm taking, and for that, I was trying to replicate this notebook but there is a function he uses to get the lagged features that is just using way too much memory for me. Here is his code:
def lag_feature(df, lags, col):
tmp = df[['date_block_num','shop_id','item_id',col]]
for i in lags:
shifted = tmp.copy()
shifted.columns = ['date_block_num','shop_id','item_id', col+'_lag_'+str(i)]
shifted['date_block_num'] += i
df = pd.merge(df, shifted, on=['date_block_num','shop_id','item_id'], how='left')
return df
After failing to run with his code I made some slight modifications to try to reduce the memory usage, and I started using google colab because it has more memory than my laptop so here is my code:
def lag_feature(df, lags, col):
df = dd.from_pandas(df, chunksize=1000)
tmp = df[['date_block_num','shop_id','item_id',col]]
for i in lags:
shifted = tmp[tmp.date_block_num + i <= 34].copy()
shifted.columns = ['date_block_num','shop_id','item_id', col+'_lag_'+str(i)]
shifted['date_block_num'] += i
df = dd.merge(df, shifted, on=['date_block_num','shop_id','item_id'], how='left')
return df.compute()
But still uses way too much memory, it got to the point where my code was using the 10 Gb o memory that google offers for this function call
sales_train = lag_feature(sales_train, [1, 2, 3, 12, 20], 'item_cnt_month')
are there ways that I can decrease my memory usage? Just to show, this is my dataframe:
Int64Index: 2829445 entries, 0 to 3134798
Data columns (total 8 columns):
date object
date_block_num int8
item_cnt_day float16
item_id int16
item_price float16
shop_id int8
item_cnt_month float16
item_category_id int8
dtypes: float16(3), int16(1), int8(3), object(1)
memory usage: 152.9+ MB
Just to add more info, the column 'date_block_num' keeps a number which identifies which month that feature happened, what I'm trying to do is get some data from a previous month into that row. So, if I had a lag of 1, means that I want to get the data from a month ago for each product in my dataframe and add it to another column with the name 'feature_lag_1'. For example, with this dataframe:
date date_block_num item_cnt_day item_id item_price shop_id \
0 14.09.2013 8 1.0 2848 99.0 24
1 14.09.2013 8 1.0 2848 99.0 24
2 14.09.2013 8 1.0 2848 99.0 24
3 01.09.2013 8 1.0 2848 99.0 24
4 01.09.2013 8 1.0 2848 99.0 24
item_cnt_month item_category_id
0 2.0 30
1 2.0 30
2 2.0 30
3 2.0 30
4 2.0 30
and this function call:
sales_train = lag_feature(sales_train, [1], 'item_cnt_month')
I want this output:
date date_block_num item_cnt_day item_id item_price shop_id \
0 14.09.2013 8 1.0 2848 99.0 24
1 14.09.2013 8 1.0 2848 99.0 24
2 14.09.2013 8 1.0 2848 99.0 24
3 01.09.2013 8 1.0 2848 99.0 24
4 01.09.2013 8 1.0 2848 99.0 24
item_cnt_month item_category_id item_cnt_month_lag_1
0 2.0 30 3.0
1 2.0 30 3.0
2 2.0 30 3.0
3 2.0 30 3.0
4 2.0 30 3.0