scikit .predict () 기본 임계 값
불균형 클래스 (5 % 1)의 분류 문제를 해결 중입니다. 확률이 아니라 클래스를 예측하고 싶습니다.
이진 분류 문제에서 scikit의이다 classifier.predict()사용 0.5기본적를? 그렇지 않은 경우 기본 방법은 무엇입니까? 그렇다면 어떻게 변경합니까?
scikit에서 일부 분류 자에는 class_weight='auto'옵션이 있지만 모두가있는 것은 아닙니다. 로 class_weight='auto', 것 .predict()임계 값과 실제 인구 비율을 사용합니까?
MultinomialNB지원하지 않는 분류기에서 이것을 수행하는 방법은 무엇입니까 class_weight? predict_proba()수업을 직접 사용 하고 계산하는 것 외에는 .
scikit
classifier.predict()은 기본적으로 0.5를 사용하고 있습니까?
확률 적 분류기에서는 그렇습니다. 다른 사람들이 설명했듯이 수학적 관점에서 볼 때 유일하게 합리적인 임계 값입니다.
지원하지 않는 MultinomialNB와 같은 분류기에서 이것을 수행하는 방법은 무엇입니까
class_weight?
클래스 y 당 class_prior사전 확률 P ( y ) 인을 설정할 수 있습니다 . 이는 의사 결정 경계를 효과적으로 이동시킵니다. 예
# minimal dataset
>>> X = [[1, 0], [1, 0], [0, 1]]
>>> y = [0, 0, 1]
# use empirical prior, learned from y
>>> MultinomialNB().fit(X,y).predict([1,1])
array([0])
# use custom prior to make 1 more likely
>>> MultinomialNB(class_prior=[.1, .9]).fit(X,y).predict([1,1])
array([1])
scikit learn의 임계 값은 이진 분류의 경우 0.5이며 다중 클래스 분류에 대한 확률이 가장 큰 클래스입니다. 많은 문제에서 임계 값을 조정하면 훨씬 더 나은 결과를 얻을 수 있습니다. 그러나 이것은 홀드 아웃 테스트 데이터가 아니라 훈련 데이터에 대한 교차 검증을 통해주의해서 수행해야합니다. 테스트 데이터에서 임계 값을 조정하면 테스트 데이터를 과적 합하는 것입니다.
임계 값을 조정하는 대부분의 방법은 ROC (수신자 작동 특성) 및 Youden의 J 통계를 기반으로 하지만 유전 알고리즘을 사용한 검색과 같은 다른 방법으로도 수행 할 수 있습니다.
다음은 의학에서 이것을 설명하는 피어 리뷰 저널 기사입니다.
http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2515362/
내가 아는 한 Python에서 수행하는 패키지는 없지만 Python에서 무차별 대입 검색으로 찾는 것은 비교적 간단하지만 비효율적입니다.
이것은 그것을 수행하는 일부 R 코드입니다.
## load data
DD73OP <- read.table("/my_probabilites.txt", header=T, quote="\"")
library("pROC")
# No smoothing
roc_OP <- roc(DD73OP$tc, DD73OP$prob)
auc_OP <- auc(roc_OP)
auc_OP
Area under the curve: 0.8909
plot(roc_OP)
# Best threshold
# Method: Youden
#Youden's J statistic (Youden, 1950) is employed. The optimal cut-off is the threshold that maximizes the distance to the identity (diagonal) line. Can be shortened to "y".
#The optimality criterion is:
#max(sensitivities + specificities)
coords(roc_OP, "best", ret=c("threshold", "specificity", "sensitivity"), best.method="youden")
#threshold specificity sensitivity
#0.7276835 0.9092466 0.7559022
임계 값은 다음을 사용하여 설정할 수 있습니다. clf.predict_proba()
예를 들면 :
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier(random_state = 2)
clf.fit(X_train,y_train)
# y_pred = clf.predict(X_test) # default threshold is 0.5
y_pred = (clf.predict_proba(X_test)[:,1] >= 0.3).astype(bool) # set threshold as 0.3
여기서 개념이 혼란스러워 보입니다. 임계 값은 "일반 분류 자"에 대한 개념이 아닙니다. 가장 기본적인 접근 방식은 일부 조정 가능한 임계 값을 기반으로하지만 대부분의 기존 방법은 임계 값으로 볼 수 없거나 적어도 표시해서는 안되는 복잡한 분류 규칙을 만듭니다.
따라서 먼저 scikit의 분류기 기본 임계 값에 대한 질문에 답할 수 없습니다.
Second - class weighting is not about threshold, is about classifier ability to deal with imbalanced classes, and it is something dependent on a particular classifier. For example - in SVM case it is the way of weighting the slack variables in the optimization problem, or if you prefer - the upper bounds for the lagrange multipliers values connected with particular classes. Setting this to 'auto' means using some default heuristic, but once again - it cannot be simply translated into some thresholding.
Naive Bayes on the other hand directly estimates the classes probability from the training set. It is called "class prior" and you can set it in the constructor with "class_prior" variable.
From the documentation:
Prior probabilities of the classes. If specified the priors are not adjusted according to the data.
0.5 is not related to the population proportion in any way. Its a probability output. There is no "threshold", if one class has a probability of 0.51, then it appears to be the most likely class. 0.5 if always the what should be used*, and no package uses a different "threshold". If your probability scores are a*ccurate and truly representative*, then you must always chose the most probable class. To do otherwise can only reduce your accuracy. Since we are using various algorithms that make assumptions, we don't know that the probability is true - but you would be going against the assumptions made by your model.
You are confused on what class_weight does. Changing the class weight increase the weights for data points in the less represented classes (/ decreasing for the over represented class) so that the "weight" of each class is equal - as if they had the same number of positive and negative examples. This is a common trick for trying to avoid a classifier that always votes for the most common class. Because this way, both classes are equally common from the learning algorithm's view.
- NOTE: if you have a fear of false positives / false negatives, then you may choose to only accept a class if its probability meets a certain minimum value. But that doesn't change how learning is done, and that dose not change the meaning behind a probability.
In case someone visits this thread hoping for ready-to-use function (python 2.7). In this example cutoff is designed to reflect ratio of events to non-events in original dataset df, while y_prob could be the result of .predict_proba method (assuming stratified train/test split).
def predict_with_cutoff(colname, y_prob, df):
n_events = df[colname].values
event_rate = sum(n_events) / float(df.shape[0]) * 100
threshold = np.percentile(y_prob[:, 1], 100 - event_rate)
print "Cutoff/threshold at: " + str(threshold)
y_pred = [1 if x >= threshold else 0 for x in y_prob[:, 1]]
return y_pred
Feel free to criticize/modify. Hope it helps in rare cases when class balancing is out of the question and the dataset itself is highly imbalanced.
참고URL : https://stackoverflow.com/questions/19984957/scikit-predict-default-threshold
'Program Club' 카테고리의 다른 글
| PKIX 경로 빌드를 무시하는 방법 실패 : sun.security.provider.certpath.SunCertPathBuilderException? (0) | 2020.12.04 |
|---|---|
| / app / 폴더를 공개하지 않고 웹 호스트 하위 폴더에 Laravel 4를 설치하는 방법은 무엇입니까? (0) | 2020.12.04 |
| VS2013 Intellisense가 지속적으로 작동을 멈춤 (0) | 2020.12.04 |
| 'return await promise'와 'return promise'의 차이점 (0) | 2020.12.04 |
| URL에서 뒤로 버튼 / 해시 변경 감지 (0) | 2020.12.04 |