隨機森林是一種集成學習方法(ensemble),由許多棵決策樹構成的森林共同來進行預測。為什么叫“隨機”森林呢?隨機主要體現在以下兩個方面:
1.每棵樹的訓練集是隨機且有放回抽樣產生的;
2.訓練樣本的特征是隨機選取的。
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0,random_state=0, shuffle=False)
clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)
clf.fit(X, y)
#生成的隨機森林具體的參數
#RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini', max_depth=2, max_features='auto', max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, in_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(clf.feature_importances_)
out:[0.14205973 0.76664038 0.0282433 0.06305659]
print(clf.predict([[0, 0, 0, 0]]))
out:[1]
隨機森林函數的參數以及方法
class sklearn.ensemble.RandomForestClassifier(n_estimators=10, criterion='gini', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features='auto', max_leaf_nodes=None, min_impurity_split=1e-07, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False, class_weight=None)
參數
- n_estimators : integer, optional (default=10)
隨機森林中樹的數量; - criterion : string, optional (default=”gini”)
樹分裂的規則:gini系數,entropy熵; - max_features : int, float, string or None, optional (default=”auto”)
查找最佳分裂所需考慮的特征數,
int:分裂的最大特征數,
float:分裂的特征占比,
auto、sqrt:sqrt(n_features),
log2:log2(n_features),
None:n_features, - max_depth : integer or None, optional (default=None)
樹的最大深度; - min_samples_split:int, float, optional (default=2)
最小分裂樣本數; - min_samples_leaf : int, float, optional (default=1)
最小葉子節點樣本數; - min_weight_fraction_leaf : float, optional (default=0.)
最小葉子節點權重; - max_leaf_nodes : int or None, optional (default=None)
最大葉子節點數; - min_impurity_split : float, optional (default=1e-7)
分裂的最小不純度; - bootstrap : boolean, optional (default=True)
是否使用bootstrap; - oob_score : bool (default=False)
是否使用袋外(out-of-bag)樣本估計準確度; - n_jobs : integer, optional (default=1)
并行job數,-1 代表全部; - random_state : int, RandomState instance or None, optional (default=None)
隨機數種子; - verbose : int, optional (default=0)
Controls the verbosity of the tree building process.(控制樹冗余?) - warm_start : bool, optional (default=False)
如果設置為True,在之前的模型基礎上預測并添加模型,否則,建立一個全新的森林; - class_weight : dict, list of dicts, “balanced”,
“balanced” 模式自動調整權重,每類的權重為 n_samples / (n_classes * np.bincount(y)),即類別數的倒數除以每類樣本數的占比。
屬性
- estimators_ : list of DecisionTreeClassifier
森林中的樹; - classes_ : array of shape = [n_classes] or a list of such arrays
類標簽; - n_classes_ : int or list
類; - n_features_ : int
特征數; - n_outputs_ : int
輸出數; - feature_importances_ : array of shape = [n_features]
特征重要性; - oob_score_ : float
使用袋外樣本估計的準確率; - oob_decision_function_ : array of shape = [n_samples, n_classes]
決策函數