我正在尝试通过使用LinearSVC
和OneVsRestClassifier
计算SVM模型中的每个预测概率,但是会出现错误
AttributeError: 'LinearSVC' object has no attribute 'predict_proba'
尝试的代码:
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)
也尝试过:
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)
但仍然出现错误AttributeError: 'SklearnClassifier' object has no attribute 'predict_proba'
请提出相同的建议。
答案 0 :(得分:0)
仅仅因为“ SKlearnClassifier”对象没有属性“ predict_proba”
您可以通过这种方式预测概率,
classifier.classify_many(test)
for pdist in classifier.prob_classify_many(test):
... print('%.4f %.4f' % (pdist.prob('x'), pdist.prob('y')))
来自here的代码
答案 1 :(得分:0)
使用线性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)
或具有Logistic回归:
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)