我有一个训练数据集,它在Pandas Dataframe中。我已经做了TfIdf矢量化来获得特征并运行Kmeans。以下是相关代码:
vectorizer = TfidfVectorizer(max_df=0.8, max_features=max_feat, norm="l1", analyzer="word",
min_df=0.1,ngram_range=(1,2)
)
X = vectorizer.fit_transform(df['reviews'])
km = KMeans(n_clusters=number, init='k-means++', max_iter=100, n_init=3,
verbose=1, n_jobs = -2)
km.fit(X)
我可以通过这个得到质心:
order_centroids = km.cluster_centers_.argsort()[:, ::-1]
现在,当我试图运行测试数据时,我得到错误。这是我为测试数据运行的代码。我基本上是从Panda的测试数据框架中提取每一行,并将其拟合到上面相同的矢量器中。我做错了吗?
sample = df.tail(int(totalTestRows * lineLimit))
for row in sample.itertuples():
test_data = np.array([row[6]])
testVectorizerArray = vectorizer.transform(test_data).toarray()
rowX = vectorizer.fit(testVectorizerArray)
print(km.predict(rowX))
在rowX = vectorizer.fit(testVectorizerArray)
行,我得到以下错误:
AttributeError: 'numpy.ndarray' object has no attribute 'lower'
我通过StackOverflow搜索,似乎我需要将test_data
数组格式化为一维数组。我已经检查过了,test_data的形式是(n,)
。然而,我仍然得到错误。我的方法有什么问题吗?
您不应该在测试阶段修改矢量化器,如果您将矢量化器和分类器与管道结合起来,您的代码将更清晰:
from sklearn.pipeline import make_pipeline
vectorizer = TfidfVectorizer(max_df=0.8, max_features=max_feat, norm="l1", analyzer="word",
min_df=0.1,ngram_range=(1,2)
)
km = KMeans(n_clusters=number, init='k-means++', max_iter=100, n_init=3,
verbose=1, n_jobs = -2)
clf = make_pipeline(vectorizer, km)
clf.fit(X)
sample = df.tail(int(totalTestRows * lineLimit))
for row in sample.itertuples():
test_data = np.array([row[6]])
print(clf.predict(test_data))