【问题标题】:Random Forest: How to add more features to a sparse matrix, and identify the items in feature importance?随机森林:如何向稀疏矩阵添加更多特征,并识别特征重要性的项目?
【发布时间】:2021-12-08 17:23:23
【问题描述】:

我需要使用词袋 (BOW) 生成的特征,以及随机森林模型中的额外特征(例如 Grp 和评分)。

  1. 由于 BOW 是一个稀疏矩阵,我如何添加额外的特征来创建一个新的稀疏矩阵?目前,我将稀疏矩阵转换为密集矩阵并连接额外的特征来创建一个df(例如df 2)。有没有办法将额外的特征添加到 BOW 稀疏矩阵中?

  2. 如果我们使用稀疏矩阵作为 X 训练,我如何识别具有特征重要性的项目?目前我使用的是df2的列。

谢谢

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ensemble import RandomForestClassifier


bards_words =["The fool doth think he is wise,",
"man fool"]

vect = CountVectorizer()

bow=vect.fit_transform(bards_words)

vocab=vect.vocabulary_

new_vocab = dict([(value, key) for key, value in vocab.items()])

df0 = pd.DataFrame(bow.toarray())
df0.rename(columns=new_vocab , inplace=True)

df1 = pd.DataFrame({'Grp': ['3' , '10'],
                   'Rating': ['1', '2']
                   })



df2=pd.concat([df0, df1], axis=1)

X_train=df2.values

forest = RandomForestClassifier(n_estimators = 500, random_state=0) 
forest = forest.fit(X_train, y_train)
feature_importances = pd.DataFrame(forest.feature_importances_, index = df2.columns, columns=['importance']).sort_values('importance', ascending=False)

【问题讨论】:

    标签: python random-forest


    【解决方案1】:

    只需使用稀疏数据结构。目前,您将稀疏矩阵转换为密集矩阵,再将数据帧转换为另一个数据帧,再转换为密集矩阵。效率不高。

    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.ensemble import RandomForestClassifier
    from scipy import sparse
    import numpy as np
    import pandas as pd
    
    bards_words =["The fool doth think he is wise,",
    "man fool"]
    
    df1 = pd.DataFrame({'Grp': ['3' , '10'],
                       'Rating': ['1', '2']
                       })
    
    vect = CountVectorizer()
    bow=vect.fit_transform(bards_words)
    
    # Stack the two df1 columns onto the left of the sparse matrix
    bow = sparse.hstack((sparse.csr_matrix(df1.astype(int).values), bow))
    
    # Keep track of features
    features = np.concatenate((df1.columns.values, vect.get_feature_names()))
    
    >>> features
    array(['Grp', 'Rating', 'doth', 'fool', 'he', 'is', 'man', 'the', 'think',
           'wise'], dtype=object)
    
    >>> bow.A
    array([[ 3,  1,  1,  1,  1,  1,  0,  1,  1,  1],
           [10,  2,  0,  1,  0,  0,  1,  0,  0,  0]])
    
    # Do your random forest
    forest = RandomForestClassifier(n_estimators = 500, random_state=0) 
    forest = forest.fit(bow, y_train)
    feature_importances = pd.DataFrame(forest.feature_importances_, index = features, columns=['importance']).sort_values('importance', ascending=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-09
      • 2021-08-29
      • 2015-08-24
      • 2013-09-25
      • 2015-05-12
      • 1970-01-01
      • 2020-05-26
      • 2020-08-28
      相关资源
      最近更新 更多