開始使用免費開始

建立邏輯迴歸模型

你可以使用 sklearnlinear_model 模組來建立邏輯迴歸模型。首先,使用 LogisticRegression() 方法建立一個邏輯迴歸模型:

logreg = linear_model.LogisticRegression()

接下來需要將資料提供給邏輯迴歸模型,以便進行擬合。X 包含預測變數,而 y 包含目標變數。

X = basetable[["predictor_1","predictor_2","predictor_3"]]`
y = basetable[["target"]]
logreg.fit(X,y)

在這個練習中,你會使用三個預測變數來建立你的第一個預測模型。

本練習屬於課程

Python 預測分析入門

檢視課程

練習說明

  • sklearn 匯入方法 linear_model
  • basetable 已載入為 basetable。注意欄位「gender」已轉換為 gender_F,以便可作為預測變數使用。建立一個包含預測變數 agegender_Ftime_since_last_gift 的 DataFrame X
  • 建立一個包含目標變數的 DataFrame y
  • 建立一個邏輯迴歸模型。
  • 在提供的 basetable 上擬合這個邏輯迴歸模型。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import linear_model from sklearn.
from ____ import ____

# Create a DataFrame X that only contains the candidate predictors age, gender_F and time_since_last_gift.
X = ____[[____, ____, ____]]

# Create a DataFrame y that contains the target.
y = ____[[____]]

# Create a logistic regression model logreg and fit it to the data.
logreg = ____.____
logreg.____(____, ____)
編輯並執行程式碼