Sklearn Pipeline: How to build for kmeans, clustering text?

拈花ヽ惹草 提交于 2019-12-01 07:54:42

What you need to do is to train a vectorizer using list1, then with the same vectorizer, transform list1 and list2. This will solve the issue. Demo:

>>> 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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!