gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:05 26 4
gpt4 key购买 nike

我想知道如何保存 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")

任何帮助将不胜感激。

真诚的,

最佳答案

使用 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)

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

关于python - 保存模型以供以后预测(OneVsRest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54446739/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com