首页 > 解决方案 > 使用自定义变量类型创建列表类型的自定义原始函数

问题描述

我对功能工具的功能有疑问make_agg_premitives

在我的数据中有由列表格式组成的值。

例如,

    id       products 
    a         ['a', 'b', 'c']
    b         ['a','c']
    a         ['a','c']

我想products通过使用各种自定义函数来聚合列:

def len_lists(values):
   return len(a)

len_ = make_agg_primitive(function = len_lists,
                           input_types = [?????],
                           return_type = ft.variable_types.Numeric,
                           description="length of a list related instance")

标签: pythonfeaturetools

解决方案


您可以使用 featuretools 创建自定义变量类型,该类型可与自定义原语一起使用以生成所需的转换功能。

注意:您要执行的操作实际上是转换原语,而不是聚合原语。

使用您的示例让我们创建一个自定义列表类型

from featuretools.variable_types import Variable

class List(Variable):
    type_string = "list"

现在让我们使用我们的新 List 类型来创建自定义转换原语,并为包含 List 变量类型的简单实体集生成特征。

from featuretools.primitives import make_trans_primitive
from featuretools.variable_types import Numeric
import pandas as pd
import featuretools as ft

def len_list(values):
    return values.str.len()

LengthList = make_trans_primitive(function = len_list,
                                  input_types = [List],
                                  return_type = Numeric,
                                  description="length of a list related instance")

# Create a simple entityset containing list data
data = pd.DataFrame({"id": [1, 2, 3],
                     "products": [ ['a', 'b', 'c'], ['a','c'], ['b'] ]})

es = ft.EntitySet(id="data")
es = es.entity_from_dataframe(entity_id="customers",
                              dataframe=data,
                              index="id",
                              variable_types={
                                   'products': List # Use the custom List type
                              })

feature_matrix, features = ft.dfs(entityset=es,
                                  target_entity="customers",
                                  agg_primitives=[],
                                  trans_primitives=[LengthList],
                                  max_depth=2)

您现在可以查看生成的特征,其中包括使用自定义变换原语的特征

feature_matrix.head()
    LEN_LIST(products)
id
1                    3
2                    2
3                    1

推荐阅读