我想知道如何保存OnevsRest分类器模型以供以后使用。
我在保存它时遇到问题,因为它也意味着保存矢量化器。我在这篇文章中学到了。
这是我创建的模型:
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(strip_accents='unicode', analyzer='word', ngram_range=(1,3), norm='l2')
vectorizer.fit(train_text)
vectorizer.fit(test_text)
x_train = vectorizer.transform(train_text)
y_train = train.drop(labels = ['id','comment_text'], axis=1)
x_test = vectorizer.transform(test_text)
y_test = test.drop(labels = ['id','comment_text'], axis=1)
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
from sklearn.multiclass import OneVsRestClassifier
%%time
# Using pipeline for applying logistic regression and one vs rest classifier
LogReg_pipeline = Pipeline([
('clf', OneVsRestClassifier(LogisticRegression(solver='sag'), n_jobs=-1)),
])
for category in categories:
printmd('**Processing {} comments...**'.format(category))
# Training logistic regression model on train data
LogReg_pipeline.fit(x_train, train[category])
# calculating test accuracy
prediction = LogReg_pipeline.predict(x_test)
print('Test accuracy is {}'.format(accuracy_score(test[category], prediction)))
print("n")
任何帮助将不胜感激。
真诚地
使用joblib
,您可以保存任何Scikit-learn Pipeline
完整的所有元素,因此还包括拟合的TfidfVectorizer
。
在这里,我使用 Newsgroups20 数据集的前 200 个示例重写了您的示例:
from sklearn.datasets import fetch_20newsgroups
data = fetch_20newsgroups()
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
from sklearn.multiclass import OneVsRestClassifier
vectorizer = TfidfVectorizer(strip_accents='unicode', analyzer='word', ngram_range=(1,3), norm='l2')
x_train = data.data[:100]
y_train = data.target[:100]
x_test = data.data[100:200]
y_test = data.target[100:200]
# Using pipeline for applying logistic regression and one vs rest classifier
LogReg_pipeline = Pipeline([
('vectorizer', vectorizer),
('clf', OneVsRestClassifier(LogisticRegression(solver='sag',
class_weight='balanced'),
n_jobs=-1))
])
# Training logistic regression model on train data
LogReg_pipeline.fit(x_train, y_train)
在上面的代码中,您只需开始定义训练和测试数据,然后实例化TfidfVectorizer
。然后,定义包含矢量化器和 OVR 分类器的管道,并将其拟合到训练数据。它将学习一次预测所有类。
现在,您只需使用 joblib
将整个拟合管道保存为单个预测变量:
from joblib import dump, load
dump(LogReg_pipeline, 'LogReg_pipeline.joblib')
您的整个模型不会以"LogReg_pipeline.joblib"的名称保存到磁盘。您可以通过以下代码片段调用它并直接在原始数据上使用它:
clf = load('LogReg_pipeline.joblib')
clf.predict(x_test)
您将获得对原始文本的预测,因为管道会自动对其进行矢量化。