特征工程是指以已有的数据为基础,根据专业领域的知识和经验,构造新的特征,获取高效准确的模型的过程。该过程是机器学习的关键,大部分工作需要依靠人力,耗费时间和精力。
特征工程也被称为特征构造,是从现有数据中构造新的特征从而训练机器学习模型的过程。这一步可能比实际上使用的模型更重要,因为一个机器学习算法只能从我们给定的数据中学习,所以构造一个和任务相关的特征是至关重要的
通常,特征工程是一个冗长的人工过程,依赖于领域知识、直觉和数据操作。这个过程可能是极其枯燥的,同时最终得到的特征将会受到人的主观性和时间的限制。特征工程自动化旨在通过从数据集中自动构造候选特征,并从中选择最优特征用于训练来帮助数据科学家。FeatureTools就是是特征工程自动化的框架,可以将时间和数据之间的关系转化为特征矩阵,自动实现特征工程。 github项目地址
https://github.com/Featuretools/featuretools
python -m pip install featuretools
conda install -c conda-forge featuretools
# 如果需要调用实体集的变量和关系的图形显示
conda install -c conda-forge featuretools
实体集是指实体(entities)和实体之间关系(relationships)的集合,实体是指数据表,例如dataframe。
import featuretools as ft
#导入demo数据
data=ft.demo.load_Mock_customer()
#定义一个实体集
es=ft.EntitySet()
#向实体集添加一个实体(数据表),定义实体名(entity_id),实体对应的表(dataframe),实体表的索引(index),实体的日期索引(time_index),属性的数据类型(variable_types)
es = es.entity_from_dataframe(entity_id='transactions',
dataframe=transactions_df,
index='transaction_id',
time_index='transaction_time',
variable_types={'product_id': ft.variable_types.Categorical,
'zip_code': ft.variable_types.ZIPCode})
#再增加一个实体
es = es.entity_from_dataframe(entity_id="products",
dataframe=products_df,
index="product_id")
#增加实体间的关系(relationship)ft.Relationship(parent entity,child entity)
new_relationship = ft.Relationship(es["products"]["product_id"], es["transactions"]["product_id"])
es = es.add_relationship(new_relationship)
EntitySet不仅可以添加已有的dataframe,也可以以已有的实体为基础,创建新的实体,并且会自动增加新建的实体和原有实体的关系
#创建新的实体,新实体的继承实体(base_entity_id),新实体的名称(new_entity_id),时间索引(make_time_index),选择继承的变量(additional_variables)
es = es.normalize_entity(base_entity_id="transactions",
new_entity_id="sessions",
index="session_id",
make_time_index="session_start"
additional_variables=["device", "customer_id", "zip_code", "session_start", "join_date"])
es = es.normalize_entity(base_entity_id="sessions",
new_entity_id="customers",
index="customer_id",
make_time_index="join_date",
additional_variables=["zip_code", "join_date"])
根据上面构建的实体集中的实体表以及关系,生成新的特征集,包括不同表的索引的统计以及时间索引的年,月,日,周的解析
#构造新的特征集,选择实体集(entityset),选择目标实体(target_entity),即你想获取的索引所在父实体
feature_matrix, feature_defs = ft.dfs(entityset=es, target_entity="transactions")
•
Seed Features(种子特征) 定义,对特定情况进行统计或运算的的处理
es = ft.demo.load_mock_customer(return_entityset=True)
#设置种子,总量大于125作为一个特定情况
es = ft.demo.load_mock_customer(return_entityset=True)
#获取每一个customer总量大于125所占的比例
feature_matrix, feature_defs = ft.dfs(entityset=es,
target_entity="customers",
agg_primitives=["percent_true"],
seed_features=[expensive_purchase])
•
Interesting values(兴趣值) 定义,感兴趣的值,对这些值进行分组的统计,生成新的特征
# 定义兴趣值
es["sessions"]["device"].interesting_values = ["desktop", "mobile", "tablet"]
# 生成新的特征,将分别统计device=deskto/mobile/tablet值的信息
feature_matrix, feature_defs = ft.dfs(entityset=es,
target_entity="customers",
agg_primitives=["count", "avg_time_between"],
where_primitives=["count", "avg_time_between"],
trans_primitives=[])
•
Encoding categorical features(编码) 对于文本或者其他分类数据进行自动编码
feature_matrix, feature_defs = ft.dfs(entityset=es,
target_entity="customers",
agg_primitives=["mode"],
max_depth=1)
#自动编码
feature_matrix_enc, features_enc = ft.encode_features(feature_matrix, feature_defs)
特征基元是指针对列数据的独立运算,生成新的特征。 FeatureTools提供的基元包括:
•
聚合(Aggregation),是指对数据进行分组统计,例如mean,max,min,std,skew,sum,count,"avg_time_between"等
•
转换(Transform),是指对列数据进行转换,例如hour(提取时间的小时),time_since_previous,absolute等
#特征基元示例,agg_primitives(聚合操作),trans_primitives(转换操作)
feature_matrix, feature_defs = ft.dfs(entityset=es,
target_entity="customers",
agg_primitives=["mean", "max", "min", "std", "skew"],
trans_primitives=["time_since_previous"])
#自定义特征基元
from featuretools.primitives import make_agg_primitive, make_trans_primitive
from featuretools.primitives import make_agg_primitive, make_trans_primitive
#自定义转换基元(求绝对值)
##首先定义函数
def absolute(column):
return abs(column)
##构造转换基元
Absolute = make_trans_primitive(function=absolute,
input_types=[Numeric],
return_type=Numeric)
#自定义聚合基元(求取最大值)
##定义函数
def maximum(column):
return max(column)
##构造聚合基元
Maximum = make_agg_primitive(function=maximum,
input_types=[Numeric],
return_type=Numeric)
#调用基元
feature_matrix, feature_defs = ft.dfs(entityset=es,
target_entity="sessions",
agg_primitives=[Maximum],
trans_primitives=[Absolute],
max_depth=2)
将特征工程保存,用于后续数据特征工程的构建
import featuretools as ft
#导入训练数据
es_train = ft.demo.load_mock_customer(return_entityset=True)
#导入测试数据
es_test = ft.demo.load_mock_customer(return_entityset=True, random_seed=33)
#构建特征工程
feature_matrix, feature_defs = ft.dfs(entityset=es_train,
target_entity="customers")
#自动编码
feature_matrix_enc, features_enc = ft.encode_features(feature_matrix, feature_defs)
#将特征工程导出
ft.save_features(features_enc, "feature_definitions")
#对测试数据进行特征工程处理
saved_features = ft.load_features('feature_definitions')
feature_matrix = ft.calculate_feature_matrix(saved_features, es_test)
#导出特征工程矩阵结果
#csv文件
feature_matrix.to_csv("feature_matrix.csv")
Feature engineering[3] What is Featuretools?[4] Feature Tools:可自动构造机器学习特征的Python库[5]