怅然|不容忽视!机器学习中的特征选择初探【sklearn实战】( 二 )


from sklearn.datasets import load_iris from sklearn.feature_selection import VarianceThreshold import numpy as np ? # 加载数据集 iris = load_iris() X = iris.data y = iris.target ? # 打印数据集中的特征数和每个特征的方差 print('原数据集中的特征数:\n', X.shape[1], '\n') print('原数据集中不同特征的方差:\n', np.var(X, axis=0), '\n') ? # 使用VarianceThreshold来过滤掉方差在0.6以下的特征 selector = VarianceThreshold(threshold=0.6) X_new = selector.fit_transform(X) ? # 打印新数据集的特征数 print('方差阈值法选择的特征数:\n', X_new.shape[1])输出为:
原数据集中的特征数: 4? 原数据集中不同特征的方差: [0.68112222 0.18871289 3.09550267 0.57713289]? 方差阈值法选择的特征数: 2
怅然|不容忽视!机器学习中的特征选择初探【sklearn实战】那么接下来 , 我们以新老特征集分别来训练一个模型来看看效果 。
首先看看原数据集:
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=101) model = LogisticRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test) acc = accuracy_score(y_test, y_pred) print('准确率:', acc)输出为:
准确率: 0.9736842105263158然后我们看看新数据集:
X_train, X_test, y_train, y_test = train_test_split(X_new, y, random_state=101) model = LogisticRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test) acc = accuracy_score(y_test, y_pred) print('准确率:', acc)输出为:
准确率: 0.9473684210526315可以看到 , 我们在仅保留了两个特征的情况下 , 仅仅牺牲了一点准确率 。
怅然|不容忽视!机器学习中的特征选择初探【sklearn实战】
怅然|不容忽视!机器学习中的特征选择初探【sklearn实战】【怅然|不容忽视!机器学习中的特征选择初探【sklearn实战】】事实上 , 在这个例子中 , 这种通过牺牲模型性能来换取计算性能的操作意义不大 , 因为这个数据集仅有150个样本、4个特征 , 但是当我们面临成千上万的特征、数以亿计的样本时 , 我们就有必要进行权衡了 。 当然 , 特征选择的目的远不止于此 , 在之后的探讨中 , 我们会发现它的更多优点 。


推荐阅读