使用Scikit-learn计算信息增益

32

我正在使用Scikit-learn进行文本分类。我想计算每个属性相对于稀疏文档术语矩阵中的类的信息增益。

  • 信息增益被定义为H(Class) - H(Class | Attribute),其中H是熵。
  • 在Weka中,可以使用InfoGainAttribute来计算这个值。
  • 但是我没有在Scikit-learn中找到这个指标。

(有人建议上面的信息增益公式和互信息是相同的度量方法。这也符合维基百科的定义。是否可能在Scikit-learn中使用特定的互信息设置来完成此任务?)


它们是相同的信息增益和互信息:不同还是相等?特征选择:信息增益VS互信息,当我们谈论点间互信息而不是期望互信息时。 - smci
@NickMorgan:在谈论PMI时,它们是相同的;引用一个短暂的来源(第三方论文中的表格已经过期)而不是CV或维基百科是没有帮助的。 - smci
3个回答

31
你可以使用scikit-learn的 mutual_info_classif ,这里有一个示例。
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_selection import mutual_info_classif
from sklearn.feature_extraction.text import CountVectorizer

categories = ['talk.religion.misc',
              'comp.graphics', 'sci.space']
newsgroups_train = fetch_20newsgroups(subset='train',
                                      categories=categories)

X, Y = newsgroups_train.data, newsgroups_train.target
cv = CountVectorizer(max_df=0.95, min_df=2,
                                     max_features=10000,
                                     stop_words='english')
X_vec = cv.fit_transform(X)

res = dict(zip(cv.get_feature_names(),
               mutual_info_classif(X_vec, Y, discrete_features=True)
               ))
print(res)
这将输出一个字典,其中词汇表中的每个属性(即项)作为键,它们的信息增益作为值。
以下是输出的样例。
{'bible': 0.072327479595571439,
 'christ': 0.057293733680219089,
 'christian': 0.12862867565281702,
 'christians': 0.068511328611810071,
 'file': 0.048056478042481157,
 'god': 0.12252523919766867,
 'gov': 0.053547274485785577,
 'graphics': 0.13044709565039875,
 'jesus': 0.09245436105573257,
 'launch': 0.059882179387444862,
 'moon': 0.064977781072557236,
 'morality': 0.050235104394123153,
 'nasa': 0.11146392824624819,
 'orbit': 0.087254803670582998,
 'people': 0.068118370234354936,
 'prb': 0.049176995204404481,
 'religion': 0.067695617096125316,
 'shuttle': 0.053440976618359261,
 'space': 0.20115901737978983,
 'thanks': 0.060202010019767334}

3
这是信息增益还是互信息增益?它们一样吗?@sgDysregulation - Sevval Kahraman
在上述代码中,如果我在对文本进行向量化时保持'binary=True',则会得到不同的互信息结果。理想情况下,分类变量的互信息仅基于存在或不存在,而与计数无关。 - Murali
1
有没有办法用scikit-learn计算每个特征/项与每个类别之间的MI,例如"bible"和"'talk.religion.misc'"之间的MI是多少。IR书籍的章节提供了一些数学知识,但我找不到使用scikit-learn的方法。 - dzieciou

3

以下是使用pandas计算信息增益的提议:

from scipy.stats import entropy
import pandas as pd
def information_gain(members, split):
    '''
    Measures the reduction in entropy after the split  
    :param v: Pandas Series of the members
    :param split:
    :return:
    '''
    entropy_before = entropy(members.value_counts(normalize=True))
    split.name = 'split'
    members.name = 'members'
    grouped_distrib = members.groupby(split) \
                        .value_counts(normalize=True) \
                        .reset_index(name='count') \
                        .pivot_table(index='split', columns='members', values='count').fillna(0) 
    entropy_after = entropy(grouped_distrib, axis=1)
    entropy_after *= split.value_counts(sort=False, normalize=True)
    return entropy_before - entropy_after.sum()

members = pd.Series(['yellow','yellow','green','green','blue'])
split = pd.Series([0,0,1,1,0])
print (information_gain(members, split))

0

使用纯Python:

def ig(class_, feature):
  classes = set(class_)

  Hc = 0
  for c in classes:
    pc = list(class_).count(c)/len(class_)
    Hc += - pc * math.log(pc, 2)
  print('Overall Entropy:', Hc)
  feature_values = set(feature)

  Hc_feature = 0
  for feat in feature_values:

    pf = list(feature).count(feat)/len(feature)
    indices = [i for i in range(len(feature)) if feature[i] == feat]
    clasess_of_feat = [class_[i] for i in indices]
    for c in classes:
        pcf = clasess_of_feat.count(c)/len(clasess_of_feat)
        if pcf != 0:
            temp_H = - pf * pcf * math.log(pcf, 2)
            Hc_feature += temp_H
  ig = Hc - Hc_feature
  return ig    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接