Logistic regression 與特徵選擇
在這個練習中,你會使用 L1 正規化,對電影評論情緒資料集進行特徵選擇。特徵與目標值已經幫你載入到 X_train 和 y_train。
我們會使用 scikit-learn 的 GridSearchCV()(先修課程已介紹過)來搜尋最佳的 C 值。
本練習屬於課程
Python 中的線性分類器
練習說明
- 建立一個使用 L1 正規化的邏輯斯迴歸物件。
- 找出能最小化交叉驗證誤差的
C值。 - 印出在此
C值下被選中的特徵數量。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Specify L1 regularization
lr = LogisticRegression(solver='liblinear', ____)
# Instantiate the GridSearchCV object and run the search
searcher = GridSearchCV(lr, {'C':[0.001, 0.01, 0.1, 1, 10]})
searcher.fit(X_train, y_train)
# Report the best parameters
print("Best CV params", searcher.best_params_)
# Find the number of nonzero coefficients (selected features)
best_lr = searcher.best_estimator_
coefs = best_lr.____
print("Total number of features:", coefs.size)
print("Number of selected features:", np.count_nonzero(coefs))