gpt4 book ai didi

python - Sklearn Pipeline : How to build for kmeans, 聚类文本?

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:05 28 4
gpt4 key购买 nike

我有如图所示的文字:

 list1 = ["My name is xyz", "My name is pqr", "I work in abc"]

以上将是使用 kmeans 对文本进行聚类的训练集。

list2 = ["My name is xyz", "I work in abc"]

以上是我的测试集

我已经构建了一个矢量化器和模型,如下所示:

vectorizer = TfidfVectorizer(min_df = 0, max_df=0.5, stop_words = "english", charset_error = "ignore", ngram_range = (1,3))
vectorized = vectorizer.fit_transform(list1)
km=KMeans(n_clusters=2, init='k-means++', n_init=10, max_iter=1000, tol=0.0001, precompute_distances=True, verbose=0, random_state=None, copy_x=True, n_jobs=1)
km.fit(vectorized)

如果我尝试为我的“list2”测试集预测集群:

km.predict(list2)

我收到以下错误:

ValueError: Incorrect number of features. Got 2 features, expected 5

我被告知使用Pipeline 来解决这个问题。所以我写了下面的代码:

pipe = Pipeline([('vect', vectorizer), ('vectorized', vectorized), ('kmeans',km )])

但是我得到了错误:

TypeError                                 Traceback (most recent call last)
/mnt/folder/Text_Mining/<ipython-input-14-321cabc3bf35> in <module>()
----> 1 pipe = Pipeline([('vect', vectorizer), ('vectorized', vectorized), ('kmeans',km )])
/usr/local/lib/python2.7/dist-packages/scikit_learn-0.13-py2.7-linux-x86_64.egg/sklearn/pipeline.pyc in __init__(self, steps)
87 raise TypeError("All intermediate steps a the chain should "
88 "be transforms and implement fit and transform"
---> 89 "'%s' (type %s) doesn't)" % (t, type(t)))
90
91 if not hasattr(estimator, "fit"):
TypeError: All intermediate steps a the chain should be transforms and implement fit and transform' (0, 2) 1.0
(1, 4) 0.57735026919
(1, 3) 0.57735026919
(1, 1) 0.57735026919
(2, 0) 1.0' (type <class 'scipy.sparse.csr.csr_matrix'>) doesn't)

我认为 vectorized 的输出可能没有实现拟合和变换,但在这种特殊情况下我该怎么做呢?我是机器学习的新手。另外,如何从 kmeans 模型中获取标签?当我运行 kmeans 时,我可以使用 km.labels_ 访问集群标签。如何在 Pipeline 中做类似的事情?

最佳答案

你需要做的是使用 list1 训练一个 vectorizer,然后使用相同的 vectorizertransform list1list2。这将解决问题。演示:

>>> list1 = ["My name is xyz", "My name is pqr", "I work in abc"]
>>> list2 = ["My name is xyz", "I work in abc"]
>>> vectorizer = TfidfVectorizer(min_df = 0, max_df=0.5, stop_words = "english", charset_error = "ignore", ngram_range = (1,3))
>>> vec=vectorizer.fit(list1) # train vec using list1
>>> vectorized = vec.transform(list1) # transform list1 using vec
>>> km=KMeans(n_clusters=2, init='k-means++', n_init=10, max_iter=1000, tol=0.0001, precompute_distances=True, verbose=0, random_state=None, cpy_x=True, n_jobs=1)
>>> km.fit(vectorized)
>>> list2Vec=vec.transform(list2) # transform list2 using vec
>>> km.predict(list2Vec)
array([0, 0], dtype=int32)

关于python - Sklearn Pipeline : How to build for kmeans, 聚类文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26903091/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com