如何保存和加载机器学习(One-vs-Rest)模型?

问题描述 投票:0回答:1

我的代码循环遍历每个标签或类别,然后从中创建一个模型。然而,我想要的是创建一个通用模型,它将能够接受来自用户输入的新预测。

我知道下面的代码保存了适合循环中最后一个类别的模型。我该如何解决这个问题,以便保存每个类别的模型,以便在加载这些模型时,我能够预测新文本的标签?

vectorizer = TfidfVectorizer(strip_accents='unicode', 
stop_words=stop_words, 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 = ['question_body'], axis=1)

x_test = vectorizer.transform(test_text)
y_test = test.drop(labels = ['question_body'], axis=1)

# Using pipeline for applying linearSVC and one vs rest classifier
SVC_pipeline = Pipeline([
                ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)),
            ])
for category in categories:
    print('... Processing {}'.format(category))

    # train the SVC model using X_dtm & y
    SVC_pipeline.fit(x_train, train[category])
    # compute the testing accuracy of SVC
    svc_prediction = SVC_pipeline.predict(x_test)
    print("SVC Prediction:")
    print(svc_prediction)
    print('Test accuracy is {}'.format(f1_score(test[category], svc_prediction)))
    print("\n")

#save the model to disk
filename = 'svc_model.sav'
pickle.dump(SVC_pipeline, open(filename, 'wb'))
python scikit-learn pickle
1个回答
1
投票

您的代码中有多个错误。

  1. 您正在训练和测试中安装您的

    TfidfVectorizer

    vectorizer.fit(train_text)
    vectorizer.fit(test_text)
    

    这是错误的。调用

    fit()
    不是增量的。如果调用两次,它不会学习这两个数据。最近对
    fit()
    的调用将会忘记过去调用的所有内容。你永远不会在测试数据上拟合(学习)一些东西。

    你需要做的是:

    vectorizer.fit(train_text)
    
  2. 管道并不按您想象的方式工作:

    # Using pipeline for applying linearSVC and one vs rest classifier
    SVC_pipeline = Pipeline([
                             ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)),
                            ])
    

    看到您正在将

    LinearSVC
    传递到
    OneVsRestClassifier
    内部,因此它将自动使用它,而不需要
    Pipeline
    Pipeline
    不会在这里做任何事情。当您想要按顺序通过多个模型传递数据时,
    Pipeline
    非常有用。像这样的东西:

    pipe = Pipeline([
                     ('pca', pca), 
                     ('logistic', LogisticRegression())
                    ])
    

    上面的

    pipe
    所做的就是将数据传递给
    PCA
    ,后者将对其进行转换。然后新数据被传递到
    LogisticRegression
    等等..

    您的情况下管道的正确用法可以是:

      SVC_pipeline = Pipeline([
                              ('vectorizer', vectorizer)
                              ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)),
                             ])
    

    在此处查看更多示例:

  3. 您需要更多地描述您的

    "categories"
    。显示一些数据示例。您没有在任何地方使用
    y_train
    y_test
    。类别与
    "question_body"
    不同吗?

© www.soinside.com 2019 - 2024. All rights reserved.