栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

解决报错:sklearn.exceptions.NotFittedError: Vocabulary not fitted or provided

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决报错:sklearn.exceptions.NotFittedError: Vocabulary not fitted or provided

在使用sklearn进行自然语言处理的时候,经常遇到一些报错,类似“X has 69 features, but MLPClassifier is expecting 284817 features as input.”或者“Vocabulary not fitted or provided”。在网页上检索了半天没有找到完美的教程,所以自己对照别人的代码拼拼凑凑解决了,以下是解决方法。

1.使用测试集时遇到问题

在分割训练集和测试集后,进行了模型拟合,在数据集上测试正常,但是到测试集上测试的时候会遇到“X has 2 features, but MLPClassifier is expecting 2817 features as input.”的问题。
导致这个问题的原因主要是训练集和测试集使用的CountVectorizer()不一样,只要更改代码使前后保持一致就能完美解决了

更改前的代码:

vect = CountVectorizer(token_pattern=u'(?u)\b[^\d\W]\w+\b',stop_words=frozenset(stopwords))
term_matrix_train = vect.fit_transform(X_train.cutted_comment)
term_matrix_test = vect.fit_transform(X_test.cutted_comment)
model = mlp.fit(term_matrix_train, y_train)
print("训练数据上的准确率为:%f" % (model.score(term_matrix_train, y_train)))
print("测试数据上的准确率为:%f" % (model.score(term_matrix_test, y_test)))

更改后的代码:

vect = CountVectorizer(token_pattern=u'(?u)\b[^\d\W]\w+\b',stop_words=frozenset(stopwords))
term_matrix_train = vect.fit_transform(X_train.cutted_comment)
term_matrix_test = vect.transform(X_test.cutted_comment)
model = mlp.fit(term_matrix_train, y_train)
print("训练数据上的准确率为:%f" % (model.score(term_matrix_train, y_train)))
print("测试数据上的准确率为:%f" % (model.score(term_matrix_test, y_test)))

只要把对测试集的训练从vect.fit_transform()改成vect.transform()就可以解决了。

2.使用模型预测新数据时遇到问题

测试集的问题解决了,但是调用训练好的模型来处理新数据的时候还是会遇到问题。起先我以为是在自定义的predict()函数里使用的是vect.fit_transform()而不是vect.transform()导致的问题。
但是更改代码后“X has 2 features, but MLPClassifier is expecting 2817 features as input.”的错误消失了,反而出现了“Vocabulary not fitted or provided”的错误。
经过资料的查阅,发现是保存模型的时候,没有把CountVectorizer()类也保存下来,导致第二次调用和训练时使用的CountVectorizer()不同。

更改后的模型保存和调用代码:

joblib.dump(model,  "model path")
joblib.dump(vect,"vect path")

def model_predict(text,model,vects):
    text1 = [" ".join(jieba.cut(text))]
    text2 = vects.transform(text1)
    predict_type = model.predict(text2)[0]
    print(predict_type)
    return predict_type

def Use_model():
    vec=joblib.load("vect path")
    model_clone = joblib.load("model path")
    text = input("待测试文本")
    model_predict(text,model_clone,vec)
    
Use_model()

以上就是这个问题的解决方法,希望能帮到大家!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/822472.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号