赞
踩
目录
1.决策树与随机森林都属于机器学习中监督学习的范畴,主要用于分类问题。
决策树算法有这几种:ID3、C4.5、CART,基于决策树的算法有bagging、随机森林、GBDT等。
决策树是一种利用树形结构进行决策的算法,对于样本数据根据已知条件或叫特征进行分叉,最终建立一棵树,树的叶子结节标识最终决策。新来的数据便可以根据这棵树进行判断。随机森林是一种通过多棵决策树进行优化决策的算法。
上述已经提到,随机森林的基本思想为: 生成n棵决策树,然后这n棵决策树进行投票或者平均得出最终结果。而每棵树生成的方式为随机选取样本、随机地选择特征。下面为随机森林的算法:
优点:
具有极高的准确率
随机性的引入,使得随机森林不容易过拟合
随机性的引入,使得随机森林有很好的抗噪声能力
能处理很高维度的数据,并且不用做特征选择
既能处理离散型数据,也能处理连续型数据,数据集无需规范化
训练速度快,可以得到变量重要性排序
容易实现并行化
缺点:
当随机森林中的决策树个数很多时,训练时需要的空间和时间会较大
随机森林模型还有许多不好解释的地方,有点算个黑盒模型
数据维度相对低(几十维),同时对准确性有较高要求时。因为不需要很多参数调整就可以达到不错的效果,基本上不知道用什么方法的时候都可以先试一下随机森林。
- # -*- coding: utf-8 -*-
-
- import numpy as np
- from decision_tree_model import ClassificationTree
- from sklearn import datasets
- from sklearn.model_selection import train_test_split
-
- class RandomForest():
- """Random Forest classifier. Uses a collection of classification trees that
- trains on random subsets of the data using a random subsets of the features.
- Parameters:
- -----------
- n_estimators: int
- 树的数量
- The number of classification trees that are used.
- max_features: int
- 每棵树选用数据集中的最大的特征数
- The maximum number of features that the classification trees are allowed to
- use.
- min_samples_split: int
- 每棵树中最小的分割数,比如 min_samples_split = 2表示树切到还剩下两个数据集时就停止
- The minimum number of samples needed to make a split when building a tree.
- min_gain: float
- 每棵树切到小于min_gain后停止
- The minimum impurity required to split the tree further.
- max_depth: int
- 每棵树的最大层数
- The maximum depth of a tree.
- """
-
- def __init__(self, n_estimators=100, min_samples_split=2, min_gain=0,
- max_depth=float("inf"), max_features=None):
-
- self.n_estimators = n_estimators #树的数量
- self.min_samples_split = min_samples_split #每棵树中最小的分割数,比如 min_samples_split = 2表示树切到还剩下两个数据集时就停止
- self.min_gain = min_gain #每棵树切到小于min_gain后停止
- self.max_depth = max_depth #每棵树的最大层数
- self.max_features = max_features #每棵树选用数据集中的最大的特征数
-
- self.trees = []
- # 建立森林(bulid forest)
- for _ in range(self.n_estimators):
- tree = ClassificationTree(min_samples_split=self.min_samples_split, min_impurity=self.min_gain,
- max_depth=self.max_depth)
- self.trees.append(tree)
-
- def fit(self, X, Y):
- # 训练,每棵树使用随机的数据集(bootstrap)和随机的特征
- # every tree use random data set(bootstrap) and random feature
- sub_sets = self.get_bootstrap_data(X, Y)
- n_features = X.shape[1]
-
- if self.max_features == None:
- self.max_features = int(np.sqrt(n_features))
- for i in range(self.n_estimators):
- # 生成随机的特征
- # get random feature
- sub_X, sub_Y = sub_sets[i]
- idx = np.random.choice(n_features, self.max_features, replace=True)
- sub_X = sub_X[:, idx]
- self.trees[i].fit(sub_X, sub_Y)
- self.trees[i].feature_indices= idx
- print("tree", i, "fit complete")
-
- def predict(self, X):
- y_preds = []
- for i in range(self.n_estimators):
- idx = self.trees[i].feature_indices
- sub_X = X[:, idx]
- y_pre = self.trees[i].predict(sub_X)
- y_preds.append(y_pre)
- y_preds = np.array(y_preds).T
- y_pred = []
- for y_p in y_preds:
- # np.bincount()可以统计每个索引出现的次数
- # np.argmax()可以返回数组中最大值的索引
- # cheak np.bincount() and np.argmax() in numpy Docs
- y_pred.append(np.bincount(y_p.astype('int')).argmax())
- return y_pred
-
- def get_bootstrap_data(self, X, Y):
-
- # 通过bootstrap的方式获得n_estimators组数据
- # get int(n_estimators) datas by bootstrap
-
- m = X.shape[0] #行数
- Y = Y.reshape(m, 1)
-
- # 合并X和Y,方便bootstrap (conbine X and Y)
- X_Y = np.hstack((X, Y)) #np.vstack():在竖直方向上堆叠/np.hstack():在水平方向上平铺
- np.random.shuffle(X_Y) #随机打乱
-
- data_sets = []
- for _ in range(self.n_estimators):
- idm = np.random.choice(m, m, replace=True) #在range(m)中,有重复的选取 m个数字
- bootstrap_X_Y = X_Y[idm, :]
- bootstrap_X = bootstrap_X_Y[:, :-1]
- bootstrap_Y = bootstrap_X_Y[:, -1:]
- data_sets.append([bootstrap_X, bootstrap_Y])
- return data_sets
-
-
- if __name__ == '__main__':
- data = datasets.load_digits()
- X = data.data
- y = data.target
-
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=2)
- print("X_train.shape:", X_train.shape)
- print("Y_train.shape:", y_train.shape)
-
- clf = RandomForest(n_estimators=100)
- clf.fit(X_train, y_train)
- y_pred = clf.predict(X_test)
-
- accuracy = accuracy_score(y_test, y_pred)
- print('y_test:{}\ty_pred:{}'.format(y_test, y_pred))
- print("Accuracy:", accuracy)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。