我试着用滑雪板构建一个文本分类器。其想法是:
我已经成功地设置了如下所示:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
vectorizer = TfidfVectorizer()
x_train = vectorizer.fit_transform(df_train["input"])
selector = SelectKBest(f_classif, k=min(20000, x_train.shape[1]))
selector.fit(x_train, df_train["label"].values)
x_train = selector.transform(x_train)
classifier = LogisticRegression()
classifier.fit(x_train, df_train["label"])现在,我想将所有这些都打包到一个管道中,并共享这个管道,以便其他人可以使用它来处理自己的文本数据。然而,我不知道如何让SelectKBest实现与上面相同的行为,即接受min(20000,来自向量器输出的n_features )为k。如果我简单地将其保留为k=20000,则当向新的语料库配置少于20k矢量化功能时,管道就不能工作(抛出一个错误)。
pipe = Pipeline([
            ("vect",TfidfVectorizer()),
            ("selector",SelectKBest(f_classif, k=20000)),
            ("clf",LogisticRegression())])发布于 2020-06-13 08:23:47
正如@vivek所指出的,您需要重写SelectKBest的SelectKBest方法,并将您的逻辑添加到其中,如下所示:
class MySelectKBest(SelectKBest):
    def _check_params(self, X, y):
        if (self.k >= X.shape[1]):
            warnings.warn("Less than %d number of features found, so setting k as %d" % (self.k, X.shape[1]),
                      UserWarning)
            self.k = X.shape[1]
        if not (self.k == "all" or 0 <= self.k):
            raise ValueError("k should be >=0, <= n_features = %d; got %r. "
                             "Use k='all' to return all features."
                             % (X.shape[1], self.k)) 我还设置了一个警告,以防发现的功能数量少于阈值设置。现在,让我们看一个相同的工作示例:
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
import warnings
categories = ['alt.atheism', 'comp.graphics',
              'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware',
              'comp.windows.x', 'misc.forsale', 'rec.autos']
newsgroups = fetch_20newsgroups(categories=categories)
y_true = newsgroups.target
# newsgroups result in 47K odd features after performing TFIDF vectorizer
# Case 1: When K < No. of features - the regular case
pipe = Pipeline([
            ("vect",TfidfVectorizer()),
            ("selector",MySelectKBest(f_classif, k=30000)),
            ("clf",LogisticRegression())])
pipe.fit(newsgroups.data, y_true)
pipe.score(newsgroups.data, y_true)
#0.968
#Case 2: When K > No. of cases - the one with an issue
pipe = Pipeline([
            ("vect",TfidfVectorizer()),
            ("selector",MySelectKBest(f_classif, k=50000)),
            ("clf",LogisticRegression())])
pipe.fit(newsgroups.data, y_true)
UserWarning: Less than 50000 number of features found, so setting k as 47407
pipe.score(newsgroups.data, y_true)
#0.9792https://stackoverflow.com/questions/62342923
复制相似问题