Python 如何使用Scikit-learn创建随机森林分类器

Python 如何使用Scikit-learn创建随机森林分类器

随机森林 是一种监督学习算法,通过在数据样本上创建决策树来用于分类、回归和其他任务。在创建了决策树之后,随机森林分类器收集每个决策树的预测结果,并通过投票方式选择最佳解决方案。

随机森林分类器最好的优点之一是通过平均结果来减少过拟合。这就是为什么与单个决策树相比,我们获得更好结果的原因。

创建随机森林分类器的步骤

我们可以按照以下步骤使用Python的Scikit-learn创建随机森林分类器:

步骤 1 - 导入所需的库。

步骤 2 - 加载数据集。

步骤 3 - 将数据集分为训练和测试数据集。

步骤 4 - 从sklearn.ensemble模块中导入随机森林分类器。

步骤 5 - 创建数据集的数据框。

步骤 6 - 创建随机森林分类器并使用fit()函数训练模型。

步骤 7 - 对测试数据集进行预测。

步骤 8 - 导入指标以找到分类器的准确度。

步骤 9 - 打印随机森林分类器的准确度。

示例

在下面的示例中,我们将使用鸢尾花数据集来构建一个随机森林分类器:

# Import required libraries
import sklearn
import pandas as pd
from sklearn import datasets

# Load the iris dataset from sklearn
iris_clf = datasets.load_iris()
print(iris_clf.target_names)
print(iris_clf.feature_names)

# Dividing the datasets into training datasets and test datasets
X, y = datasets.load_iris( return_X_y = True)
from sklearn.model_selection import train_test_split

# 60 % training dataset and 40 % test datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.40)

# Import random forest classifier from sklearn assemble module
from sklearn.ensemble import RandomForestClassifier

# Create dataframe
data = pd.DataFrame({'sepallength': iris_clf.data[:, 0],
'sepalwidth': iris_clf.data[:, 1],
'petallength': iris_clf.data[:, 2],
'petalwidth': iris_clf.data[:, 3],
'species': iris_clf.target})

# Create a Random Forest classifier
RForest_clf = RandomForestClassifier(n_estimators = 100)

# Train the model on the training dataset by using fit() function
RForest_clf.fit(X_train, y_train)

# Predict from the test dataset
y_pred = RForest_clf.predict(X_test)

# Import metrics for accuracy calculation
from sklearn import metrics
print('\n'"Accuracy of our Random Forst Classifier is: ",
metrics.accuracy_score(y_test, y_pred)*100)

输出

它将产生以下输出:

['setosa' 'versicolor' 'virginica']
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']

Accuracy of our Random Forst Classifier is: 95.0

让我们使用我们的分类器来预测花的类型 –

# Predicting the type of flower
RForest_clf.predict([[5, 4, 3, 1]])

输出

它会产生以下输出 –

array([1])

array([1])代表着变色鸢尾类型。

# Predicting the type of flower
RForest_clf.predict([[5, 4, 5, 2]])

输出

它将产生以下输出

array([2])

在这里,array([2])代表着Virginica类型。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程