我正在为我所学课程的最终项目参加这个Kaggle比赛,并且为此我试图复制这篇笔记本,但他使用的获取滞后特征的函数对我来说占用了太多内存。以下是他的代码:
我想要这个输出:
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
在我的电脑上失败后,我做了一些小修改来尝试减少内存使用,开始使用Google Colab,因为它比我的笔记本电脑有更多的内存,所以这是我的代码:
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()
但仍然使用了过多的内存,到了代码使用谷歌提供的10 Gb内存的极限。
sales_train = lag_feature(sales_train, [1, 2, 3, 12, 20], 'item_cnt_month')
有什么方法可以减少内存使用吗?只是为了展示,这是我的数据框:
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
补充一些信息,列'date_block_num'保存一个数字,用于标识该特征发生的月份,我想做的是从上个月获取一些数据并将其添加到该行。因此,如果我有一个滞后期为1,意味着我想为数据框中的每个产品获取一个月前的数据,并将其添加到名称为'feature_lag_1'的另一列中。例如,对于这个数据框:
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
并且这个函数调用:
sales_train = lag_feature(sales_train, [1], 'item_cnt_month')
我想要这个输出:
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
.shift
或者简单地使用索引将新的 Series 作为列添加,并自动对齐索引即可。 - ALollz