实例
数据集
笔记本

笔记本

删除低方差特征

删除方差不满足某个阈值的特征,达到数据降维的目的。
Dave上传于 3 years ago
标签
暂无标签
浏览600
笔记本内容

删除低方差特征 #

特征选择的一个基本方法是 VarianceThreshold ,它会删除所有方差不满足某个阈值的特征。这是什么意思呢?假设某个特征所有的值都是同一个,

比如,客户价值挖掘你发现一个特征是 “地球人”,非常大概率所有的样本都为 True,这时,该特征的方差为 0 。我们大概率是想删除这样的特征的,

对于伯努利随机变量,这些变量的方差可以由如下公式计算获得。

$$Var[x] = p(1-p)$$

于是我们可以通过 VarianceThreshold 来筛选那些方差小于阈值的特征,并从数据中删除。

from sklearn.feature_selection import VarianceThreshold
import pandas as pd
import matplotlib.pyplot as plt
X = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 0],
    [0, 1, 1],
    [0, 1, 0],
    [1, 1, 1],
    [0, 1, 1],
    [0, 0, 1],
    [0, 1, 0],
    [1, 1, 0],
    [0, 1, 1],
    [0, 0, 1],
]
df = pd.DataFrame(X, columns=['Feature_A', 'Feature_B', 'Feature_C'])
df.head()
Feature_A Feature_B Feature_C
0 0 0 1
1 0 1 0
2 1 0 0
3 0 1 1
4 0 1 0
ax = plt.subplot(111, projection='3d')
ax.scatter(df['Feature_A'], df['Feature_B'], df['Feature_C'], c='b',s=10);

我们可以尝试删除那些 0 或 1 超过 80% 的特征。

var = .7 * (1 - .7)
sel = VarianceThreshold(threshold=(var))
df_select = pd.DataFrame(sel.fit_transform(df), columns=list(sel.get_feature_names_out()))

满足条件的 Feature_A 被删除了。

df_select
Feature_B Feature_C
0 0 1
1 1 0
2 0 0
3 1 1
4 1 0
5 1 1
6 1 1
7 0 1
8 1 0
9 1 0
10 1 1
11 0 1
ax = plt.subplot()
plt.scatter(df_select['Feature_B'], df_select['Feature_C'], c='b',s=10);
评论(0条)