特征工程

用 Python 预测 CTR 的机器学习实战

Kevin Huo

Instructor

处理日期

print(df.hour.head(1))
14102101
df['hour'] = pd.to_datetime(
  df['hour'], format = '%y%m%d%H')
df['hour_of_day'] = df['hour'].dt.hour
print(df.hour.head(1))
2014-10-21 01:00:0
print(df.groupby('hour_of_day')
      ['click'].sum())
             click
hour_of_day       
1             1092
2             6546
用 Python 预测 CTR 的机器学习实战

用哈希转换类别变量

  • 类别型特征需转换为数值格式

  • 哈希函数:将任意输入映射为整数,对同一输入返回完全相同的输出

  • Lambda 函数:lambda x: f(x)

  • 通过 f(x) = hash(x) 应用哈希函数:

df['site_id'] = df['site_id'].apply(lambda x: hash(x))
83a0ad1a -> -9161053084583616050
85f751fd-> 818242008494177460
用 Python 预测 CTR 的机器学习实战

深入了解特征

  • count()nunique() 示例:
df['ad_type'].count()
50000
df['ad_type'].nunique()
31

类别列分布示例

用 Python 预测 CTR 的机器学习实战

构建特征

  • 多数变量为类别型
  • 增加特征通常提升预测能力

  • 新特征示例:按 device_id(用户)与 search_engine_type 的曝光量:

df['device_id_count'] = df.groupby('device_id')['click'].transform("count")
df['search_engine_type_count'] = df.groupby('search_engine_type')['click'].transform("count")
print(df.head(1))
...  device_id_count  search_engine_type_count
...            40862                     47710
用 Python 预测 CTR 的机器学习实战

开始练习!

用 Python 预测 CTR 的机器学习实战

Preparing Video For Download...