邏輯回歸:
是一種廣義的線性回歸分析模型
邏輯回歸針對的目標變量是類別型的,參數估值上,采用最大似然法。
分類問題可以轉換成概率的都是邏輯回歸的常見場景,如:
會不會逾期(風控)
會不會是流失客戶(會員運營)
會不會點擊(CTR預估、推薦系統、搜索)
優點:模型簡單、可解釋性強
缺點:不能做特征交叉
代碼演示
需求:探究不同職業的人使用優惠券的可能
1 數據預處理
注意:剔除異常值、處理缺失值,排除共線性問題
1.1 本文數據預覽
1.2 過采樣處理樣本不均衡問題處理
1.2.1 選定自變量 因變量
x = df[['job_admin.', 'job_blue-collar', 'job_entrepreneur', 'job_housemaid', 'job_management', 'job_retired', 'job_self-employed', 'job_services', 'job_student', 'job_technician', 'job_unemployed', 'job_unknown']] y = df['coupon_ind']
1.2.2 查看是否均衡,發現樣本不均衡
也可以使用 df.coupon_ind.value_counts() 來查看
1.2.3 進行過采樣處理
from imblearn.over_sampling import SMOTE smo = SMOTE(random_state=11) x, y= smo.fit_sample(x, y)
2 划分訓練集、測試集
from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split( x, y, test_size=0.3, random_state=11)
3 邏輯回歸模型
from sklearn.linear_model import LogisticRegression lr = LogisticRegression() lr.fit(x_train, y_train)
# 回歸系數
lr.coef_
# 截距
lr.intercept_
4模型評估
4.1 使用模型進行預測
y_pred_train = lr.predict(x_train)
y_pred_test = lr.predict(x_test)
4.2 查看得分
from sklearn.metrics import accuracy_score accuracy_score(y_train, y_pred_train)
4.3 查看召回率
from sklearn.metrics import auc, roc_curve fpr, tpr, _ = roc_curve(y_train, y_pred_train) roc_auc = auc(fpr,tpr) roc_auc