0

在 TfidfVectorizer 输出上应用 SelectKBest 后,我​​们在文档术语矩阵中获得了如此多的重复特征。我想删除那些重复的功能。我尝试了一些方法来删除这些冗余功能,但是我需要手动执行很多步骤,如下所示:

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer 
from sklearn.feature_selection import SelectKBest, chi2

text = ["How is your brother? ", 
          "How are your siblings? ", 
          "Who is coming? ", 
          "Who is going? "
         ]
target = [1,1, 0,0]
df = pd.DataFrame({'text': text, 'target': target})
vectorizer = TfidfVectorizer(ngram_range=(1, 5), analyzer = 'char')
sparsedtm = vectorizer.fit_transform(df['text'])

## Selecting best features
k_best = SelectKBest(chi2, k=5)
bestfeat = k_best.fit_transform(sparsedtm, df['target'])
mask = k_best.get_support() #list of booleans
## Filtered features using chi-square
new_features = [] # The list of your K best features
for bool, feature in zip(mask, vectorizer.get_feature_names()):
    if bool:
        new_features.append(feature)
        
newdf = pd.DataFrame(bestfeat.todense(), columns=new_features)
print(newdf)

我的输出如下所示:

      r         wh       who        who     who i
0  0.264662  0.000000  0.000000  0.000000  0.000000
1  0.168275  0.000000  0.000000  0.000000  0.000000
2  0.000000  0.117124  0.117124  0.117124  0.117124
3  0.000000  0.123835  0.123835  0.123835  0.123835

我想从此 DTM中删除whwho 和。who i为了删除这些冗余功能,我从 SO 中找到了以下代码:

## Removing similar column from a Document Term Matrix
class removeSameCols(object) :
  def __init__(self) :
    pass

  def _delSameCols(self, df) :
    cols = []
    for i in range(df.shape[1]) :
      for j in range(i+1, df.shape[1]) :
        if (df.iloc[:,i].dtype!='O') | (df.iloc[:,j].dtype!='O') :
          if np.array_equal(df.iloc[:,i], df.iloc[:,j]) :
            cols.append(df.columns[j])
    cols = list(set(cols))
    return cols

  def transform(self, x) :
    dat = x.copy()
    lstcols = list(set(dat.columns) - set(self.lstRemCols))
    return dat.loc[:, lstcols]

  def fit(self, x, y=None) :
    dat = x.copy()
    self.lstRemCols = self._delSameCols(dat)
#     print(self.lstRemCols)
    return self

rmCols = Pipeline([('remCols', removeSameCols())])
x_1 = rmCols.fit_transform(newdf)
print(x_1)

输出是:

      wh         r
0  0.000000  0.264662
1  0.000000  0.168275
2  0.117124  0.000000
3  0.123835  0.000000

现在,我想对其他一些样本进行转换,如下所示:

vecout = vectorizer.transform(df['text']) ## Using same training samples for transformation 
ch2test = k_best.transform(vecout) 
dftest = pd.DataFrame(ch2test.todense(), columns = new_features) 
x_2 = rmCols.transform(dftest) 
print(x_2)

输出是:

        wh       r
0   0.000000    0.264662
1   0.000000    0.168275
2   0.117124    0.000000
3   0.123835    0.000000

如何执行上述所有步骤Pipeline以避免手动执行如此多的中间步骤?任何帮助,将不胜感激!

4

1 回答 1

0

对我来说唯一明显的障碍是您依赖于删除转换器中的列名,而 sklearn 的转换器输出 numpy 数组。修改您的转换器以在整个过程中假定 numpy 数组并保存需要删除的列索引而不是它们的名称应该相对容易。您还可以将 sklearn SelectorMixinmixin 用于特征选择类,以节省一些样板文件(docs,但您需要仔细阅读一些代码才能使其有意义)。

但是,要检索列名,您需要使用 tfidf's get_feature_names,然后按自定义转换器中的选定列进行子集化。

于 2021-03-26T17:51:48.110 回答