机器学习 - 不同分类模型的比较

一、模型训练

本案例中,我们将通过四种不同的模型来预测泰坦尼克号乘客的生存情况。
一下是训练的具体步骤。

加载数据

从seaborn库中加载目标数据。该数据集包括多个特征,如 PassengerId, Pclass, Name, Sex, Age, SibSp, Parch, Ticket, Fare, Cabin, 和 Embarked。我们训练使用特征 Pclass, Age, Fare, 和 Sex,标签列为 Survived

import pandas as pd
import seaborn as sns

# Load the Titanic dataset
data = sns.load_dataset('titanic')
print(data.head())

Result
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   
3            4         1       1   
4            5         0       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  35.0      1   
4                           Allen, Mr. William Henry    male  35.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  
3      0            113803  53.1000  C123        S  
4      0            373450   8.0500   NaN        S  

数据预处理

在本案例中,我们的目标是预测泰坦尼克号乘客的生存情况。首先,我将详细介绍使用的数据预处理方法,这是确保模型表现良好的重要步骤。

1. 缺失值处理

在泰坦尼克号数据集中,Age 是存在缺失值的重要特征。处理缺失值是确保模型准确性的关键步骤之一。

# Handle missing values for 'Age'
imputer = SimpleImputer(strategy='mean')
features['Age'] = imputer.fit_transform(features[['Age']])
  • SimpleImputer(strategy='mean'): 这行代码创建了一个填充器对象,指定使用均值(mean)来填充缺失值。
  • imputer.fit_transform(features[['Age']]): 这里应用填充器,计算所有已知年龄的均值,并填充到缺失的位置。这种方法假设年龄数据的缺失是随机的,使用均值是合理的首选。
2. 类别特征编码

Sex 列是分类数据,包含文本值(male/female),需要转换为模型可处理的数值形式。

# Convert 'Sex' from categorical to numerical
encoder = LabelEncoder()
features['Sex'] = encoder.fit_transform(features['Sex'])
  • LabelEncoder(): 这行代码创建了一个标签编码器,用于将文本标签转换为唯一的整数。
  • encoder.fit_transform(features['Sex']): 应用编码器,将 malefemale 分别转换为数值(例如 0 和 1)。这是必须的步骤,因为大多数机器学习算法在训练过程中不能直接处理文本数据。
3. 特征缩放

由于KNN和许多其他机器学习算法对数据的尺度敏感,所以对特征进行标准化是很重要的。

# Standardize the features
scaler = StandardScaler()
features_scaled = scaler.fit_transform(features)
  • StandardScaler(): 创建一个标准化器,用于将特征缩放到具有零均值和单位方差的范围内。
  • scaler.fit_transform(features): 应用标准化处理,确保所有特征都处于相同的尺度,有助于改善模型的性能和收敛速度。
4. 数据集划分

最后,数据被划分为训练集和测试集,用于训练模型和评估其性能。

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features_scaled, target, test_size=0.2, random_state=42)
  • train_test_split(): 这个函数将数据随机分为训练集和测试集,test_size=0.2 表示 20% 的数据用于测试,剩下的 80% 用于训练。random_state=42 确保每次数据分割的方式相同,这对于可复现性是很重要的。

这些预处理步骤确保了数据的一致性和适用性,是后续模型训练和验证的基础。

5.数据预处理代码
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.metrics import classification_report

# Select the required features and the target
features = data[['Pclass', 'Age', 'Fare', 'Sex']]
target = data['Survived']

# Handle missing values for 'Age'
imputer = SimpleImputer(strategy='mean')
features['Age'] = imputer.fit_transform(features[['Age']])

# Convert 'Sex' from categorical to numerical
encoder = LabelEncoder()
features['Sex'] = encoder.fit_transform(features['Sex'])

# Standardize the features
scaler = StandardScaler()
features_scaled = scaler.fit_transform(features)

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features_scaled, target, test_size=0.2, random_state=42)

KNN模型训练

from sklearn.neighbors import KNeighborsClassifier

# Train the KNN model
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)

# Predictions and evaluation
knn_predictions = knn.predict(X_test)
knn_report = classification_report(y_test, knn_predictions)

knn_report

KNN模型评估报告:

              precision    recall  f1-score   support

           0       0.82      0.89      0.85       105
           1       0.82      0.72      0.76        74

    accuracy                           0.82       179
   macro avg       0.82      0.80      0.81       179
weighted avg       0.82      0.82      0.81       179

这个报告显示了模型在测试集上的表现,包括精确度(precision)、召回率(recall)、F1分数和总体准确度(accuracy)。

线性回归模型训练

from sklearn.linear_model import LinearRegression

# Train the Linear Regression model
# Note: Linear regression is not typically used for classification tasks, but we'll demonstrate it here for learning purposes.
linear_reg = LinearRegression()
linear_reg.fit(X_train, y_train)

# Predictions
linear_reg_predictions = linear_reg.predict(X_test)

# Convert predictions to binary to evaluate (0 if < 0.5 else 1)
linear_reg_predictions_binary = [1 if x >= 0.5 else 0 for x in linear_reg_predictions]

# Evaluation
linear_reg_report = classification_report(y_test, linear_reg_predictions_binary)

linear_reg_report

线性回归评估报告:

              precision    recall  f1-score   support

           0       0.81      0.84      0.82       105
           1       0.76      0.72      0.74        74

    accuracy                           0.79       179
   macro avg       0.78      0.78      0.78       179
weighted avg       0.79      0.79      0.79       179

尽管线性回归通常不用于分类任务,这里我们通过将输出阈值设为0.5来将其用于二分类问题。

逻辑回归模型训练

from sklearn.linear_model import LogisticRegression

