如何解决尝试使用 skmultilearn.BinaryRelevance 预测新文本时出现 Matmul 错误
import skmultilearn
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
from scipy.sparse import csr_matrix
from pandas.core.common import flatten
from sklearn.naive_bayes import MultinomialNB
from skmultilearn.problem_transform import BinaryRelevance
TRAIN_DATA = [
['Como efetuar uma conexão com MysqL usando PHP ?',['desenvolvimento','banco']],['Quais são os melhores clientes de VPN hoje em dia?',['redes']],['Qual é o equivalente ao tipo booleano no Oracle?',['banco']],['Como remover entidade indesejada da sessão do Hibernate?',['desenvolvimento']],['Como implementar o pool de conexão TCP em java?','redes']],['Como posso me conectar ao banco de dados Postgresql remotamente de outra rede?',['banco',['Qual a função python para remover acentos em uma string?',['Como remover índices no sql Server?',['Como configurar o firewall com DMZ?',['redes']]
]
data_frame = pd.DataFrame(TRAIN_DATA,columns=['text','labels'])
corpus = data_frame['text']
unique_labels = set(flatten(data_frame['labels']))
for u in unique_labels:
data_frame[u] = 0
data_frame[u] = pd.to_numeric(data_frame[u])
for i,row in data_frame.iterrows():
for u in unique_labels:
if u in row.labels:
data_frame.at[i,u] = 1
tfidf = TfidfVectorizer()
Xfeatures = tfidf.fit_transform(corpus).toarray()
y = data_frame[unique_labels]
binary_rel_clf = BinaryRelevance(MultinomialNB())
binary_rel_clf.fit(Xfeatures,y)
predict_text = ['sql Server no PHP?']
X_predict = tfidf.fit_transform(predict_text)
br_prediction = binary_rel_clf.predict(X_predict)
print(br_prediction)
但是,我收到此错误:
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0,with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 56 is different from 4)
我需要更改什么“维度”才能正确运行 predict()?
解决方法
您正在使用 TfidfVectorizer
来转换您的文本特征。您应该在训练数据上只拟合一次转换器,在您的情况下是 corpus
。但是,在准备要测试/预测的数据时,您应该使用 transform
方法,而不要 fit_transform
再次使用,因为这会重新安装转换器。
更改以下内容以使其工作:
X_predict = tfidf.transform(predict_text)