python机器学习之用随机森林处理泰坦尼克号数据

随机森林是集成方法的一种。

集成方法指的是用多个分类器进行组合而成的方法。

随机森林是用多个决策树组合起来的方法。

两个随机:

        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
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值