保存模型以供以后预测(OneVsRest)

时间:2019-01-30 17:57:10

标签: python scikit-learn save multilabel-classification tfidfvectorizer

我想知道如何保存OnevsRest 分类器 模型以备将来使用。

我在保存它方面遇到问题,因为这也意味着要保存矢量化程序。我已经在此post中学习到了。

这是我创建的模型:

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") 

任何帮助将不胜感激。

此致

1 个答案:

答案 0 :(得分:1)

使用joblib,您可以保存所有Scikit学习课程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)

您将获得原始文本的预测,因为管道会自动将其矢量化。