在Scikit-Learn对一组数据运行方差阈值后,它删除了几个特征。我觉得我在做一些简单而愚蠢的事情,但我想保留其余功能的名称。以下代码:
def VarianceThreshold_selector(data):
selector = VarianceThreshold(.5)
selector.fit(data)
selector = (pd.DataFrame(selector.transform(data)))
return selector
x = VarianceThreshold_selector(data)
print(x)
更改以下数据(这只是行的一小部分):
Survived Pclass Sex Age SibSp Parch Nonsense
0 3 1 22 1 0 0
1 1 2 38 1 0 0
1 3 2 26 0 0 0
插入到这个(同样只是行的一小部分)
0 1 2 3
0 3 22.0 1 0
1 1 38.0 1 0
2 3 26.0 0 0
使用get_support方法,我知道这些是Pclass、Age、Sibsp和Parch,所以我希望它们返回的内容更像:
Pclass Age Sibsp Parch
0 3 22.0 1 0
1 1 38.0 1 0
2 3 26.0 0 0
是否有简单的方法来做到这一点?我是Scikit Learn的新手,所以我可能只是在做一些愚蠢的事情。
这样的东西会有帮助吗?如果您向它传递一个pandas数据框架,它将获得列,并使用您提到的get_support
按列的索引迭代列列表,以仅提取满足方差阈值的列标题。
>>> df
Survived Pclass Sex Age SibSp Parch Nonsense
0 0 3 1 22 1 0 0
1 1 1 2 38 1 0 0
2 1 3 2 26 0 0 0
>>> from sklearn.feature_selection import VarianceThreshold
>>> def variance_threshold_selector(data, threshold=0.5):
selector = VarianceThreshold(threshold)
selector.fit(data)
return data[data.columns[selector.get_support(indices=True)]]
>>> variance_threshold_selector(df, 0.5)
Pclass Age
0 3 22
1 1 38
2 3 26
>>> variance_threshold_selector(df, 0.9)
Age
0 22
1 38
2 26
>>> variance_threshold_selector(df, 0.1)
Survived Pclass Sex Age SibSp
0 0 3 1 22 1
1 1 1 2 38 1
2 1 3 2 26 0
我来到这里寻找一种方法来获得transform()
或fit_transform()
返回数据帧,但我怀疑它不支持。
但是,您可以像这样更清晰地划分数据子集:
data_transformed = data.loc[:, selector.get_support()]
可能有更好的方法来做到这一点,但对于那些感兴趣的人来说,这里是我的做法:
def VarianceThreshold_selector(data):
#Select Model
selector = VarianceThreshold(0) #Defaults to 0.0, e.g. only remove features with the same value in all samples
#Fit the Model
selector.fit(data)
features = selector.get_support(indices = True) #returns an array of integers corresponding to nonremoved features
features = [column for column in data[features]] #Array of all nonremoved features' names
#Format and Return
selector = pd.DataFrame(selector.transform(data))
selector.columns = features
return selector
由于我对Jarad的函数有一些问题,我将它与pteehan的解决方案混合在一起,我发现这更可靠。我还添加了NA替换作为标准,因为VarianceThreshold不喜欢NA值。
def variance_threshold_select(df, thresh=0.0, na_replacement=-999):
df1 = df.copy(deep=True) # Make a deep copy of the dataframe
selector = VarianceThreshold(thresh)
selector.fit(df1.fillna(na_replacement)) # Fill NA values as VarianceThreshold cannot deal with those
df2 = df.loc[:,selector.get_support(indices=False)] # Get new dataframe with columns deleted that have NA values
return df2
如何将其作为代码?
columns = [col for col in df.columns]
low_var_cols = []
for col in train_file.columns:
if statistics.variance(df[col]) <= 0.1:
low_var_cols.append(col)
然后从数据框中删除列?
您也可以使用Pandas来设置阈值
data_new = data.loc[:, data.std(axis=0) > 0.75]