The Wayback Machine - https://web.archive.org/web/20241128050303/https://www.geeksforgeeks.org/python-decision-tree-regression-using-sklearn/
Open In App

Python | Decision Tree Regression using sklearn

Last Updated : 11 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Decision Tree is a decision-making tool that uses a flowchart-like tree structure or is a model of decisions and all of their possible results, including outcomes, input costs, and utility.
Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables.

The branches/edges represent the result of the node and the nodes have either: 

  1. Conditions [Decision Nodes]
  2. Result [End Nodes]

The branches/edges represent the truth/falsity of the statement and take makes a decision based on that in the example below which shows a decision tree that evaluates the smallest of three numbers:  


Decision Tree Regression: 
Decision tree regression observes features of an object and trains a model in the structure of a tree to predict data in the future to produce meaningful continuous output. Continuous output means that the output/result is not discrete, i.e., it is not represented just by a discrete, known set of numbers or values.

Discrete output example: A weather prediction model that predicts whether or not there’ll be rain on a particular day. 
Continuous output example: A profit prediction model that states the probable profit that can be generated from the sale of a product.
Here, continuous values are predicted with the help of a decision tree regression model.

Let’s see the Step-by-Step implementation – 

  • Step 1: Import the required libraries. 

Python3




# import numpy package for arrays and stuff
import numpy as np 
  
# import matplotlib.pyplot for plotting our result
import matplotlib.pyplot as plt
  
# import pandas for importing csv files 
import pandas as pd 


  • Step 2: Initialize and print the Dataset.

Python3




# import dataset
# dataset = pd.read_csv('Data.csv') 
# alternatively open up .csv file to read data
  
dataset = np.array(
[['Asset Flip', 100, 1000],
['Text Based', 500, 3000],
['Visual Novel', 1500, 5000],
['2D Pixel Art', 3500, 8000],
['2D Vector Art', 5000, 6500],
['Strategy', 6000, 7000],
['First Person Shooter', 8000, 15000],
['Simulator', 9500, 20000],
['Racing', 12000, 21000],
['RPG', 14000, 25000],
['Sandbox', 15500, 27000],
['Open-World', 16500, 30000],
['MMOFPS', 25000, 52000],
['MMORPG', 30000, 80000]
])
  
# print the dataset
print(dataset) 


Output:

[['Asset Flip' '100' '1000']
 ['Text Based' '500' '3000']
 ['Visual Novel' '1500' '5000']
 ['2D Pixel Art' '3500' '8000']
 ['2D Vector Art' '5000' '6500']
 ['Strategy' '6000' '7000']
 ['First Person Shooter' '8000' '15000']
 ['Simulator' '9500' '20000']
 ['Racing' '12000' '21000']
 ['RPG' '14000' '25000']
 ['Sandbox' '15500' '27000']
 ['Open-World' '16500' '30000']
 ['MMOFPS' '25000' '52000']
 ['MMORPG' '30000' '80000']]
  • Step 3: Select all the rows and column 1 from the dataset to “X”.

Python3




# select all rows by : and column 1
# by 1:2 representing features
X = dataset[:, 1:2].astype(int) 
  
# print X
print(X)


Output:

[[  100]
 [  500]
 [ 1500]
 [ 3500]
 [ 5000]
 [ 6000]
 [ 8000]
 [ 9500]
 [12000]
 [14000]
 [15500]
 [16500]
 [25000]
 [30000]]
  • Step 4: Select all of the rows and column 2 from the dataset to “y”.

Python3




# select all rows by : and column 2
# by 2 to Y representing labels
y = dataset[:, 2].astype(int) 
  
# print y
print(y)


Output:

[ 1000  3000  5000  8000  6500  7000 15000 20000 21000 25000 27000 30000 52000 80000]
  • Step 5: Fit decision tree regressor to the dataset

Python3




# import the regressor
from sklearn.tree import DecisionTreeRegressor 
  
# create a regressor object
regressor = DecisionTreeRegressor(random_state = 0) 
  
# fit the regressor with X and Y data
regressor.fit(X, y)


Output:

DecisionTreeRegressor(ccp_alpha=0.0, criterion='mse', max_depth=None,
                      max_features=None, max_leaf_nodes=None,
                      min_impurity_decrease=0.0, min_impurity_split=None,
                      min_samples_leaf=1, min_samples_split=2,
                      min_weight_fraction_leaf=0.0, presort='deprecated',
                      random_state=0, splitter='best')
  • Step 6: Predicting a new value

Python3




# predicting a new value
  
# test the output by changing values, like 3750
y_pred = regressor.predict([[3750]])
  
# print the predicted price
print("Predicted price: % d\n"% y_pred) 


Output:

Predicted price:  8000
  • Step 7: Visualising the result

Python3




# arange for creating a range of values 
# from min value of X to max value of X 
# with a difference of 0.01 between two
# consecutive values
X_grid = np.arange(min(X), max(X), 0.01)
  
