The Wayback Machine - https://web.archive.org/web/20240709151206/https://www.geeksforgeeks.org/decision-threshold-in-machine-learning/
Open In App

Decision Threshold In Machine Learning

Last Updated : 17 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

What is Decision Threshold ?
sklearn does not let us set the decision threshold directly, but it gives us the access to decision scores ( Decision function o/p ) that is used to make the prediction. We can select the best score from decision function output and set it as Decision Threshold value and consider all those Decision score values which are less than this Decision Threshold as a negative class ( 0 ) and all those decision score values that are greater than this Decision Threshold value as a positive class ( 1 ).

Using Precision-Recall curve for various Decision Threshold values, we can select the best value for Decision Threshold such that it gives High Precision ( Without affection Recall much ) or High Recall ( Without affecting Precision much ) based on whether our project is precision-oriented or recall-oriented respectively.

The main purpose of doing this is to get a high precision ML model, or high recall ML model, based on whether our ML project is precision-oriented or recall-oriented respectively.

Code: Python code to build a high Precision ML model




# Import required modules.
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report, recall_score, precision_score, accuracy_score
  
# Get the data.
data_set = datasets.load_breast_cancer()
  
# Get the data into an array form.
x = data_set.data        # Input feature x.
y = data_set.target      # Input target variable y.
  
# Get the names of the features.
feature_list = data_set.feature_names
  
# Convert the data into pandas data frame.
data_frame = pd.DataFrame(x, columns = feature_list)
  
# To insert an output column in data_frame.
data_frame.insert(30, 'Outcome', y)       # Run this line only once for every new training.
  
# Data Frame.
data_frame.head(7)


Output:

Code: Train the model




# Train Test Split.
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 42)
  
# Create Classifier Object.
clf = SVC()
clf.fit(x_train, y_train)
  
# Use decision_function method.
decision_function = clf.decision_function(x_test)


Actual Scores obtained:




# Actual obtained results without any manual setting of Decision Threshold.
predict_actual = clf.predict(x_test)       # Predict using classifier.
accuracy_actual = clf.score(x_test, y_test)
classification_report_actual = classification_report(y_test, predict_actual)
print(predict_actual, accuracy_actual, classification_report_actual, sep ='\n')


Output:

In the above classification report, we can see that our model precision value for (1) is 0.92 and recall value for (1) is 1.00. Since our goal in this article is to build a High-Precision ML model in predicting (1) without affecting Recall much, we need to manually select the best value of Decision Threshold value form the below Precision-Recall curve, so that we could increase the precision of this model.

Code:




# Plot Precision-Recall curve using sklearn.
from sklearn.metrics import precision_recall_curve
precision, recall, threshold = precision_recall_curve(y_test, decision_function)
  
# Plot the output.
plt.plot(threshold, precision[:-1], c ='r', label ='PRECISION')
plt.plot(threshold, recall[:-1], c ='b', label ='RECALL')
plt.grid()
plt.legend()
plt.title('Precision-Recall Curve')


Output:


Here in the above plot, we can see that if we want high precision value, then we need to increase the value of decision threshold     ( x-axis ), but which would decrease the value of recall ( which is not favourable). so we need to choose that value of Decision Threshold which would increase Precision but not much decrease in Recall. One such value form the above plot is around 0.6 Decision Threshold.

Code:




# Implementing main logic.
  
# Based on analysis of the Precision-Recall curve.
# Let Decision Threshold value be around 0.6... to get high Precision without affecting recall much.
# Desired results.
  
# Decision Function output for x_test.
df = clf.decision_function(x_test)
  
# Set the value of decision threshold.
decision_teshold = 0.5914643767268305
  
# Desired prediction to increase precision value.
desired_predict =[]
  
# Iterate through each value of decision function output
# and if  decision score is > than Decision threshold then,
# append (1) to the empty list ( desired_prediction) else
# append (0).
for i in df:
    if i<decision_teshold:
        desired_predict.append(0)
    else:
        desired_predict.append(1)


Code: Comparison between old and new Precision Values.




# Comparison
  
# Old Precision Value
print("old precision value:", precision_score(y_test, predict_actual))
# New precision Value  
print("new precision value:", precision_score(y_test, desired_predict))


Output:

old precision value: 0.922077922077922
new precision value: 0.9714285714285714

OBSERVATIONS:

  • The value of Precision has increased from 0.92 to 0.97.
  • The Value of Recall has decreased due to Precision-Recall Trade off.

NOTE:
The above code is not data preprocessed( Data Cleaned or Feature Engineered ), which would makes this article prolonged. This is just an idea how to make use of Decision Threshold in practice.



Similar Reads

Pros and Cons of Decision Tree Regression in Machine Learning
Decision tree regression is a widely used algorithm in machine learning for predictive modeling tasks. It is a powerful tool that can handle both classification and regression problems, making it versatile for various applications. However, like any other algorithm, decision tree regression has its strengths and weaknesses. In this article, we'll e
5 min read
KNN vs Decision Tree in Machine Learning
There are numerous machine learning algorithms available, each with its strengths and weaknesses depending on the scenario. Factors such as the size of the training data, the need for accuracy or interpretability, training time, linearity assumptions, the number of features, and whether the problem is supervised or unsupervised all influence the ch
5 min read
Decision Tree in Machine Learning
A decision tree in machine learning is a versatile, interpretable algorithm used for predictive modelling. It structures decisions based on input data, making it suitable for both classification and regression tasks. This article delves into the components, terminologies, construction, and advantages of decision trees, exploring their applications
12 min read
How to Extract the Decision Rules from scikit-learn Decision-tree?
You might have already learned how to build a Decision-Tree Classifier, but might be wondering how the scikit-learn actually does that. So, in this article, we will cover this in a step-by-step manner. You can run the code in sequence, for better understanding. Decision-Tree uses tree-splitting criteria for splitting the nodes into sub-nodes until
4 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Machine Learning Model with Teachable Machine
Teachable Machine is a web-based tool developed by Google that allows users to train their own machine learning models without any coding experience. It uses a web camera to gather images or videos, and then uses those images to train a machine learning model. The user can then use the model to classify new images or videos. The process of creating
7 min read
Artificial intelligence vs Machine Learning vs Deep Learning
Nowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are related to each other but not the same. Let's see
4 min read
Difference Between Artificial Intelligence vs Machine Learning vs Deep Learning
Artificial Intelligence is basically the mechanism to incorporate human intelligence into machines through a set of rules(algorithm). AI is a combination of two words: "Artificial" meaning something made by humans or non-natural things and "Intelligence" meaning the ability to understand or think accordingly. Another definition could be that "AI is
14 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works &amp; what is happening under
6 min read
Practice Tags :