Python打卡第22天

@浙大疏锦行

import pandas as pd    #用于数据处理和分析,可处理表格数据。
import numpy as np     #用于数值计算,提供了高效的数组操作。
import matplotlib.pyplot as plt    #用于绘制各种类型的图表
import seaborn as sns   #基于matplotlib的高级绘图库,能绘制更美观的统计图形。

from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import classification_report, confusion_matrix
import warnings
import time
 
warnings.filterwarnings("ignore")
# 设置中文字体(解决中文显示问题)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
 
# 读取数据
train_data = pd.read_csv('train.csv')
test_data = pd.read_csv('test.csv')
gender_submission = pd.read_csv('gender_submission.csv')
 
# 打印读取后train_data和test_data的列名,检查是否正常读取
print("读取后train_data的列名:", train_data.columns)
print("读取后test_data的列名:", test_data.columns)
 
# 数据预处理
# Sex列标签编码
sex_mapping = {'male': 0, 'female': 1}
train_data['Sex'] = train_data['Sex'].map(sex_mapping)
test_data['Sex'] = test_data['Sex'].map(sex_mapping)
 
# Embarked列标签编码并处理缺失值
embarked_mapping = {'S': 0, 'C': 1, 'Q': 2}
train_data['Embarked'] = train_data['Embarked'].fillna('S').map(embarked_mapping)
test_data['Embarked'] = test_data['Embarked'].fillna('S').map(embarked_mapping)
 
# 处理Age列缺失值,用中位数填充
train_data['Age'] = train_data['Age'].fillna(train_data['Age'].median())
test_data['Age'] = test_data['Age'].fillna(test_data['Age'].median())
 
# 处理Fare列缺失值,用中位数填充
train_data['Fare'] = train_data['Fare'].fillna(train_data['Fare'].median())
test_data['Fare'] = test_data['Fare'].fillna(test_data['Fare'].median())
 
# 划分特征和标签
# 打印处理前X_train可能的列名
print("处理前X_train可能的列名:", train_data.columns)
X_train = train_data.drop(['Survived', 'Name', 'Ticket', 'Cabin', 'PassengerId'], axis = 1, errors='ignore')
# 检查X_train中是否还有PassengerId列
if 'PassengerId' in X_train.columns:
    print("X_train中仍存在PassengerId列,请检查数据处理逻辑")
y_train = train_data['Survived']
 
# 打印处理前X_test可能的列名
print("处理前X_test可能的列名:", test_data.columns)
X_test = test_data.drop(['Name', 'Ticket', 'Cabin', 'PassengerId'], axis = 1, errors='ignore')
# 检查X_test中是否还有PassengerId列
if 'PassengerId' in X_test.columns:
    print("X_test中仍存在PassengerId列,请检查数据处理逻辑")
y_test = gender_submission['Survived']
 
# --- 1. 默认参数的随机森林 ---
print("--- 1. 默认参数随机森林 (训练集 -> 测试集) ---")
start_time = time.time()
rf_model = RandomForestClassifier(random_state = 42)
rf_model.fit(X_train, y_train)
rf_pred = rf_model.predict(X_test)
end_time = time.time()
 
print(f"训练与预测耗时: {end_time - start_time:.4f} 秒")
print("\n默认随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred))
print("默认随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred))
读取后train_data的列名: Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
读取后test_data的列名: Index(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch',
       'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
处理前X_train可能的列名: Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
处理前X_test可能的列名: Index(['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch',
       'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
--- 1. 默认参数随机森林 (训练集 -> 测试集) ---
训练与预测耗时: 0.1793 秒

默认随机森林 在测试集上的分类报告:
              precision    recall  f1-score   support

           0       0.87      0.85      0.86       266
           1       0.75      0.78      0.76       152

    accuracy                           0.83       418
   macro avg       0.81      0.81      0.81       418
weighted avg       0.83      0.83      0.83       418

默认随机森林 在测试集上的混淆矩阵:
[[227  39]
 [ 34 118]]

from sklearn.ensemble import RandomForestClassifier #随机森林分类器

from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # 用于评估分类器性能的指标
from sklearn.metrics import classification_report, confusion_matrix #用于生成分类报告和混淆矩阵
import warnings #用于忽略警告信息
warnings.filterwarnings("ignore") # 忽略所有警告信息
# --- 2. 网格搜索优化随机森林 ---
print("\n--- 2. 网格搜索优化随机森林 (训练集 -> 测试集) ---")
from sklearn.model_selection import GridSearchCV

# 定义要搜索的参数网格
param_grid = {
    'n_estimators': [50, 100, 200],
    'max_depth': [None, 10, 20, 30],
    'min_samples_split': [2, 5, 10],
    'min_samples_leaf': [1, 2, 4]
}

# 创建网格搜索对象
grid_search = GridSearchCV(estimator=RandomForestClassifier(random_state=42), # 随机森林分类器
                           param_grid=param_grid, # 参数网格
                           cv=5, # 5折交叉验证
                           n_jobs=-1, # 使用所有可用的CPU核心进行并行计算
                           scoring='accuracy') # 使用准确率作为评分标准

start_time = time.time()
# 在训练集上进行网格搜索
grid_search.fit(X_train, y_train) # 在训练集上训练,模型实例化和训练的方法都被封装在这个网格搜索对象里了
end_time = time.time()

print(f"网格搜索耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", grid_search.best_params_) #best_params_属性返回最佳参数组合

# 使用最佳参数的模型进行预测
best_model = grid_search.best_estimator_ # 获取最佳模型
best_pred = best_model.predict(X_test) # 在测试集上进行预测

print("\n网格搜索优化后的随机森林 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("网格搜索优化后的随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))
--- 2. 网格搜索优化随机森林 (训练集 -> 测试集) ---
网格搜索耗时: 31.3900 秒
最佳参数:  {'max_depth': 20, 'min_samples_leaf': 1, 'min_samples_split': 10, 'n_estimators': 50}

网格搜索优化后的随机森林 在测试集上的分类报告:
              precision    recall  f1-score   support

           0       0.87      0.91      0.89       266
           1       0.82      0.76      0.79       152

    accuracy                           0.85       418
   macro avg       0.84      0.83      0.84       418
weighted avg       0.85      0.85      0.85       418

网格搜索优化后的随机森林 在测试集上的混淆矩阵:
[[241  25]
 [ 37 115]]
! pip install  scikit-optimize -i https://pypi.tuna.tsinghua.edu.cn/simple
# --- 2. 贝叶斯优化随机森林 ---
print("\n--- 2. 贝叶斯优化随机森林 (训练集 -> 测试集) ---")
from skopt import BayesSearchCV
from skopt.space import Integer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
import time

# 定义要搜索的参数空间
search_space = {
    'n_estimators': Integer(50, 200),
    'max_depth': Integer(10, 30),
    'min_samples_split': Integer(2, 10),
    'min_samples_leaf': Integer(1, 4)
}

# 创建贝叶斯优化搜索对象
bayes_search = BayesSearchCV(
    estimator=RandomForestClassifier(random_state=42),
    search_spaces=search_space,
    n_iter=32,  # 迭代次数,可根据需要调整
    cv=5, # 5折交叉验证,这个参数是必须的,不能设置为1,否则就是在训练集上做预测了
    n_jobs=-1,
    scoring='accuracy'
)

start_time = time.time()
# 在训练集上进行贝叶斯优化搜索
bayes_search.fit(X_train, y_train)
end_time = time.time()

print(f"贝叶斯优化耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", bayes_search.best_params_)

# 使用最佳参数的模型进行预测
best_model = bayes_search.best_estimator_
best_pred = best_model.predict(X_test)

print("\n贝叶斯优化后的随机森林 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("贝叶斯优化后的随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))
--- 2. 贝叶斯优化随机森林 (训练集 -> 测试集) ---
贝叶斯优化耗时: 68.6010 秒
最佳参数:  OrderedDict([('max_depth', 30), ('min_samples_leaf', 2), ('min_samples_split', 7), ('n_estimators', 200)])

贝叶斯优化后的随机森林 在测试集上的分类报告:
              precision    recall  f1-score   support

           0       0.87      0.92      0.90       266
           1       0.85      0.76      0.80       152

    accuracy                           0.86       418
   macro avg       0.86      0.84      0.85       418
weighted avg       0.86      0.86      0.86       418

贝叶斯优化后的随机森林 在测试集上的混淆矩阵:
[[245  21]
 [ 36 116]]
! pip install bayesian-optimization -i https://mirrors.aliyun.com/pypi/simple/
# --- 2. 贝叶斯优化随机森林 ---
print("\n--- 2. 贝叶斯优化随机森林 (训练集 -> 测试集) ---")
from bayes_opt import BayesianOptimization
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.metrics import classification_report, confusion_matrix
import time
import numpy as np

# 假设 X_train, y_train, X_test, y_test 已经定义好
# 定义目标函数,这里使用交叉验证来评估模型性能
def rf_eval(n_estimators, max_depth, min_samples_split, min_samples_leaf):
    n_estimators = int(n_estimators)
    max_depth = int(max_depth)
    min_samples_split = int(min_samples_split)
    min_samples_leaf = int(min_samples_leaf)
    model = RandomForestClassifier(
        n_estimators=n_estimators,
        max_depth=max_depth,
        min_samples_split=min_samples_split,
        min_samples_leaf=min_samples_leaf,
        random_state=42
    )
    scores = cross_val_score(model, X_train, y_train, cv=5, scoring='accuracy')
    return np.mean(scores)

# 定义要搜索的参数空间
pbounds_rf = {
    'n_estimators': (50, 200),
   'max_depth': (10, 30),
   'min_samples_split': (2, 10),
   'min_samples_leaf': (1, 4)
}

# 创建贝叶斯优化对象,设置 verbose=2 显示详细迭代信息
optimizer_rf = BayesianOptimization(
    f=rf_eval, # 目标函数
    pbounds=pbounds_rf, # 参数空间
    random_state=42, # 随机种子
    verbose=2  # 显示详细迭代信息
)

start_time = time.time()
# 开始贝叶斯优化
optimizer_rf.maximize(
    init_points=5,  # 初始随机采样点数
    n_iter=32  # 迭代次数
)
end_time = time.time()

print(f"贝叶斯优化耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", optimizer_rf.max['params'])

# 使用最佳参数的模型进行预测
best_params = optimizer_rf.max['params']
best_model = RandomForestClassifier(
    n_estimators=int(best_params['n_estimators']),
    max_depth=int(best_params['max_depth']),
    min_samples_split=int(best_params['min_samples_split']),
    min_samples_leaf=int(best_params['min_samples_leaf']),
    random_state=42
)
best_model.fit(X_train, y_train)
best_pred = best_model.predict(X_test)

print("\n贝叶斯优化后的随机森林 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("贝叶斯优化后的随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))
--- 2. 贝叶斯优化随机森林 (训练集 -> 测试集) ---

贝叶斯优化耗时: 64.1209 秒
最佳参数:  {'max_depth': np.float64(10.747174663868378), 'min_samples_leaf': np.float64(1.424777414608795), 'min_samples_split': np.float64(2.1413174082993267), 'n_estimators': np.float64(175.89825430988975)}

贝叶斯优化后的随机森林 在测试集上的分类报告:
              precision    recall  f1-score   support

           0       0.88      0.91      0.89       266
           1       0.83      0.78      0.80       152

    accuracy                           0.86       418
   macro avg       0.85      0.84      0.85       418
weighted avg       0.86      0.86      0.86       418

贝叶斯优化后的随机森林 在测试集上的混淆矩阵:
[[242  24]
 [ 34 118]]

你可能感兴趣的:(Python打卡60天,python,开发语言,机器学习)