# Train the Logistic Regression model
logistic_reg = LogisticRegression(random_state=42)
logistic_reg.fit(X_train, y_train)

# Predictions
logistic_reg_predictions = logistic_reg.predict(X_test)

# Evaluation
logistic_reg_report = classification_report(y_test, logistic_reg_predictions)

logistic_reg_report

逻辑回归评估报告:

              precision    recall  f1-score   support

           0       0.82      0.86      0.84       105
           1       0.78      0.73      0.76        74

    accuracy                           0.80       179
   macro avg       0.80      0.79      0.80       179
weighted avg       0.80      0.80      0.80       179

决策树模型训练

from sklearn.tree import DecisionTreeClassifier

# Train the Decision Tree model
decision_tree = DecisionTreeClassifier(random_state=42)
decision_tree.fit(X_train, y_train)

# Predictions
decision_tree_predictions = decision_tree.predict(X_test)

# Evaluation
decision_tree_report = classification_report(y_test, decision_tree_predictions)

decision_tree_report

决策树评估报告:

              precision    recall  f1-score   support

           0       0.79      0.77      0.78       105
           1       0.69      0.72      0.70        74

    accuracy                           0.75       179
   macro avg       0.74      0.74      0.74       179
weighted avg       0.75      0.75      0.75       179

模型比较

在这项分析中,我们使用了四种不同的机器学习模型来处理同一数据集,下面是每个模型的性能总结和对比:

KNN (K-Nearest Neighbors)

  • 精确度 (Precision): 0.82 (平均)
  • 召回率 (Recall): 0.80 (平均)
  • F1 分数: 0.81 (平均)
  • 总体准确率 (Accuracy): 82%
  • 优点: 相对直观易懂,不需要假设数据分布。
  • 缺点: 对异常值敏感,计算量较大,需要调整超参数(如K值)。

线性回归 (Linear Regression)

  • 精确度: 0.78 (平均)
  • 召回率: 0.78 (平均)
  • F1 分数: 0.78 (平均)
  • 总体准确率: 79%
  • 优点: 实现简单,解释性强。
  • 缺点: 不适合用于分类任务,需要转换为分类输出,容易受到异常值的影响。

逻辑回归 (Logistic Regression)

  • 精确度: 0.80 (平均)
  • 召回率: 0.79 (平均)
  • F1 分数: 0.80 (平均)
  • 总体准确率: 80%
  • 优点: 输出可解释性强,输出值具有概率意义。
  • 缺点: 非线性问题表现一般。

决策树 (Decision Tree)

  • 精确度: 0.74 (平均)
  • 召回率: 0.74 (平均)
  • F1 分数: 0.74 (平均)
  • 总体准确率: 75%
  • 优点: 不需要数据预处理,对非线性关系处理得好,易于理解和解释。
  • 缺点: 容易过拟合,对于数据变化较敏感。

总结

  • 性能最佳: KNN 和逻辑回归在本次任务中表现最佳,具有较高的准确率和平衡的精确度与召回率。
  • 适用性: 逻辑回归提供了概率输出,更适合需要概率解释的场景。决策树在解释性和处理非线性数据方面有优势。
  • 资源消耗: KNN在大数据集上运行较慢,因为需要计算每个实例之间的距离。决策树和逻辑回归相对资源消耗较低。

很好,我们可以进一步探讨一些可能的改进方法或者根据模型性能的具体分析来提供额外的见解。

模型优化和选择

改进模型性能的策略

  1. KNN:

    • 参数调整: KNN的K值对模型的性能有重大影响。通过交叉验证来找到最佳的K值可以改进模型的精确度和召回率。
    • 距离度量: 选择不同的距离度量(如欧氏距离、曼哈顿距离)可能会对结果产生影响,特别是在特征差异性较大的数据集中。
  2. 线性回归和逻辑回归:

    • 特征工程: 引入多项式特征或交互特征可以帮助模型捕捉更复杂的关系,尤其是在逻辑回归中处理非线性边界时。
    • 正则化: 对逻辑回归使用L1或L2正则化可以帮助避免过拟合,同时选择合适的正则化强度是关键。
  3. 决策树:

    • 剪枝: 对决策树进行剪枝(限制树的深度、叶节点的最小样本数等)可以减少过拟合,提高模型的泛化能力。
    • 集成方法: 使用随机森林或梯度提升决策树(Gradient Boosting Decision Trees, GBDT)等集成方法可以显著提升决策树的性能和稳定性。

模型选择的考虑因素

  • 数据大小和特征数: 对于大规模数据集,计算密集型的模型(如KNN)可能不是最佳选择。相反,决策树和逻辑回归在大数据集上的表现通常更优。
  • 预测时间要求: 如果应用场景对预测速度有严格要求,需要考虑模型的预测效率。例如,决策树的预测速度通常非常快。
  • 模型的解释性: 在需要解释模型决策的应用中(如医疗、金融领域),决策树和逻辑回归的可解释性优势可能更为重要。

更多问题咨询

Cos机器人

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-14 06:48:10       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-14 06:48:10       100 阅读
  3. 在Django里面运行非项目文件

    2024-05-14 06:48:10       82 阅读
  4. Python语言-面向对象

    2024-05-14 06:48:10       91 阅读

热门阅读

  1. Nginx-01-聊一聊 nginx

    2024-05-14 06:48:10       37 阅读
  2. 《VS+QT》dat文件与txt文件相互转换

    2024-05-14 06:48:10       29 阅读
  3. docker部署调度程序

    2024-05-14 06:48:10       35 阅读
  4. http和https的区别

    2024-05-14 06:48:10       30 阅读
  5. 2024/5/13 SpringBoot配置多个RabbitMQ

    2024-05-14 06:48:10       20 阅读