【问题标题】:How to extract coefficients for TF-IDF features?如何提取 TF-IDF 特征的系数?
【发布时间】:2019-07-03 11:55:45
【问题描述】:

我有一个数据集,我在其中使用文本列来预测一些数字列。

我的终极问题是:文本列中的哪些词与更高/更低的分数相关联?

所以我的管道是首先对我的文本列进行矢量化,然后使用岭回归。但是在我构建了这个管道之后,如何提取向量器特征名称上的系数?

import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split

# This is my toy data 
d = {'text': ["I am a a string", "And I am a string", "I, too am string", "And me", "Me too"], 
     'target': [3, 4, 14, 6, 7]}
df = pd.DataFrame(d)

X_train, X_test, y_train, y_test= train_test_split(df['text'], df['target'], 
                                                   test_size=0.3, random_state=42)


# Here is a vectorizer 
vect = TfidfVectorizer(stop_words='english')
X_train_vect = vect.fit_transform(X_train)

# Here is a ridge regressor
model = Ridge(random_state=42)
model.fit(X_train_vect, y_train)

# Now we make a pipeline
pipe = Pipeline([('vect',vect),('model',model)])
y_pred = pipe.predict(X_test)

我将如何从这里提取单词作为系数? 例如:"I am": 0.05 或其他任何内容

【问题讨论】:

    标签: scikit-learn nlp


    【解决方案1】:
    idf = vect.idf_
    print (dict(zip(vect.get_feature_names(), idf)))
    

    应该这样做。

    【讨论】:

      【解决方案2】:

      您没有以最佳方式使用pipeline。您可以使用管道本身执行.fit(),如下所示。

      # Here is a vectorizer 
      vect = TfidfVectorizer(stop_words='english')
      
      # Here is a ridge regressor
      model = Ridge(random_state=42)
      
      # Now we make a pipeline
      pipe = Pipeline([('vect',vect),('model',model)])
      pipe.fit(X_train, y_train)
      pipe.predict(X_test)
      
      # array([8.07176068, 7.21966856])
      

      现在,要知道每个特征使用对应的系数:

      # for sklearn >= 0.21.0
      list(zip(pipe['vect'].get_feature_names(), pipe['model'].coef_ ))
      
      # for sklearn < 0.21.0
      list(zip(pipe.named_steps.vect.get_feature_names(), pipe.named_steps.model.coef_ ))
      

      【讨论】:

        猜你喜欢
        • 2020-09-27
        • 2011-02-24
        • 2014-07-10
        • 2016-09-07
        • 2020-01-18
        • 2020-09-22
        • 2018-05-27
        • 1970-01-01
        • 2012-02-29
        相关资源
        最近更新 更多