相关性分析
最佳苦于如何从众多特征中找到最佳特征,老师建议先使用相关性分析,数据分析小白来记录一下这个过程。
发现一个很好的方法:sklearn.feature_selection 的 SelectKBest
互信息法
- 互信息法主要两个点:
(1)注意区分离散数据和连续数据
(2)输出一般为索引,但只获得索引对特征量大的数据集非常不友好,需要想办法获得特征名
针对(1)可以考虑重写SelectKBest的fit方法
参考:如何使用混合离散和连续特征的互信息来选择KBest?
class SelectKBestCustom(SelectKBest):
def fit(self, X, y,discrete_features='auto'):
X, y = check_X_y(X, y, ['csr', 'csc'], multi_output=True)
if not callable(self.score_func):
raise TypeError("the score function should be a callable, %s (%s)""was passed."%(self.score_func, type(self.score_func)))
self._check_params(X,y)
score_func_ret = self.score_func(X, y, discrete_features)
if isinstance(score_func_ret, (list, tuple)):
self.scores_, self.pvalues_ = score_func_ret
self.pvalues_ = np.asarray(self.pvalues_)
else:
self.scores_ = score_func_ret
self.pvalues_ = None
self.scores_ = np.asarray(self.scores_)
return self
最后调用自己的类
selector_mic = SelectKBestCustom(mic, k=12)
#discrete_features输入离散变量的索引
selector_mic.fit(x_array, y_array,discrete_features = [])
selector_mic.transform(x_array)
针对(2)对于我比较有效的方法如下:
cols = selector_mic.get_support(indices=True)
features_new_mic = data_frame.columns[cols]
卡方验证
卡方验证也是比较推荐的相关性验证方法,同样使用SelectKBest
这里并没有用改写的类,其一是因为chi2方法本身只支持两个参数,其二是我其实也并不清楚卡方验证是不是本身就会考虑离散型数据和连续型数据,有懂的小伙伴欢迎解答~
selector_chi2 = SelectKBest(chi2, k=12)
selector_chi2.fit(x_array, y_array)
selector_chi2.transform(x_array)
cols_chi2 = selector_chi2.get_support(indices=True)
features_new_chi2 = data_frame.columns[cols_chi2]