【问题标题】:How to Save and Load Machine Learning (One-vs-Rest) Models (PYTHON)如何保存和加载机器学习(One-vs-Rest)模型 (PYTHON)
【发布时间】:2018-12-27 07:12:35
【问题描述】:

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

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

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. 您正在训练和测试您的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,所以它会自动使用它而不需要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" 不同?

    【讨论】:

    • @CodeGeek 你的问题解决了吗?我已在第 3 点中要求提供更多信息。
    • 是的,我决定保存在每个类别中创建的模型:)
    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2013-02-18
    • 2020-07-17
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多