【问题标题】:Scikit learn SVC predict probability doesn't work as expectedScikit 学习 SVC 预测概率无法按预期工作
【发布时间】:2017-08-19 14:07:14
【问题描述】:

我使用 SVM 分类器构建了情绪分析器。我用概率=真训练模型,它可以给我概率。但是当我腌制模型并稍后再次加载时,概率不再起作用。

型号:

from sklearn.svm import SVC, LinearSVC
pipeline_svm = Pipeline([
    ('bow', CountVectorizer()),
    ('tfidf', TfidfTransformer()),
    ('classifier', SVC(probability=True)),])

# pipeline parameters to automatically explore and tune
param_svm = [
  {'classifier__C': [1, 10, 100, 1000], 'classifier__kernel': ['linear']},
  {'classifier__C': [1, 10, 100, 1000], 'classifier__gamma': [0.001, 0.0001], 'classifier__kernel': ['rbf']},
]

grid_svm = GridSearchCV(
    pipeline_svm,
    param_grid=param_svm,
    refit=True,
    n_jobs=-1, 
    scoring='accuracy',
    cv=StratifiedKFold(label_train, n_folds=5),)

svm_detector_reloaded = cPickle.load(open('svm_sentiment_analyzer.pkl', 'rb'))
print(svm_detector_reloaded.predict([""""Today is awesome day"""])[0])

给我:

AttributeError:predict_proba 在probability=False 时不可用

【问题讨论】:

  • 能否把原来保存对象的代码显示到''svm_sentiment_analyzer.pkl''?
  • 在收到AttributeError 时,您是否尝试拨打predict_proba 而不是predict?否则这有点令人费解

标签: python scikit-learn svc


【解决方案1】:

使用:SVM(probability=True)

grid_svm = GridSearchCV(
    probability=True
    pipeline_svm,
    param_grid=param_svm,
    refit=True,
    n_jobs=-1, 
    scoring='accuracy',
    cv=StratifiedKFold(label_train, n_folds=5),)

【讨论】:

    【解决方案2】:

    添加(概率= true),同时将分类器初始化为上面建议的人,解决了我的错误:

    clf = SVC(kernel='rbf', C=1e9, gamma=1e-07, probability=True).fit(xtrain,ytrain)
    

    【讨论】:

      【解决方案3】:

      您可以使用 CallibratedClassifierCV 进行概率分数输出。

      from sklearn.calibration import CalibratedClassifierCV
      
      model_svc = LinearSVC()
      model = CalibratedClassifierCV(model_svc) 
      model.fit(X_train, y_train)
      

      使用pickle保存模型。

      import pickle
      filename = 'linearSVC.sav'
      pickle.dump(model, open(filename, 'wb'))
      

      使用 pickle.load 加载模型。

      model = pickle.load(open(filename, 'rb'))

      现在开始预测。

      pred_class = model.predict(pred)
      probability = model.predict_proba(pred)
      

      【讨论】:

        【解决方案4】:

        如果有帮助,请使用以下方法腌制模型:

        import pickle
        pickle.dump(grid_svm, open('svm_sentiment_analyzer.pkl', 'wb'))
        

        并加载模型并使用

        进行预测
        svm_detector_reloaded = pickle.load(open('svm_sentiment_analyzer.pkl', 'rb'))
        print(svm_detector_reloaded.predict_proba(["Today is an awesome day"])[0])
        

        在处理您的代码以重新运行它并在 pandas sents DataFrame 上使用

        训练模型之后,给我返回了两个概率
        grid_svm.fit(sents.Sentence.values, sents.Positive.values)
        

        关于模型序列化的最佳实践(例如使用joblib)可以在https://scikit-learn.org/stable/modules/model_persistence.html找到

        【讨论】:

          【解决方案5】:

          使用 predprobs 函数计算 auc(y_true, y_score) 中要求的分数或概率/分数,问题是因为 y_score。 您可以将其转换为如下代码行所示

          # Classifier - Algorithm - SVM
          # fit the training dataset on the classifier
          SVM = svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto',probability=True)
          SVM.fit(Train_X_Tfidf,Train_Y)
          # predict the labels on validation dataset
          predictions_SVM = SVM.predict(Test_X_Tfidf)
          # Use accuracy_score function to get the accuracy
          **print("SVM Accuracy Score -> ",accuracy_score(predictions_SVM, Test_Y))**
          
          probs = SVM.**predict_proba**(Test_X_Tfidf)
          preds = probs[:,1]
          fpr, tpr, threshold = **roc_curve(Test_Y, preds)**
          **print("SVM Area under curve -> ",auc(fpr, tpr))**
          

          看看accuracy_score和auc()的区别,你需要预测的分数。

          【讨论】:

            猜你喜欢
            • 2017-09-11
            • 2016-02-14
            • 2013-12-05
            • 2014-12-06
            • 2020-10-29
            • 2020-09-07
            • 2020-10-08
            • 2019-02-08
            • 2016-05-23
            相关资源
            最近更新 更多