一、基于惩罚的方法 L1 正则化示例
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_breast_cancer
breast_cancer = load_breast_cancer()
X, y = breast_cancer.data, breast_cancer.target
# 归一化
mms = MinMaxScaler()
x = mms.fit_transform(X)
# L1正则化拟合数据
lr = LogisticRegression(penalty='l2',C=0.01, solver='liblinear')
lr.fit(x, y)
# 获取模型特征系数
lr.coef_[0]
二、基于树模型的方法 之 随机森林分类器示例
使用 sklearn 中的SelectFromModel,模型得分是由estimator打出来的,也就是选取的模型。模型选定以后,就可以给feature进行打分,所以模型必须要具备以下两个属性中的一个:coef or feature importance。
from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
# 加载数据集
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
selector = SelectFromModel(estimator=RandomForestClassifier()).fit(X, y)
{'选取的最优特征为':selector.get_feature_names_out()}