0% found this document useful (0 votes)
106 views10 pages

Random Forest Implementation in Python

This document describes implementing a random forest classifier in Python. It preprocesses data, fits the random forest model to training data, predicts test results, evaluates accuracy with a confusion matrix, and visualizes training and test results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views10 pages

Random Forest Implementation in Python

This document describes implementing a random forest classifier in Python. It preprocesses data, fits the random forest model to training data, predicts test results, evaluates accuracy with a confusion matrix, and visualizes training and test results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Implementation of Random Forest

Algorithm
Now we will implement the Random Forest Algorithm tree using Python. For this, we will
use the same dataset "user_data.csv", which we have used in previous classification
models. By using the same dataset, we can compare the Random Forest classifier with
other classification models such as Decision tree Classifier, KNN, SVM, Logistic
Regression, etc.

Implementation Steps are given below:

o Data Pre-processing step


o Fitting the Random forest algorithm to the Training set
o Predicting the test result
o Test accuracy of the result (Creation of Confusion matrix)
o Visualizing the test set result.

[Link] Pre-Processing Step:


Below is the code for the pre-processing step:

1. # importing libraries
2. import numpy as nm
3. import [Link] as mtp
4. import pandas as pd
5.
6. #importing datasets
7. data_set= pd.read_csv('user_data.csv')
8.
9. #Extracting Independent and dependent Variable
10. x= data_set.iloc[:, [2,3]].values
11. y= data_set.iloc[:, 4].values
12.
13. # Splitting the dataset into training and test set.
14. from sklearn.model_selection import train_test_split
15. x_train, x_test, y_train, y_test= train_test_split(x, y, test_size= 0.25, random_state=0
)
16.
17. #feature Scaling
18. from [Link] import StandardScaler
19. st_x= StandardScaler()
20. x_train= st_x.fit_transform(x_train)
21. x_test= st_x.transform(x_test)

1. # importing libraries
2. import numpy as nm
3. import [Link] as mtp
4. import pandas as pd
5.
6. #importing datasets
7. data_set= pd.read_csv('user_data.csv')
8.
9. #Extracting Independent and dependent Variable
10. x= data_set.iloc[:, [2,3]].values
11. y= data_set.iloc[:, 4].values
12.
13. # Splitting the dataset into training and test set.
14. from sklearn.model_selection import train_test_split
15. x_train, x_test, y_train, y_test= train_test_split(x, y, test_size= 0.25, random_state=0
)
16.
17. #feature Scaling
18. from [Link] import StandardScaler
19. st_x= StandardScaler()
20. x_train= st_x.fit_transform(x_train)
21. x_test= st_x.transform(x_test)

In the above code, we have pre-processed the data. Where we have loaded the dataset,
which is given as:
2. Fitting the Random Forest algorithm to the
training set:
Now we will fit the Random forest algorithm to the training set. To fit it, we will import
the RandomForestClassifier class from the [Link] library. The code is given
below:

1. #Fitting Decision Tree classifier to the training set


2. from [Link] import RandomForestClassifier
3. classifier= RandomForestClassifier(n_estimators= 10, criterion="entropy")
4. [Link](x_train, y_train)

1. #Fitting Decision Tree classifier to the training set


2. from [Link] import RandomForestClassifier
3. classifier= RandomForestClassifier(n_estimators= 10, criterion="entropy")
4. [Link](x_train, y_train)

In the above code, the classifier object takes below parameters:

o n_estimators= The required number of trees in the Random Forest. The default
value is 10. We can choose any number but need to take care of the overfitting
issue.
o criterion= It is a function to analyze the accuracy of the split. Here we have taken
"entropy" for the information gain.

Output:

RandomForestClassifier(bootstrap=True, class_weight=None, criterion='entropy',


max_depth=None, max_features='auto',
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, n_estimators=10,
n_jobs=None, oob_score=False, random_state=None,
verbose=0, warm_start=False)

3. Predicting the Test Set result


Since our model is fitted to the training set, so now we can predict the test result. For
prediction, we will create a new prediction vector y_pred. Below is the code for it:

1. #Predicting the test set result


2. y_pred= [Link](x_test)

1. #Predicting the test set result


2. y_pred= [Link](x_test)

Output:

The prediction vector is given as:


By checking the above prediction vector and test set real vector, we can determine the
incorrect predictions done by the classifier.

4. Creating the Confusion Matrix


Now we will create the confusion matrix to determine the correct and incorrect
predictions. Below is the code for it:

1. #Creating the Confusion matrix


