การเลือกตัวแปรแบบ Forward Stepwise

การวิเคราะห์เชิงพยากรณ์เบื้องต้นด้วย Python

Nele Verbiest, Ph.D

Data Scientist @PythonPredictions

ขั้นตอนการเลือกตัวแปรแบบ Forward Stepwise

  • เริ่มจากเซตว่าง
  • หาตัวแปรที่ดีที่สุด $v_1$
  • หาตัวแปรที่ดีที่สุด $v_2$ ร่วมกับ $v_1$
  • หาตัวแปรที่ดีที่สุด $v_3$ ร่วมกับ $v_1, v_2$
  • ...

(จนกว่าจะเพิ่มตัวแปรครบทุกตัว หรือครบจำนวนที่กำหนด)

การวิเคราะห์เชิงพยากรณ์เบื้องต้นด้วย Python

ฟังก์ชันใน Python

def function_sum(a,b):

s = a + b return(s)
print(function_sum(1,2))
3
การวิเคราะห์เชิงพยากรณ์เบื้องต้นด้วย Python

การนำขั้นตอน Forward Stepwise ไปใช้งาน

  • ฟังก์ชัน 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

ขั้นตอนการเลือกตัวแปรแบบ Forward Stepwise

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

มาฝึกกันเถอะ!

การวิเคราะห์เชิงพยากรณ์เบื้องต้นด้วย Python

Preparing Video For Download...