# reshape for reshaping the data into 
# a len(X_grid)*1 array, i.e. to make
# a column out of the X_grid values
X_grid = X_grid.reshape((len(X_grid), 1)) 
  
# scatter plot for original data
plt.scatter(X, y, color = 'red')
  
# plot predicted data
plt.plot(X_grid, regressor.predict(X_grid), color = 'blue') 
  
# specify title
plt.title('Profit to Production Cost (Decision Tree Regression)') 
  
# specify X axis label
plt.xlabel('Production Cost')
  
# specify Y axis label
plt.ylabel('Profit')
  
# show the plot
plt.show()


  • Step 8: The tree is finally exported and shown in the TREE STRUCTURE below, visualized using http://www.webgraphviz.com/ by copying the data from the ‘tree.dot’ file.

Python3




# import export_graphviz
from sklearn.tree import export_graphviz 
  
# export the decision tree to a tree.dot file
# for visualizing the plot easily anywhere
export_graphviz(regressor, out_file ='tree.dot',
               feature_names =['Production Cost']) 


Output (Decision Tree): 


 



Previous Article
Next Article

Similar Reads

Changing Colors for Decision Tree Plot Using Sklearn plot_tree
Decision trees are a popular machine learning model used for classification and regression tasks. Visualizing decision trees can provide insights into the decision-making process of the model, making it easier to interpret and explain the results. Scikit-learn, a widely used machine learning library in Python, offers a convenient method called plot
4 min read
Passing categorical data to Sklearn Decision Tree
Theoretically, decision trees are capable of handling numerical as well as categorical data, but, while implementing, we need to prepare the data for classification. There are two methods to handle the categorical data before training: one-hot encoding and label encoding. In this article, we understand how each method helps in converting categorica
5 min read
Python Sklearn – sklearn.datasets.load_breast_cancer() Function
In this article, we are going to see how to convert sklearn dataset to a pandas dataframe in Python. Sklearn is a python library that is used widely for data science and machine learning operations. Sklearn library provides a vast list of tools and functions to train machine learning models. The library is available via pip install. pip install sci
2 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
Python | Linear Regression using sklearn
Prerequisite: Linear Regression Linear Regression is a machine learning algorithm based on supervised learning. It performs a regression task. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on –
3 min read
ML | Logistic Regression v/s Decision Tree Classification
Logistic Regression and Decision Tree classification are two of the most popular and basic classification algorithms being used today. None of the algorithms is better than the other and one's superior performance is often credited to the nature of the data being worked upon. We can compare the two algorithms on different categories - CriteriaLogis
2 min read
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
Partial Least Squares Regression (PLSRegression) using Sklearn
Partial least square regression is a Machine learning Algorithm used for modelling the relationship between independent and dependent variables. This is mainly used when there are many interrelated independent variables. It is more commonly used in regression and latent variable modelling. It finds the directions (latent variables) in the independe
8 min read
Understanding Kernel Ridge Regression With Sklearn
Kernel ridge regression (KRR) is a powerful technique in scikit-learn for tackling regression problems, particularly when dealing with non-linear relationships between features and the target variable.  This technique allows for the modeling of complex, nonlinear relationships between variables, making it a valuable asset in data analysis. This art
7 min read
Decision Trees vs Clustering Algorithms vs Linear Regression
In machine learning, Decision Trees, Clustering Algorithms, and Linear Regression stand as pillars of data analysis and prediction. Decision Trees create structured pathways for decisions, Clustering Algorithms group similar data points, and Linear Regression models relationships between variables. In this article, we will discuss how each method h
6 min read
How to improve the performance of segmented regression using quantile regression in R?
Segmented regression, also known as piecewise or broken-line regression is a powerful statistical technique used to identify changes in the relationship between a dependent variable and one or more independent variables. Quantile regression, on the other hand, estimates the conditional quantiles of a response variable distribution in the linear mod
8 min read
ML | Linear Regression vs Logistic Regression
Linear Regression is a machine learning algorithm based on supervised regression algorithm. Regression models a target prediction value based on independent variables. It is mostly used for finding out the relationship between variables and forecasting. Different regression models differ based on – the kind of relationship between the dependent and
3 min read
Is least squares regression the same as linear regression
Yes, Least squares regression and linear regression are closely related in machine learning, but they’re not quite the same. Linear regression is a type of predictive model that assumes a linear relationship between input features and the output variable. Least squares is a common method used to find the best-fitting line in linear regression by mi
2 min read
The Difference between Linear Regression and Nonlinear Regression Models
areRegression analysis is a fundamental tool in statistical modelling used to understand the relationship between a dependent variable and one or more independent variables. Two primary types of regression models are linear regression and nonlinear regression. This article delves into the key differences between these models, their applications, an
7 min read
Analyzing Decision Tree and K-means Clustering using Iris dataset
Iris Dataset is one of best know datasets in pattern recognition literature. This dataset contains 3 classes of 50 instances each, where each class refers to a type of iris plant. One class is linearly separable from the other 2 the latter are NOT linearly separable from each other. Attribute Information:Sepal Length in cmSepal Width in cmPetal Len
5 min read
Feature selection using Decision Tree
Feature selection using decision trees involves identifying the most important features in a dataset based on their contribution to the decision tree's performance. The article aims to explore feature selection using decision trees and how decision trees evaluate feature importance. What is feature selection?Feature selection involves choosing a su
5 min read
Predict default payments using decision tree in R
Predicting default payments is a common task in finance, where we aim to identify whether a customer is likely to default on their loan based on various attributes. Decision trees are a popular choice for this task due to their interpretability and simplicity. In this article, we will demonstrate how to use decision trees in R to predict default pa
5 min read
Data Prediction using Decision Tree of rpart
Decision trees are a popular choice due to their simplicity and interpretation, and effectiveness at handling both numerical and categorical data. The rpart (Recursive Partitioning) package in R specializes in constructing these trees, offering a robust framework for building predictive models. Overview of rpartrpart stands for Recursive Partitioni
3 min read
Decision tree using continuous variable in R
Decision trees are widely used due to their simplicity and effectiveness. They split data into branches to form a tree structure based on decision rules, making them intuitive and easy to interpret. In R, several packages such as rpart and party are available to facilitate decision tree modeling. This guide will specifically delve into how to utili
5 min read
Python | Decision tree implementation
Decision Tree is one of the most powerful and popular algorithms. Python Decision-tree algorithm falls under the category of supervised learning algorithms. It works for both continuous as well as categorical output variables. In this article, We are going to implement a Decision tree in Python algorithm on the Balance Scale Weight & Distance D
15 min read
Python | Create Test DataSets using Sklearn
Python's Sklearn library provides a great sample dataset generator which will help you to create your own custom dataset. It's fast and very easy to use. Following are the types of samples it provides.For all the above methods you need to import sklearn.datasets.samples_generator. C/C++ Code # importing libraries from sklearn.datasets import make_b
3 min read
How To Do Train Test Split Using Sklearn In Python
In this article, let's learn how to do a train test split using Sklearn in Python. Train Test Split Using Sklearn The train_test_split() method is used to split our data into train and test sets. First, we need to divide our data into features (X) and labels (y). The dataframe gets divided into X_train,X_test , y_train and y_test. X_train and y_tra
5 min read
Decision Tree in R Programming
Decision Trees are useful supervised Machine learning algorithms that have the ability to perform both regression and classification tasks. It is characterized by nodes and branches, where the tests on each attribute are represented at the nodes, the outcome of this procedure is represented at the branches and the class labels are represented at th
8 min read
Decision Tree Classifiers in R Programming
Classification is the task in which objects of several categories are categorized into their respective classes using the properties of classes. A classification model is typically used to, Predict the class label for a new unlabeled data objectProvide a descriptive model explaining what features characterize objects in each class There are various
4 min read
C5.0 Algorithm of Decision Tree
The C5 algorithm, created by J. Ross Quinlan, is a development of the ID3 decision tree method. By recursively dividing the data according to information gain—a measurement of the entropy reduction achieved by splitting on a certain attribute—it constructs decision trees. For classification problems, the C5.0 method is a decision tree algorithm. It
12 min read
How to Determine the Best Split in Decision Tree?
Answer: To determine the best split in a decision tree, select the split that maximizes information gain or minimizes impurity.To determine the best split in a decision tree, follow these steps: Calculate Impurity Measure:Compute an impurity measure (e.g., Gini impurity or entropy) for each potential split based on the target variable's values in t
1 min read
How to Calculate Gini Index in Decision Tree?
Answer: To calculate the Gini index in a decision tree, compute the sum of squared probabilities of each class subtracted from one.To calculate the Gini index in a decision tree, follow these steps: Calculate Gini Impurity for Each Node:For a node t containing Nt​ data points, calculate the Gini impurity (G(t)) using the formula: [Tex]G(t) = 1-\sum
2 min read
How to Calculate Information Gain in Decision Tree?
Answer: To calculate information gain in a decision tree, subtract the weighted average entropy of child nodes from the entropy of the parent node.To calculate information gain in a decision tree, follow these steps: Calculate the Entropy of the Parent Node:Compute the entropy of the parent node using the formula: Entropy=−∑i=1 [Tex] \sum_{c}^{i=1}
2 min read
How to Calculate Training Error in Decision Tree?
Answer: To calculate training error in a decision tree, compare the predicted class labels with the actual class labels for the training data and calculate the misclassification rate or accuracy.To calculate the training error in a decision tree, follow these steps: Fit the Decision Tree Model:Train the decision tree model using the training datase
2 min read
Difference Between Random Forest and Decision Tree
Choosing the appropriate model is crucial when it comes to machine learning. A model that functions properly with one kind of dataset might not function well with another. Both Random Forest and Decision Tree are strong algorithms for applications involving regression and classification. The aim of the article is to cover the distinction between de
3 min read
Practice Tags :
three90RightbarBannerImg