2. from [Link] import confusion_matrix
3. cm= confusion_matrix(y_test, y_pred)

1. #Creating the Confusion matrix


2. from [Link] import confusion_matrix
3. cm= confusion_matrix(y_test, y_pred)

Output:

As we can see in the above matrix, there are 4+4= 8 incorrect predictions and 64+28=
92 correct predictions.

5. Visualizing the training Set result


Here we will visualize the training set result. To visualize the training set result we will
plot a graph for the Random forest classifier. The classifier will predict yes or No for the
users who have either Purchased or Not purchased the SUV car as we did in Logistic
Regression. Below is the code for it:

1. from [Link] import ListedColormap


2. x_set, y_set = x_train, y_train
3. x1, x2 = [Link]([Link](start = x_set[:, 0].min() - 1, stop = x_set[:, 0].max
() + 1, step =0.01),
4. [Link](start = x_set[:, 1].min() - 1, stop = x_set[:, 1].max() + 1, step = 0.01))
5. [Link](x1, x2, [Link]([Link]([[Link](), [Link]()]).T).reshape(x1
.shape),
6. alpha = 0.75, cmap = ListedColormap(('purple','green' )))
7. [Link]([Link](), [Link]())
8. [Link]([Link](), [Link]())
9. for i, j in enumerate([Link](y_set)):
10. [Link](x_set[y_set == j, 0], x_set[y_set == j, 1],
11. c = ListedColormap(('purple', 'green'))(i), label = j)
12. [Link]('Random Forest Algorithm (Training set)')
13. [Link]('Age')
14. [Link]('Estimated Salary')
15. [Link]()
16. [Link]()

1. from [Link] import ListedColormap


2. x_set, y_set = x_train, y_train
3. x1, x2 = [Link]([Link](start = x_set[:, 0].min() - 1, stop = x_set[:, 0].max
() + 1, step =0.01),
4. [Link](start = x_set[:, 1].min() - 1, stop = x_set[:, 1].max() + 1, step = 0.01))
5. [Link](x1, x2, [Link]([Link]([[Link](), [Link]()]).T).reshape(x1
.shape),
6. alpha = 0.75, cmap = ListedColormap(('purple','green' )))
7. [Link]([Link](), [Link]())
8. [Link]([Link](), [Link]())
9. for i, j in enumerate([Link](y_set)):
10. [Link](x_set[y_set == j, 0], x_set[y_set == j, 1],
11. c = ListedColormap(('purple', 'green'))(i), label = j)
12. [Link]('Random Forest Algorithm (Training set)')
13. [Link]('Age')
14. [Link]('Estimated Salary')
15. [Link]()
16. [Link]()

Output:
The above image is the visualization result for the Random Forest classifier working with
the training set result. It is very much similar to the Decision tree classifier. Each data
point corresponds to each user of the user_data, and the purple and green regions are
the prediction regions. The purple region is classified for the users who did not purchase
the SUV car, and the green region is for the users who purchased the SUV.

So, in the Random Forest classifier, we have taken 10 trees that have predicted Yes or
NO for the Purchased variable. The classifier took the majority of the predictions and
provided the result.

6. Visualizing the test set result


Now we will visualize the test set result. Below is the code for it:

1. #Visulaizing the test set result


2. from [Link] import ListedColormap
3. x_set, y_set = x_test, y_test
4. x1, x2 = [Link]([Link](start = x_set[:, 0].min() - 1, stop = x_set[:, 0].max
() + 1, step =0.01),
5. [Link](start = x_set[:, 1].min() - 1, stop = x_set[:, 1].max() + 1, step = 0.01))
6. [Link](x1, x2, [Link]([Link]([[Link](), [Link]()]).T).reshape(x1
.shape),
7. alpha = 0.75, cmap = ListedColormap(('purple','green' )))
8. [Link]([Link](), [Link]())
9. [Link]([Link](), [Link]())
10. for i, j in enumerate([Link](y_set)):
11. [Link](x_set[y_set == j, 0], x_set[y_set == j, 1],
12. c = ListedColormap(('purple', 'green'))(i), label = j)
13. [Link]('Random Forest Algorithm(Test set)')
14. [Link]('Age')
15. [Link]('Estimated Salary')
16. [Link]()
17. [Link]()

1. #Visulaizing the test set result


