前向逐步变量选择

Python 预测分析入门

Nele Verbiest, Ph.D

Data Scientist @PythonPredictions

前向逐步变量选择流程

  • 空集
  • 找到最优变量 v1
  • 在与 v1 组合下找到最优变量 v2
  • 在与 v1、v2 组合下找到最优变量 v3
  • ...

(直到加入所有变量,或达到预设数量)

Python 预测分析入门

Python 中的函数

def function_sum(a,b):

s = a + b return(s)
print(function_sum(1,2))
3
Python 预测分析入门

前向逐步流程的实现

  • auc 函数:给定一组变量计算 AUC
  • best_next 函数:结合当前变量返回下一个最优变量
  • 循环直至达到所需变量数
Python 预测分析入门

AUC 函数的实现

from sklearn import linear_model
from sklearn.metrics import roc_auc_score

def auc(variables, target, basetable):

X = basetable[variables] y = basetable[target]
logreg = linear_model.LogisticRegression() logreg.fit(X, y)
predictions = logreg.predict_proba(X)[:,1] auc = roc_auc_score(y, predictions) return(auc)
auc = auc(["age","gender_F"],["target"],basetable)
print(round(auc,2))
0.54
Python 预测分析入门

计算下一个最优变量

def next_best(current_variables,candidate_variables, target, basetable):

best_auc = -1 best_variable = None
for v in candidate_variables: auc_v = auc(current_variables + [v], target, basetable)
if auc_v >= best_auc: best_auc = auc_v best_variable = v
return best_variable
current_variables = ["age","gender_F"] candidate_variables = ["min_gift","max_gift","mean_gift"] next_variable = next_best(current_variables, candidate_variables, basetable) print(next_variable)
min_gift
Python 预测分析入门

前向逐步变量选择流程

candidate_variables = ["mean_gift","min_gift","max_gift",
"age","gender_F","country_USA","income_low"]
current_variables = []
target = ["target"]

max_number_variables = 5 number_iterations = min(max_number_variables, len(candidate_variables)) for i in range(0,number_iterations):
next_var = next_best(current_variables,candidate_variables,target,basetable)
current_variables = current_variables + [next_variable] candidate_variables.remove(next_variable)
print(current_variables)
['max_gift', 'mean_gift', 'min_gift', 'age', 'gender_F']
Python 预测分析入门

Passons à la pratique !

Python 预测分析入门

Preparing Video For Download...