首页 > 解决方案 > 如何使用 FeatureTools 通过交叉表中的特征来生成新特征?

问题描述

特征交叉是一种在数据集中寻找非线性关系的非常常用的技术。如何使用 FeatureTools 通过交叉表中的特征来生成新特征?

标签: featuretools

解决方案


可以使用原语 在 Featuretools 中自动交叉每对数字特征Multiply。作为一个代码示例,假设我们有虚构的数据框

       index  price  shares_bought       date
index                                        
1          1   1.00              3 2017-12-29
2          2   0.75              4 2017-12-30
3          3   0.60              5 2017-12-31
4          4   0.50             18 2018-01-01
5          5   1.00              1 2018-01-02

我们想price乘以shares_bought。我们会跑

es = ft.EntitySet('Transactions')
es.entity_from_dataframe(dataframe=df, entity_id='log', index='index', time_index='date')

from featuretools.primitives import Multiply

fm, features = ft.dfs(entityset=es,
                      target_entity='log',
                      trans_primitives=[Multiply])

将数据框变成实体集,然后运行 ​​DFS 以Multiply在所有可能的地方应用。在这种情况下,由于只有两个数字特征,我们将得到一个特征矩阵fm,如下所示

       price  shares_bought  price * shares_bought
index                                             
1       1.00              3                    3.0
2       0.75              4                    3.0
3       0.60              5                    3.0
4       0.50             18                    9.0
5       1.00              1                    1.0

如果我们想手动将原语应用于特定的一对特征,可以使用种子特征来实现。我们的代码将是

n12_cross = Multiply(es['log']['price'], es['log']['shares_bought'])

fm, features = ft.dfs(entityset=es,
                      target_entity='log',
                      seed_features=[n12_cross])

得到与上面相同的特征矩阵。


编辑:为了制作上面的数据框,我使用了

import pandas as pd
import featuretools as ft
df = pd.DataFrame({'index': [1, 2, 3, 4, 5],
                   'shares_bought': [3, 4, 5, 18, 1],
                   'price': [1.00, 0.75, 0.60, 0.50, 1.00]})
df['date'] = pd.date_range('12/29/2017', periods=5, freq='D')

推荐阅读