📅  最后修改于: 2020-12-10 05:56:04             🧑  作者: Mango
本章将帮助您了解Sklearn中的随机决策树。
众所周知,DT通常是通过递归拆分数据来训练的,但是容易过度拟合,通过在数据的各个子样本上训练许多树,可以将它们转换为随机森林。 sklearn.ensemble模块具有以下两种基于随机决策树的算法-
对于考虑中的每个特征,它都会计算局部最优特征/分割组合。在随机森林中,集合中的每个决策树都是根据从训练集中替换而来的样本构建的,然后从每个样本中获取预测,最后通过投票选择最佳解决方案。它可以用于分类以及回归任务。
为了创建随机森林分类器,Scikit-learn模块提供了sklearn.ensemble.RandomForestClassifier 。在构建随机森林分类器时,此模块使用的主要参数是‘max_features’和‘n_estimators’ 。
在这里, “ max_features”是分割节点时要考虑的特征随机子集的大小。如果我们将此参数的值选择为none,则它将考虑所有功能,而不是随机子集。另一方面, n_estimators是森林中树木的数量。树的数量越多,结果越好。但是计算也需要更长的时间。
在下面的示例中,我们将使用sklearn.ensemble.RandomForestClassifier构建一个随机森林分类器,并使用cross_val_score模块检查其准确性。
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
X, y = make_blobs(n_samples = 10000, n_features = 10, centers = 100,random_state = 0) RFclf = RandomForestClassifier(n_estimators = 10,max_depth = None,min_samples_split = 2, random_state = 0)
scores = cross_val_score(RFclf, X, y, cv = 5)
scores.mean()
0.9997
我们还可以使用sklearn数据集构建随机森林分类器。如以下示例所示,我们使用虹膜数据集。我们还将找到其准确性得分和混淆矩阵。
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
path = "https://archive.ics.uci.edu/ml/machine-learning-database
s/iris/iris.data"
headernames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']
dataset = pd.read_csv(path, names = headernames)
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)
RFclf = RandomForestClassifier(n_estimators = 50)
RFclf.fit(X_train, y_train)
y_pred = RFclf.predict(X_test)
result = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(result)
result1 = classification_report(y_test, y_pred)
print("Classification Report:",)
print (result1)
result2 = accuracy_score(y_test,y_pred)
print("Accuracy:",result2)
Confusion Matrix:
[[14 0 0]
[ 0 18 1]
[ 0 0 12]]
Classification Report:
precision recall f1-score support
Iris-setosa 1.00 1.00 1.00 14
Iris-versicolor 1.00 0.95 0.97 19
Iris-virginica 0.92 1.00 0.96 12
micro avg 0.98 0.98 0.98 45
macro avg 0.97 0.98 0.98 45
weighted avg 0.98 0.98 0.98 45
Accuracy: 0.9777777777777777
为了创建随机森林回归,Scikit-learn模块提供了sklearn.ensemble.RandomForestRegressor 。在构建随机森林回归器时,它将使用与sklearn.ensemble.RandomForestClassifier相同的参数。
在下面的示例中,我们将使用sklearn.ensemble.RandomForestregressor构建一个随机森林回归器,并且还将通过使用prepare ()方法预测新值。
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression
X, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False)
RFregr = RandomForestRegressor(max_depth = 10,random_state = 0,n_estimators = 100)
RFregr.fit(X, y)
RandomForestRegressor(
bootstrap = True, criterion = 'mse', max_depth = 10,
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 = 100, n_jobs = None,
oob_score = False, random_state = 0, verbose = 0, warm_start = False
)
一旦拟合,我们可以从回归模型预测如下:
print(RFregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))
[98.47729198]
对于考虑中的每个功能,它都会为分割选择一个随机值。使用额外的树方法的好处在于,它可以进一步减少模型的方差。使用这些方法的缺点是它会稍微增加偏差。
为了使用Extra-tree方法创建分类器,Scikit-learn模块提供了sklearn.ensemble.ExtraTreesClassifier 。它使用与sklearn.ensemble.RandomForestClassifier相同的参数。唯一的区别在于,它们在构建树木的方式如上所述。
在以下示例中,我们将使用sklearn.ensemble.ExtraTreeClassifier构建一个随机森林分类器,并使用cross_val_score模块检查其准确性。
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_blobs
from sklearn.ensemble import ExtraTreesClassifier
X, y = make_blobs(n_samples = 10000, n_features = 10, centers=100,random_state = 0)
ETclf = ExtraTreesClassifier(n_estimators = 10,max_depth = None,min_samples_split = 10, random_state = 0)
scores = cross_val_score(ETclf, X, y, cv = 5)
scores.mean()
1.0
我们还可以使用sklearn数据集通过Extra-Tree方法构建分类器。如以下示例所示,我们使用的是Pima-Indian数据集。
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import ExtraTreesClassifier
path = r"C:\pima-indians-diabetes.csv"
headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names=headernames)
array = data.values
X = array[:,0:8]
Y = array[:,8]
seed = 7
kfold = KFold(n_splits=10, random_state=seed)
num_trees = 150
max_features = 5
ETclf = ExtraTreesClassifier(n_estimators=num_trees, max_features=max_features)
results = cross_val_score(ETclf, X, Y, cv=kfold)
print(results.mean())
0.7551435406698566
为了创建Extra-Tree回归,Scikit-learn模块提供了sklearn.ensemble.ExtraTreesRegressor 。在构建随机森林回归器时,它将使用与sklearn.ensemble.ExtraTreesClassifier相同的参数。
在以下示例中,我们将sklearn.ensemble.ExtraTreesregressor应用于创建随机森林回归器时所使用的相同数据。让我们看看输出的区别
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.datasets import make_regression
X, y = make_regression(n_features = 10, n_informative = 2,random_state = 0, shuffle = False)
ETregr = ExtraTreesRegressor(max_depth = 10,random_state = 0,n_estimators = 100)
ETregr.fit(X, y)
ExtraTreesRegressor(bootstrap = False, criterion = 'mse', max_depth = 10,
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 = 100, n_jobs = None,
oob_score = False, random_state = 0, verbose = 0, warm_start = False)
一旦拟合,我们可以从回归模型预测如下:
print(ETregr.predict([[0, 2, 3, 0, 1, 1, 1, 1, 2, 2]]))
[85.50955817]