如何解决如何在 FeatureTools 中实现多输出基元的自定义命名
从 v0.12.0 版本开始,Featuretools 允许您为多输出原语分配自定义名称:https://github.com/alteryx/featuretools/pull/794。默认情况下,当您定义自定义多输出原语时,生成的特征的列名称会附加 [0]
、[1]
、[2]
等。所以让我们说我有以下代码来输出多输出原语:
def sine_and_cosine_datestamp(column):
"""
Returns the Sin and Cos of the hour of datestamp
"""
sine_hour = np.sin(column.dt.hour)
cosine_hour = np.cos(column.dt.hour)
ret = [sine_hour,cosine_hour]
return ret
Sine_Cosine_Datestamp = make_trans_primitive(function = sine_and_cosine_datestamp,input_types = [vtypes.Datetime],return_type = vtypes.Numeric,number_output_features = 2)
在从 DFS 生成的数据框中,生成的两个列的名称将是 SINE_AND_COSINE_DATESTAMP(datestamp)[0]
和 SINE_AND_COSINE_DATESTAMP(datestamp)[1]
。实际上,我希望列的名称能够反映对列进行的操作。所以我希望列名类似于 SINE_AND_COSINE_DATESTAMP(datestamp)[sine]
和 SINE_AND_COSINE_DATESTAMP(datestamp)[cosine]
。显然,您必须使用 generate_names
方法才能这样做。我在网上找不到任何东西来帮助我使用这种方法,而且我一直遇到错误。例如,当我尝试以下代码时:
def sine_and_cosine_datestamp(column,string = ['sine,cosine']):
"""
Returns the Sin and Cos of the hour of the datestamp
"""
sine_hour = np.sin(column.dt.hour)
cosine_hour = np.cos(column.dt.hour)
ret = [sine_hour,cosine_hour]
return ret
def sine_and_cosine_generate_names(self,base_feature_names):
return u'STRING_COUNT(%s,"%s")' % (base_feature_names[0],self.kwargs['string'])
Sine_Cosine_Datestamp = make_trans_primitive(function = sine_and_cosine_datestamp,number_output_features = 2,description = "For each value in the base feature"
"outputs the sine and cosine of the hour,day,and month.",cls_attributes = {'generate_names': sine_and_cosine_generate_names})
我收到了断言错误。更令我困惑的是,当我进入 transform_primitve_base.py
文件夹中的 featuretools/primitives/base
文件时,我看到 generate_names
函数如下所示:
def generate_names(self,base_feature_names):
n = self.number_output_features
base_name = self.generate_name(base_feature_names)
return [base_name + "[%s]" % i for i in range(n)]
在上面的函数中,您似乎无法生成自定义基元名称,因为它默认使用 base_feature_names
和输出特征的数量。任何帮助将不胜感激。
解决方法
感谢提问!此功能没有得到很好的记录。
您的代码的主要问题是 string_count_generate_name
应该返回一个字符串列表,每列一个。
看起来您正在改编文档中的 StringCount
示例——我认为对于这个原语,总是使用“正弦”和“余弦”作为自定义名称,并删除来自 string
的可选 sine_and_cosine_datestamp
参数。我还更新了功能名称文本以匹配您想要的文本。
在这些变化之后:
def sine_and_cosine_datestamp(column):
"""
Returns the Sin and Cos of the hour of the datestamp
"""
sine_hour = np.sin(column.dt.hour)
cosine_hour = np.cos(column.dt.hour)
ret = [sine_hour,cosine_hour]
return ret
def sine_and_cosine_generate_names(self,base_feature_names):
template = 'SINE_AND_COSINE_DATESTAMP(%s)[%s]'
return [template % (base_feature_names[0],string) for string in ['sine','cosine']]
这创建了像 SINE_AND_COSINE_DATESTAMP(order_date)[sine]
这样的特征列名称。无需更改实际的 make_trans_primitive
调用。
在上面的函数中,您似乎无法生成自定义基元名称,因为它默认使用 base_feature_names 和输出特征的数量。
这是转换原语的默认 generate_names
函数。由于我们将此自定义生成名称函数分配给 Sine_Cosine_Datestamp
,因此不会使用默认值。
希望对您有所帮助,如果您还有问题,请告诉我!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。