實作 logistic regression
這題和先前你用 scipy.optimize.minimize 從零實作 linear regression 的練習非常相似。不過這次要最小化的是 logistic loss,並和 scikit-learn 的 LogisticRegression 做比較(我們把 C 設為很大的值以關閉正規化;第 3 章會再詳細說明!)。
前一題的 log_loss() 函式已經在你的環境中定義好,且 sklearn 的乳癌預測資料集(取前 10 個特徵並已標準化)也已載入到變數 X 和 y。
本練習屬於課程
Python 中的線性分類器
練習說明
- 在
range()中填入訓練樣本數。 - 填寫 logistic regression 的損失函式。
- 將係數與 sklearn 的
LogisticRegression比較。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# The logistic loss, summed over training examples
def my_loss(w):
s = 0
for i in range(____):
raw_model_output = w@X[i]
s = s + ____(raw_model_output * y[i])
return s
# Returns the w that makes my_loss(w) smallest
w_fit = minimize(my_loss, X[0]).x
print(w_fit)
# Compare with scikit-learn's LogisticRegression
lr = LogisticRegression(fit_intercept=False, C=1000000).fit(X,y)
print(lr.coef_)