這是一個用 tf-idf 制作的用于特征提取的情感分析模型我想知道如何保存這個模型并重用它。我嘗試以這種方式保存它,但是當我加載它時,對測驗文本和 fit_transform 進行相同的預處理,它給出了一個錯誤,即模型期望 X 個特征但得到 Y
這就是我保存它的方式
filename = "model.joblib"
joblib.dump(model, filename)
這是我的 tf-idf 模型的代碼
import pandas as pd
import re
import nltk
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import BernoulliNB
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
nltk.download('stopwords')
from nltk.corpus import stopwords
processed_text = ['List of pre-processed text']
y = ['List of labels']
tfidfconverter = TfidfVectorizer(max_features=10000, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = tfidfconverter.fit_transform(processed_text).toarray()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
text_classifier = BernoulliNB()
text_classifier.fit(X_train, y_train)
predictions = text_classifier.predict(X_test)
print(confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))
print(accuracy_score(y_test, predictions))
編輯:只是為了準確地將每一行放在哪里之后:
tfidfconverter = TfidfVectorizer(max_features=10000, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
然后
tfidf_obj = tfidfconverter.fit(processed_text)//this is what will be used again
joblib.dump(tfidf_obj, 'tf-idf.joblib')
然后你做剩下的步驟,你將在訓練后保存分類器,所以在之后:
text_classifier.fit(X_train, y_train)
當你想預測任何文本時,現在放 joblib.dump(model, "classifier.joblib")
tf_idf_converter = joblib.load("tf-idf.joblib")
classifier = joblib.load("classifier.joblib")
現在你有要預測的句子串列
sent = []
classifier.predict(tf_idf_converter.transform(sent))
現在列印每個句子的情緒串列
uj5u.com熱心網友回復:
您可以首先tfidf使用以下方法適應您的訓練集:
tfidfconverter = TfidfVectorizer(max_features=10000, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
tfidf_obj = tfidfconverter.fit(processed_text)
然后找到一種方法來存盤tfidf_obj例如使用pickle或joblib例如:
joblib.dump(tfidf_obj, filename)
然后加載保存tfidf_obj并transform僅應用于您的測驗集
loaded_tfidf = joblib.load(filename)
test_new = loaded_tfidf.transform(X_test)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/481169.html
標籤:Python 机器学习 scikit-学习 tf-idf tfidfvectorizer
