一、模型訓練
本案例中,我們將通過四種不同的模型來預測泰坦尼克號乘客的生存情況。
一下是訓練的具體步驟。
加載數據
從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())
ResultPassengerId 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'])
: 應用編碼器,將male
和female
分別轉換為數值(例如 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 support0 0.82 0.89 0.85 1051 0.82 0.72 0.76 74accuracy 0.82 179macro 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 support0 0.81 0.84 0.82 1051 0.76 0.72 0.74 74accuracy 0.79 179macro 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 support0 0.82 0.86 0.84 1051 0.78 0.73 0.76 74accuracy 0.80 179macro 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 support0 0.79 0.77 0.78 1051 0.69 0.72 0.70 74accuracy 0.75 179macro 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在大數據集上運行較慢,因為需要計算每個實例之間的距離。決策樹和邏輯回歸相對資源消耗較低。
很好,我們可以進一步探討一些可能的改進方法或者根據模型性能的具體分析來提供額外的見解。
模型優化和選擇
改進模型性能的策略
-
KNN:
- 參數調整: KNN的K值對模型的性能有重大影響。通過交叉驗證來找到最佳的K值可以改進模型的精確度和召回率。
- 距離度量: 選擇不同的距離度量(如歐氏距離、曼哈頓距離)可能會對結果產生影響,特別是在特征差異性較大的數據集中。
-
線性回歸和邏輯回歸:
- 特征工程: 引入多項式特征或交互特征可以幫助模型捕捉更復雜的關系,尤其是在邏輯回歸中處理非線性邊界時。
- 正則化: 對邏輯回歸使用L1或L2正則化可以幫助避免過擬合,同時選擇合適的正則化強度是關鍵。
-
決策樹:
- 剪枝: 對決策樹進行剪枝(限制樹的深度、葉節點的最小樣本數等)可以減少過擬合,提高模型的泛化能力。
- 集成方法: 使用隨機森林或梯度提升決策樹(Gradient Boosting Decision Trees, GBDT)等集成方法可以顯著提升決策樹的性能和穩定性。
模型選擇的考慮因素
- 數據大小和特征數: 對于大規模數據集,計算密集型的模型(如KNN)可能不是最佳選擇。相反,決策樹和邏輯回歸在大數據集上的表現通常更優。
- 預測時間要求: 如果應用場景對預測速度有嚴格要求,需要考慮模型的預測效率。例如,決策樹的預測速度通常非常快。
- 模型的解釋性: 在需要解釋模型決策的應用中(如醫療、金融領域),決策樹和邏輯回歸的可解釋性優勢可能更為重要。