How to calculate prediction probability in python

2019-08-27 17:34发布

问题:

I am trying to calculate each prediction probability in SVM model by using LinearSVC and OneVsRestClassifier but getting the error

AttributeError: 'LinearSVC' object has no attribute 'predict_proba'

tried code:

model = Pipeline([('vectorizer', CountVectorizer(ngram_range=(1,2))),
    ('tfidf', TfidfTransformer(use_idf=True)),
    ('clf', OneVsRestClassifier(LinearSVC(class_weight="balanced")))])

model.fit(X_train, y_train)
y_train.shape
pred = model.predict(X_test)

probas = model.predict_proba(X_test)

Also tried:

from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.svm import SVC

LinearSVC_classifier = SklearnClassifier(SVC(kernel='linear',probability=True))
prob_1 = LinearSVC_classifier.predict_proba(X_test)

but still getting error AttributeError: 'SklearnClassifier' object has no attribute 'predict_proba'

Please suggestion for the same.

回答1:

With your Linear SVM:

from sklearn.calibration import CalibratedClassifierCV
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import FeatureUnion, make_pipeline
from sklearn.svm import LinearSVC

word_vectorizer = TfidfVectorizer(ngram_range=(1, 2))
features = FeatureUnion([('words', word_vectorizer), ])
calibrated_svc = CalibratedClassifierCV(LinearSVC(), method='sigmoid', cv=3)
pipeline = make_pipeline(features, calibrated_svc)
pipeline.fit(train_x, train_y)
predicted = pipeline.predict_proba(test_x)

or with Logistic Regression:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import FeatureUnion, make_pipeline
from sklearn.linear_model import LogisticRegression

word_vectorizer = TfidfVectorizer(ngram_range=(1, 2))
features = FeatureUnion([('words', word_vectorizer), ])
pipeline = make_pipeline(features, LogisticRegression())
pipeline.fit(train_x, train_y)
predicted = pipeline.predict_proba(test_x)


回答2:

Simply because 'SKlearnClassifier' object has no attribute 'predict_proba'

You can predict probability this way,

 classifier.classify_many(test)

 for pdist in classifier.prob_classify_many(test):
...     print('%.4f %.4f' % (pdist.prob('x'), pdist.prob('y')))

code from here