2. from [Link] import ListedColormap
3. x_set, y_set = x_test, y_test
4. x1, x2 = [Link]([Link](start = x_set[:, 0].min() - 1, stop = x_set[:, 0].max
() + 1, step =0.01),
5. [Link](start = x_set[:, 1].min() - 1, stop = x_set[:, 1].max() + 1, step = 0.01))
6. [Link](x1, x2, [Link]([Link]([[Link](), [Link]()]).T).reshape(x1
.shape),
7. alpha = 0.75, cmap = ListedColormap(('purple','green' )))
8. [Link]([Link](), [Link]())
9. [Link]([Link](), [Link]())
10. for i, j in enumerate([Link](y_set)):
11. [Link](x_set[y_set == j, 0], x_set[y_set == j, 1],
12. c = ListedColormap(('purple', 'green'))(i), label = j)
13. [Link]('Random Forest Algorithm(Test set)')
14. [Link]('Age')
15. [Link]('Estimated Salary')
16. [Link]()
17. [Link]()

Output:
The above image is the visualization result for the test set. We can check that there is a
minimum number of incorrect predictions (8) without the Overfitting issue. We will get
different results by changing the number of trees in the classifier.

Common questions

Powered by AI

The 'n_estimators' parameter in RandomForestClassifier defines the number of trees in the forest. Increasing 'n_estimators' generally improves the model's performance as it reduces variance and captures more patterns in the data. However, too many trees can lead to overfitting, making the model too complex and tailored to the training data's noise. It is crucial to balance accuracy and model generalizability by using techniques such as cross-validation to determine the optimal number of trees .

Increasing the number of trees in a Random Forest classifier generally helps in reducing errors in both training and test sets by averaging out individual decision tree biases. A greater number of trees can improve robustness and the model's ability to generalize, leading to higher accuracy on unseen data. However, beyond a certain point, it can also introduce diminishing returns and unnecessary computational complexity without significant gains in performance. Balancing these factors is key to achieving optimal model performance .

Data pre-processing for Random Forest involves several steps: loading the dataset, extracting relevant features and target variables, splitting the data into training and test sets, and standardizing feature scales. These steps ensure that the model has a balanced representation for training and that the input features are on a similar scale to prevent any bias in the model's predictions due to disparity in feature ranges .

Using 'entropy' as the splitting criterion affects decision trees within a Random Forest by focusing on information gain. Each split in the tree is chosen to maximize information gain, thereby ensuring that splits lead to purer child nodes. This results in more informative decision boundaries that classify data points with greater confidence, ultimately improving the forecasting accuracy of the model .

Feature scaling standardizes input data to ensure that the model evaluates all features equally, preventing any single feature from dominating due to its scale. While Random Forest is less sensitive to feature scaling compared to other algorithms like SVM or k-nearest neighbors, scaling can improve the convergence speed and performance especially when features have a wide range. Therefore, it is considered a best practice, particularly when the model incorporates distance-based metrics or comparisons across features .

Visualization of Random Forest's predictions on a test set can reveal signs of overfitting, where the model shows high accuracy on training data but poor performance on test data. By analyzing decision boundaries and misclassified test points, it becomes evident if the model has become too complex, capturing noise as patterns, leading to diminished generalization capability. Adjusting model complexity and parameters based on these insights can enhance test performance and model robustness .

The 'criterion' parameter in RandomForestClassifier, set to 'entropy,' specifies the function that measures the quality of a split in the decision trees. 'Entropy' measures the information gain by evaluating how well a node separates the classes based on the distribution of the data. Using entropy helps in creating informative and non-overlapping splits, enhancing the accuracy and efficiency of the classification process .

Visualizing prediction results helps in qualitatively assessing the model's decision boundaries, showing how the classifier separates different classes based on input features. For Random Forest models, plots highlight regions where predictions are correct or incorrect, facilitating an understanding of underfitting or overfitting issues. Visualization can also illustrate how changes in parameters (e.g., number of trees) affect model performance across different sectors of the input space, serving as a guide for parameter tuning .

Incorrect predictions reduce the overall accuracy of a Random Forest classifier, as they increase the total count of misclassifications compared to correct predictions. A confusion matrix provides a clear depiction of this impact by detailing false positives and false negatives. Analyzing these errors helps in identifying patterns or features leading to misclassifications, giving insights on possible data or model adjustments to increase reliability and predictive performance .

A confusion matrix is crucial for evaluating a Random Forest model's performance as it provides a detailed breakdown of correct and incorrect predictions by comparing actual versus predicted outcomes. It allows the calculation of key performance metrics such as accuracy, precision, recall, and F1-score. These insights help determine the model's effectiveness in predicting different classes and identifying areas where the model might be biased or overfitting, thus guiding further optimization .

You might also like