KMeans正在使用GridSearchCV scikitlearn

2024-06-07 14:10:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对我的文本数据执行聚类。为了找到最好的文本预处理参数,我制作了pipeline并将其放入GridSearchCV中:

text_clf = Pipeline([('vect1', CountVectorizer(analyzer = "word"),
                   ('myfun', MyLemmanization(lemmatize=True,
                                           leave_other_words = True)),
                   ('vect2', CountVectorizer(analyzer = "word",
                                          max_df=0.95, min_df=2,
                                          max_features=2000)),
                   ('tfidf', TfidfTransformer()),
                   ('clust',   KMeans(n_clusters=10, init='k-means++',
                                      max_iter=100, n_init=1, verbose=1))])
parameters = {'myfun__lemmatize': (True, False),
              'myfun__leave_other_words': (True, False)}
gs_clf = GridSearchCV(text_clf, parameters, n_jobs=1, scoring=score)
gs_clf = gs_clf.fit(text_data)

其中score

^{pr2}$

并且my_f1的形式是:

def my_f1(labels_true, labels_pred):
    #fansy stuff goes here

并且specially是为集群而设计的

所以我的问题是:如何使之有效?如何通过labels_pred,当作为一个kmeans的自然我只能做

gs_clf.fit(data)

分类时有可能:

gs_clf.fit(data, labels_true)

我知道我可以编写自定义函数,就像我对MyLemmanization所做的那样:

class MyLemmanization(BaseEstimator, TransformerMixin):

def __init__(self,  lemmatize=True, leave_other_words=True):
    #some code here

def do_something_to(self, X):
    # some code here
    return articles

def transform(self, X, y=None):
    return self.do_something_to(X)  # where the actual feature extraction happens

def fit(self, X, y=None):
    return self  # generally does nothing

但是如何以及必须对KMeans或其他聚类算法做些什么呢?在


Tags: textselfgstruelabelsdefmaxfit

热门问题