【发布时间】:2019-03-12 14:32:46
【问题描述】:
我正在将this Kaggle competition 作为我正在学习的课程的最终项目,为此,我试图复制this notebook,但他使用了一个函数来获取滞后的功能对我来说使用了太多的内存。这是他的代码:
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 o 内存,谷歌为此函数调用提供了 10 Gb o 内存
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
【问题讨论】:
-
你能提供一个minimal reproducible example 你的数据和预期的输出吗?我不明白你为什么需要在这里合并。您也许可以只使用
.shift或简单地使用索引将新系列添加为在索引上自动对齐的列。 -
现在我只是在等着看 MRockilin 的答案是否有效,一旦完成处理,我可以发布更多详细信息,但如果有效,我可以尝试更好地描述它。只是我的笔记本还在处理中。
-
我做了一些更改,希望对您有所帮助,我会尽快添加示例。
-
@ALollz,如果有帮助,我已经添加了更多信息
-
您是否为此使用 Jupyter Notebook?