随机森林是集成方法的一种。
集成方法指的是用多个分类器进行组合而成的方法。
随机森林是用多个决策树组合起来的方法。
两个随机:
1.训练集随机:N个样本中随机有放回的出去N个。
2.特征随机:从M个特征中随机抽取m个特征, 其中M>>m。
这相当于一种降维方法。
优点:1、具有极好的准确率,会比用到的单一的分类器效果要好。
2、适合在大数据集,处理高维特征,不需要降维。
python 代码为:
首先需要引入随机森林库以及用到的所需要的库:
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
定义函数randForest():
def randForest():
path = "E:\data\\titanic.csv"
titanic = pd.read_csv(path)
# print("type(titanic):",type(titanic))
# 1.处理特征值和目标值
x = titanic[["pclass", "age", "sex"]]
# print(x)
y = titanic["survived"]
# print(y)
# print("x1:",x,type(x))
# 2.特征值处理
# (1)缺失值处理
x["age"].fillna(x["age"].mean(), inplace=True)
# print("x2:", x)
# #(2)转化成字典
x = x.to_dict(orient="records")
# print("x3:", x)
# #3.数据集划分
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=22)
# print(x_train)
# #4.字典特征抽取
transfer = DictVectorizer()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
#5.随机森林 网格搜索
estimator=RandomForestClassifier() #在此处与决策树不同,此处用的随机森林。
param_dict = {"n_estimators": [120, 200, 300, 800, 1200],"max_depth":[5,8,15,25,30]} #n_estimators 表示树的数量
estimator = GridSearchCV(estimator, param_grid=param_dict, cv=3)
estimator.fit(x_train, y_train)
# 5.模型评估
# 1.直接比对
y_predict = estimator.predict(x_test)
print("y_predict:\n", y_predict)
print("直接比对真实值和预测值:\n", y_test == y_predict)
# 2.计算准确率
score = estimator.score(x_test, y_test)
print("准确率为:\n", score)
# 最佳参数:best_params_
print("最佳参数:\n", estimator.best_params_)
# 最佳结果:best_score_
print("最佳结果:\n", estimator.best_score_)
# 最佳估计器:best_estimator_
print("最佳估计器:\n", estimator.best_estimator_)
# 交叉验证结果:cv_results_
print("交叉验证结果:\n", estimator.cv_results_)
return None