手動遞迴式特徵消除(RFE)
現在我們已經建立了一個糖尿病分類器,來看看能不能在不大幅犧牲模型準確率的情況下,減少特徵數量。
在第二行程式碼中,會從原始的 DataFrame 中選取特徵。請調整這個選取。
StandardScaler() 物件已經預先定義為 scaler,LogisticRegression() 已預先定義為 lr。
所有必要的函式與套件也都已經載入。
本練習屬於課程
Python 的降維
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Remove the feature with the lowest model coefficient
X = diabetes_df[['pregnant', 'glucose', 'diastolic', 'triceps', 'insulin', 'bmi', 'family', 'age']]
# Performs a 25-75% train test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
# Scales features and fits the logistic regression model
lr.fit(scaler.fit_transform(X_train), y_train)
# Calculates the accuracy on the test set and prints coefficients
acc = accuracy_score(y_test, lr.predict(scaler.transform(X_test)))
print(f"{acc:.1%} accuracy on test set.")
print(dict(zip(X.columns, abs(lr.coef_[0]).round(2))))