Feature engineering

Predicting CTR with Machine Learning in Python

Kevin Huo

Instructor

Dealing with dates

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
Predicting CTR with Machine Learning in Python

Converting categorical variables via hashing

  • Categorical features must be converted into a numerical format

  • Hash function: maps arbitrary input to an integer output, returning exact same output for a given input

  • Lambda function: lambda x: f(x)

  • Apply hash function via f(x) = hash(x) as follows:

df['site_id'] = df['site_id'].apply(lambda x: hash(x), axis = 0)
83a0ad1a -> -9161053084583616050
85f751fd-> 818242008494177460
Predicting CTR with Machine Learning in Python

A closer look at features

  • Examples of count() and nunique():
df['ad_type'].count()
50000
df['ad_type'].nunique()
31

Example of distribution of a categorical column

Predicting CTR with Machine Learning in Python

Creating features

  • Most of variables are categorical
  • Adding more features is better for predictive power

  • Example of new feature: impressions by device_id (user) and 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
Predicting CTR with Machine Learning in Python

Let's practice!

Predicting CTR with Machine Learning in Python

Preparing Video For Download...