手动递归特征消除
既然我们已经创建了一个糖尿病分类器,来看一看能否在不显著降低模型准确率的情况下减少特征数量。
在第二行代码中,从原始 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))))