簡體   English   中英

使用 GridSearchCV scikit-learn 進行管道中的 KMeans

[英]KMeans in pipeline with GridSearchCV scikit-learn

我想對我的文本數據執行聚類。 為了找到最佳的文本預處理參數,我制作了管道並將其放入 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在哪里

score = make_scorer(my_f1, greater_is_better=True)

my_f1的形式是:

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

並且專為聚類設計

所以我的問題是:如何使它起作用? 如何通過labels_pred ,當作為 kmeans 性質我只能做

gs_clf.fit(data)

而在分類中有可能:

gs_clf.fit(data, labels_true)

我知道我可以編寫自定義函數,就像我在MyLemmanization所做的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 或其他聚類算法做什么?

您可以創建自定義 K-means,在其中使用標記數據構建初始質心,然后讓 K-means 發揮其魔力。

您可能還想嘗試k-NN ,即使它是一種不同的方法。

更重要的是,你有一個概念上的問題。 你說你使用聚類的原因之一是因為它可能會發現以前未知的主題,但你也說你想通過與已知標簽進行比較來評估性能。 但是,您不能同時擁有兩者...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM