titanic_sample_random_forest.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # In[4]:
  4. import pandas as pd
  5. # In[5]:
  6. # 1、获取数据
  7. titianic = pd.read_csv("./titanic.csv")
  8. titianic.head()
  9. # In[6]:
  10. # 筛选特征值和目标值
  11. x = titianic[["pclass", "age", "sex"]]
  12. y = titianic["survived"]
  13. # In[7]:
  14. x.head()
  15. # In[8]:
  16. y.head()
  17. # In[9]:
  18. # 2、数据处理
  19. # 1) 缺失值处理 age字段
  20. x.loc[:, "age"] = x["age"].fillna(x["age"].mean())
  21. # In[10]:
  22. # 2) 转换成字典
  23. x = x.to_dict(orient="records")
  24. # In[11]:
  25. from sklearn.model_selection import train_test_split
  26. # 3、数据集划分
  27. x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=22)
  28. # In[12]:
  29. # 4、字典特征抽取
  30. from sklearn.feature_extraction import DictVectorizer
  31. # In[13]:
  32. transfer = DictVectorizer()
  33. x_train = transfer.fit_transform(x_train)
  34. x_test = transfer.transform(x_test)
  35. # In[14]:
  36. from sklearn.tree import DecisionTreeClassifier
  37. from sklearn.tree import export_graphviz
  38. # 5、模型训练和预测
  39. estimator = DecisionTreeClassifier(criterion="entropy")
  40. estimator.fit(x_train, y_train)
  41. # 6、 模型评估
  42. # 方法一: 直接比对真实值和预测值
  43. y_predict = estimator.predict(x_test)
  44. print("直接比对真实值和预测值:\n", y_test == y_predict)
  45. # 方法二: 计算准确率
  46. score = estimator.score(x_test, y_test)
  47. print("准确率: \n", score)
  48. # 6) 决策树的可视化
  49. export_graphviz(estimator, out_file="./titian_tree.dot", feature_names=transfer.get_feature_names_out())
  50. # #### 随机森林预测泰坦尼克数据集
  51. # In[15]:
  52. from sklearn.ensemble import RandomForestClassifier
  53. from sklearn.model_selection import GridSearchCV
  54. # In[16]:
  55. # 4) 随机森林算法预估
  56. estimator = RandomForestClassifier(n_estimators=120, random_state=22, max_features="sqrt") # n_estimators: 树的数量
  57. # 加入网格搜索与交叉验证
  58. param_grid = {"n_estimators": [120, 200, 300, 500, 800, 1200],
  59. "max_depth": [5, 8, 15, 25, 30]}
  60. estimator = GridSearchCV(estimator, param_grid=param_grid, cv=3)
  61. estimator.fit(x_train, y_train)
  62. # 5) 模型评估
  63. # 方法一: 直接比对真实值和预测值
  64. y_predict = estimator.predict(x_test)
  65. print("y_predict:\n", y_predict)
  66. print("直接比对真实值和预测值:\n", y_test == y_predict)
  67. # 方法二: 计算准确率
  68. score = estimator.score(x_test, y_test)
  69. print("准确率: \n", score)
  70. # 6. 获取最佳参数
  71. print("最佳参数: \n", estimator.best_params_)
  72. print("最佳结果: \n", estimator.best_score_)
  73. print("最佳估计器: \n", estimator.best_estimator_)
  74. print("交叉验证结果: \n", estimator.cv_results_)