我是机器学习的新手,正在努力让分类器使用测试数据集进行预测。
我认为错误尺寸失配是由于将矢量化器安装了测试装置造成的,但是我已经解决了这个问题,但是仍然有问题。
该错误是由于矢量化器被覆盖了,我相信它无法进入该位置,但是我找不到它...
非常感谢我已经为此提供了很长时间:)
import sqlalchemy
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
from sklearn import metrics
from sklearn.metrics import accuracy_score
from sklearn import metrics
import pickle
### Connect to MYSQL database
##
#
dbServerName = "localhost"
dbUser = "root"
dbPassword = "woodycool123"
dbName = "azure_support_tweets"
engine = sqlalchemy.create_engine('mysql+pymysql://root:woodycool123@localhost:3306/azure_support_tweets')
pd.set_option('display.max_colwidth', -1)
df = pd.read_sql_table("preprocessed_tweets", engine)
data = pd.DataFrame(df)
### Training and Test Data Split
##
#
features_train, features_test, labels_train, labels_test = train_test_split(data['text_tweet'], data['main_category'], random_state = 42, test_size=0.34)
### CountVectorizer
##
#
cv = CountVectorizer(ngram_range=(1,2), stop_words='english', min_df=3, max_df=0.50)
features_train_cv = cv.fit_transform(features_train)
# Uncomment to print a matrix count of tokens
# print(features_train_cv.toarray())
print("Feature Count\nCountVectorizer() #", len(cv.get_feature_names()))
### TF-IDF Transformer
##
#
tfidfv = TfidfTransformer(use_idf=True)
features_train_tfidfv = tfidfv.fit_transform(features_train_cv)
print("Feature Set\nTfidfVectorizer() #", features_train_tfidfv.shape)
# Remove to print the top 10 features
# features = tfidfv.get_feature_names()
# feature_order = np.argsort(tfidfv.idf_)[::-1]
# top_n = 10
# top_n_features = [features[i] for i in feature_order[:top_n]]
# print(top_n_features)
### SelectKBest
##
#
selector = SelectKBest(chi2, k=1000).fit_transform(features_train_tfidfv, labels_train)
print("Feature Set\nSelectKBest() and chi2 #", selector.shape)
### Train Model
##
#
clf = MultinomialNB()
clf.fit(selector, labels_train)
### Test Model
##
#
features_test_cv = cv.transform(features_test)
features_test_cv_two = tfidfv.transform(features_test_cv)
pred = clf.predict(features_test_cv)
错误:
Traceback (most recent call last):
File "/Users/bethwalsh/Documents/classifier-twitter/building_the_classifer/feature_generation_selection.py", line 76, in <module>
pred = clf.predict(features_test_cv)
File "/Users/bethwalsh/anaconda3/lib/python3.6/site-packages/sklearn/naive_bayes.py", line 66, in predict
jll = self._joint_log_likelihood(X)
File "/Users/bethwalsh/anaconda3/lib/python3.6/site-packages/sklearn/naive_bayes.py", line 725, in _joint_log_likelihood
return (safe_sparse_dot(X, self.feature_log_prob_.T) +
File "/Users/bethwalsh/anaconda3/lib/python3.6/site-packages/sklearn/utils/extmath.py", line 135, in safe_sparse_dot
ret = a * b
File "/Users/bethwalsh/anaconda3/lib/python3.6/site-packages/scipy/sparse/base.py", line 515, in __mul__
raise ValueError('dimension mismatch')
ValueError: dimension mismatch
答案 0 :(得分:2)
您也需要通过选择器来传递测试集,但是首先您必须先进行拟合
selector = SelectKBest(chi2, k=1000)
selector.fit(features_train_tfidfv, labels_train)
clf = MultinomialNB()
clf.fit(selector.transform(features_train_tfidfv), labels_train)
features_test_cv = selector.transform(tfidfv.transform(cv.transform(features_test)))
pred = clf.predict(features_test_cv)
抛出该错误是因为选择器减小了训练集而不是测试集的大小
答案 1 :(得分:1)
好像您忘记了在测试模型部分中使用降维(也称为SelectKBest
)。我不知道如果要转换测试数据,以这种方式使用SelectKBest
是否正确。但是无论如何,朴素的贝叶斯模型
clf = MultinomialNB()
clf.fit(selector, labels_train)
等待selector
形状的东西,即您的示例中k = 1000。在模型的测试部分,
features_test_cv = cv.transform(features_test)
features_test_cv_two = tfidfv.transform(features_test_cv)
pred = clf.predict(features_test_cv)
您跳过了此转换,因此clf.predict
采用其他形状的矩阵。尝试使用SelectKBest.transform
获得所需的输出:
selector_model = SelectKBest(chi2, k=1000). # create an object, use it later
selector = selector_model.fit_transform(features_train_tfidfv, labels_train)
print("Feature Set\nSelectKBest() and chi2 #", selector.shape)
clf = MultinomialNB()
clf.fit(selector, labels_train)
features_test_cv = cv.transform(features_test)
features_test_cv_two = tfidfv.transform(features_test_cv)
selector_test = selector_model.transform(features_test_cv_two)
pred = clf.predict(selector_test)