我是一个机器学习的新手,目前在解读我的第一个程序的结果时遇到了困难。以下是我的设置:
我有一个书评数据集。这些书可以被标记为大约1600个限定词中的任意数量。评论这些书的人也可以用这些限定词标记自己,以表明他们喜欢阅读带有该标签的内容。
数据集中为每个限定词设置了一列。对于每条评论,如果某个限定词同时用于标记书籍和评论者,则记录值为1。如果在某条评论中某个限定词没有“匹配”,则记录值为0。
还有一个“评分”列,每条评论都有一个1到5的整数(该评论的“星级评分”)。我的目标是确定哪些特征对获得高分最重要。
这是我目前的代码(https://gist.github.com/souldeux/99f71087c712c48e50b7):
def determine_feature_importance(df): #Determines the importance of individual features within a dataframe #Grab header for all feature values excluding score & ids features_list = df.columns.values[4::] print "Features List: \n", features_list #set X equal to all feature values, excluding Score & ID fields X = df.values[:,4::] #set y equal to all Score values y = df.values[:,0] #fit a random forest with near-default paramaters to determine feature importance print '\nCreating Random Forest Classifier...\n' forest = RandomForestClassifier(oob_score=True, n_estimators=10000) print '\nFitting Random Forest Classifier...\n' forest.fit(X,y) feature_importance = forest.feature_importances_ print feature_importance #Make importances relative to maximum importance print "\nMaximum feature importance is currently: ", feature_importance.max() feature_importance = 100.0 * (feature_importance / feature_importance.max()) print "\nNormalized feature importance: \n", feature_importance print "\nNormalized maximum feature importance: \n", feature_importance.max() print "\nTo do: set fi_threshold == max?" print "\nTesting: setting fi_threshhold == 1" fi_threshold=1 #get indicies of all features over fi_threshold important_idx = np.where(feature_importance > fi_threshold)[0] print "\nRetrieved important_idx: ", important_idx #create a list of all feature names above fi_threshold important_features = features_list[important_idx] print "\n", important_features.shape[0], "Important features(>", fi_threshold, "% of max importance:\n", important_features #get sorted indices of important features sorted_idx = np.argsort(feature_importance[important_idx])[::-1] print "\nFeatures sorted by importance (DESC):\n", important_features[sorted_idx] #generate plot pos = np.arange(sorted_idx.shape[0]) + .5 plt.subplot(1,2,2) plt.barh(pos,feature_importance[important_idx][sorted_idx[::-1]],align='center') plt.yticks(pos, important_features[sorted_idx[::-1]]) plt.xlabel('Relative importance') plt.ylabel('Variable importance') plt.draw() plt.show() X = X[:, important_idx][:, sorted_idx] return "Feature importance determined"
我成功生成了一个图表,但老实说,我不确定这个图表的含义是什么。据我所知,这是在显示任何给定特征对评分变量的影响强度。但是,我意识到这可能是一个愚蠢的问题,我如何知道这种影响是正面的还是负面的?
回答:
简而言之,你不知道。决策树(随机森林的构建块)不是这样工作的。如果你使用线性模型,那么区分特征是“正面”还是“负面”就相当简单,因为它对最终结果的唯一影响是被加(带权重)。仅此而已。然而,决策树的集合可以为每个特征设定任意复杂的规则,例如“如果书的封面是红色的并且超过100页,如果书中包含龙,则得高分”,但“如果书的封面是蓝色的并且超过100页,如果书中包含龙,则得低分”,依此类推。
特征重要性只告诉你哪些特征对决策有贡献,而不是“以何种方式”,因为有时候它会这样起作用,有时候会以另一种方式起作用。
你能做些什么呢?你可以做一些极端的简化——假设你只对在完全没有其他特征的情况下感兴趣的特征,现在——一旦你知道哪些是重要的,你可以计算这个特征在每个类别(在你的例子中是评分)中出现的次数。这样你将得到分布
P(gets score X|has feature Y)
这将或多或少地显示它在(经过边缘化后)是否有正面或负面的影响。