DeepCTR-Torch:基於深度學習的CTR預測演算法庫

  • 2019 年 10 月 7 日
  • 筆記

在計算廣告和推薦系統中,CTR預估一直是一個核心問題。無論在工業界還是學術界都是一個熱點研究問題,近年來也有若干相關的演算法競賽陸續舉辦。本文介紹一個使用PyTorch編寫的深度學習的點擊率預測演算法庫DeepCTR-Torch,具有簡潔易用、模組化和可擴展的優點,非常適合初學者快速入門學習。

(本文作者:沈偉臣,阿里巴巴演算法工程師)

點擊率預估問題

點擊率預估問題通常形式化描述為給定用戶,物料,上下文的情況下,計算用戶點擊物料的概率即:pCTR = p(click=1|user,item,context)

簡單來說,在廣告業務中使用pCTR來計算廣告的預期收益,在推薦業務中通過使用pCTR來確定候選物料的一個排序列表。

DeepCTR-Torch

人們通過構造有效的組合特徵和使用複雜的模型來學習數據中的模式來提升效果。基於因子分解機的方法,可以通過向量乘積的形式學習特徵的交互,並且泛化到那些沒有出現過的組合上。

隨著深度神經網路在若干領域的巨大發展,近年來研究者也提出了若干基於深度學習的分解模型來同時學習低階和高階的特徵交互,如:

PNN,Wide&Deep,DeepFM,Attentional FM,Neural FM,DCN,xDeepFM,AutoInt,FiBiNET

以及基於用戶歷史行為序列建模的DIN,DIEN,DSIN等。

對於剛接觸這方面的同學來說,可能對這些方法的細節還不太了解,雖然網上有很多介紹,但是程式碼卻沒有統一的形式,且當想要遷移到自己的數據集進行實驗時也很不方便。本文介紹的一個使用PyTorch實現的基於深度學習的CTR模型包DeepCTR-PyTorch,無論是使用還是學習都很方便。

DeepCTR-PyTorch是一個簡潔易用、模組化可擴展的基於深度學習的CTR模型包。除了近年來主流模型外,還包括許多可用於輕鬆構建您自己的自定義模型的核心組件層。

您簡單的通過model.fit()model.predict()來使用這些複雜的模型執行訓練和預測任務,以及在通過模型初始化列表的device參數來指定運行在cpu還是gpu上。

安裝與使用

  • 安裝
pip install -U deepctr-torch
  • 使用例子

下面用一個簡單的例子告訴大家,如何快速的應用一個基於深度學習的CTR模型,程式碼地址在:

https://github.com/shenweichen/DeepCTR-Torch/blob/master/examples/run_classification_criteo.py。

The Criteo Display Ads datasetkaggle上的一個CTR預估競賽數據集。裡面包含13個數值特徵I1-I13和26個類別特徵C1-C26

# -*- coding: utf-8 -*-  # 使用pandas 讀取上面介紹的數據,並進行簡單的缺失值填充  import pandas as pd  from sklearn.metrics import log_loss, roc_auc_score  from sklearn.model_selection import train_test_split  from sklearn.preprocessing import LabelEncoder, MinMaxScaler  from deepctr_torch.models import *  from deepctr_torch.inputs import SparseFeat, DenseFeat, get_fixlen_feature_names  import torch    # 使用pandas 讀取上面介紹的數據,並進行簡單的缺失值填充  data = pd.read_csv('./criteo_sample.txt')  # 上面的數據在:https://github.com/shenweichen/DeepCTR-Torch/blob/master/examples/criteo_sample.txt    sparse_features = ['C' + str(i) for i in range(1, 27)]  dense_features = ['I' + str(i) for i in range(1, 14)]    data[sparse_features] = data[sparse_features].fillna('-1', )  data[dense_features] = data[dense_features].fillna(0, )  target = ['label']    #這裡我們需要對特徵進行一些預處理,對於類別特徵,我們使用LabelEncoder重新編碼(或者哈希編碼),對於數值特徵使用MinMaxScaler壓縮到0~1之間。    for feat in sparse_features:     lbe = LabelEncoder()     data[feat] = lbe.fit_transform(data[feat])  mms = MinMaxScaler(feature_range=(0, 1))  data[dense_features] = mms.fit_transform(data[dense_features])    # 這裡是比較關鍵的一步,因為我們需要對類別特徵進行Embedding,所以需要告訴模型每一個特徵組有多少個embbedding向量,我們通過pandas的nunique()方法統計。      fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique())                             for feat in sparse_features] + [DenseFeat(feat, 1,)                                                             for feat in dense_features]    dnn_feature_columns = fixlen_feature_columns  linear_feature_columns = fixlen_feature_columns    fixlen_feature_names = get_fixlen_feature_names(     linear_feature_columns + dnn_feature_columns)    #最後,我們按照上一步生成的特徵列拼接數據    train, test = train_test_split(data, test_size=0.2)  train_model_input = [train[name] for name in fixlen_feature_names]  test_model_input = [test[name] for name in fixlen_feature_names]    # 檢查是否可以使用gpu    device = 'cpu'  use_cuda = True  if use_cuda and torch.cuda.is_available():     print('cuda ready...')     device = 'cuda:0'    # 初始化模型,進行訓練和預測    model = DeepFM(linear_feature_columns=linear_feature_columns, dnn_feature_columns=dnn_feature_columns, task='binary',                 l2_reg_embedding=1e-5, device=device)    model.compile("adagrad", "binary_crossentropy",                 metrics=["binary_crossentropy", "auc"],)  model.fit(train_model_input, train[target].values,             batch_size=256, epochs=10, validation_split=0.2, verbose=2)    pred_ans = model.predict(test_model_input, 256)  print("")  print("test LogLoss", round(log_loss(test[target].values, pred_ans), 4))  print("test AUC", round(roc_auc_score(test[target].values, pred_ans), 4))

相關資料

  • DeepCTR-Torch程式碼主頁

https://github.com/shenweichen/DeepCTR-Torch

  • DeepCTR-Torch文檔: https://deepctr-torch.readthedocs.io/en/latest/index.html
  • DeepCTR(tensorflow版)程式碼主頁 : https://github.com/shenweichen/DeepCTR
  • DeepCTR(tensorflow版)文檔: https://deepctr-doc.readthedocs.io/en/latest/index.html