11

After seeing the precision_recall_curve, if I want to set threshold = 0.4, how to implement 0.4 into my random forest model (binary classification), for any probability <0.4, label it as 0, for any >=0.4, label it as 1.

from sklearn.ensemble import RandomForestClassifier
  random_forest = RandomForestClassifier(n_estimators=100, oob_score=True, random_state=12)
  random_forest.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
  predicted = random_forest.predict(X_test)
accuracy = accuracy_score(y_test, predicted)

Documentation Precision recall

3 Answers 3

30

Assuming you are doing binary classification, it's quite easy:

threshold = 0.4

predicted_proba = random_forest.predict_proba(X_test)
predicted = (predicted_proba [:,1] >= threshold).astype('int')

accuracy = accuracy_score(y_test, predicted)
2
  • Hi Stev, my last part give me a error "ValueError: Can't handle mix of binary and multilabel-indicator." accuracy = accuracy_score(y_test, predicted) print(round(accuracy,4,)*100, "%") Do you know how to fix it?
    – BigData
    Apr 12, 2018 at 18:15
  • @BigData,Ooops my bad, I didn't run the rest of your code. In that case, you only need to take the second column. That column is 1 if class 1 and 0 if not, which my implication is class 0. Check my edit.
    – Stev
    Apr 13, 2018 at 8:20
1
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, y_train)

threshold = 0.4

predicted = random_forest.predict_proba(X_test)
predicted[:,0] = (predicted[:,0] < threshold).astype('int')
predicted[:,1] = (predicted[:,1] >= threshold).astype('int')


accuracy = accuracy_score(y_test, predicted)
print(round(accuracy,4,)*100, "%")

this comes with an error refers to the last accuracy part" ValueError: Can't handle mix of binary and multilabel-indicator"

0

sklearn.metrics.accuracy_score takes 1 d array but your predicted array is 2-d. This comes with an error.
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html

1
  • Instead of using predicted, pick the predicted class you want to view the accuracy_score for. Use one of predicted[:,0] or predicted[:,1], instead of predicted.
    – ddragosd
    May 23, 2022 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.