如何保存和加载机器学习(一对一)模型 (PYTHON)

How to Save and Load Machine Learning (One-vs-Rest) Models (PYTHON)

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

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

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

您的代码中有多个错误。

  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)),
                            ])
    

    看到您在 OneVsRestClassifier 中传递了 LinearSVC,因此它会自动使用它而不需要 PipelinePipeline 不会在这里做任何事情。 Pipeline 当您想要按顺序通过多个模型传递数据时很有用。像这样:

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

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

    在您的案例中正确使用管道可以是:

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

    在此处查看更多示例:

  3. 您需要详细描述您的 "categories"。显示一些数据示例。您没有在任何地方使用 y_trainy_test。类别与"question_body"不同吗?