使用 Python 進行機器學習的宇宙飛船泰坦尼克號專案


機器學習中最初的泰坦尼克號專案旨在確定泰坦尼克號上的人是否會倖存下來。但是,這個名為宇宙飛船泰坦尼克號的專案略有不同。

這裡的問題陳述是,一艘宇宙飛船載著人們進行太空旅行。但由於發生碰撞,一些人需要被運送到另一個維度或星球。現在這不能隨機進行。因此,我們將使用 Python 中的機器學習技術來找出誰將被運送,誰將不被運送。

演算法

步驟 1 − 匯入 numpy、pandas、matplotlib、seaborn 和 sklearn 等庫,並將資料集載入為 pandas 資料框。

步驟 2  為了清理資料,首先繪製條形圖以檢查空值。如果發現空值,則查詢各個特徵之間的關係並填充空值。在填充值之前檢查異常值,如果需要。

步驟 3  再次檢查空值。這次,使用樸素值填充所有空值。在此步驟中,您應該獲得 0 作為輸出,這意味著所有空值都已處理。

步驟 4  提取、減少、合併或新增特徵以匯出重要且最顯著的資訊。這是透過重複比較和相關操作完成的。

步驟 5  為了找出進一步的關係,使用 EDA 或探索性資料分析,我們利用視覺化工具來檢視不同特徵之間的關係。我們將製作餅圖、條形圖和熱圖,以檢視是否存在任何高度相關的特徵。

步驟 6  將資料集拆分為測試集和訓練集,並使用 StandardScaler 對資料進行標準化。

步驟 7  現在在這個資料上訓練一些機器學習模型,並檢查哪個模型最合適。我們正在使用邏輯迴歸、XGBClassifier 和 SVC。

步驟 8  選擇效能最佳的模型。

步驟 9  使用所選模型列印混淆矩陣和驗證資料。

示例

在這個例子中,我們將使用一個宇宙飛船泰坦尼克號資料集,您可以在此處找到它,然後,我們將執行預測一個人是否將從宇宙飛船運送到不同的星球或維度所需的各種步驟。請注意,我們沒有采用所有行,因為它是一個巨大的資料集,但您可以根據需要採用任意多行。

#part 1
#--------------------------------------------------------------------
#setting up libraries and dataset

#Import the required libraries 
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
import sklearn  
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn import metrics
from sklearn.svm import SVC
from xgboost import XGBClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.metrics import confusion_matrix  
import warnings
warnings.filterwarnings('ignore')

#load and print the dataset
df = pd.read_csv('titanic_dataset.csv')
df.head()

#print other information about the dataset 
df.shape
df.info()
df.describe()

#part 2
#--------------------------------------------------------------------
#preprocessing the data

#find the null values 
df.isnull().sum().plot.bar()
plt.show()

#substitute the null values as needed 
col = df.loc[:,'RoomService':'VRDeck'].columns
df.groupby('VIP')[col].mean()
df.groupby('CryoSleep')[col].mean()
temp = df['CryoSleep'] == True
df.loc[temp, col] = 0.0
for c in col:
    for val in [True, False]:
        temp = df['VIP'] == val
        k = df[temp].mean()
        df.loc[temp, c] = df.loc[temp, c].fillna(k)

#check relationship bw VIP and HomePlanet feature
sb.countplot(data=df, x='VIP',
             hue='HomePlanet')
plt.show()

col = 'HomePlanet'
temp = df['VIP'] == False
df.loc[temp, col] = df.loc[temp, col].fillna('Earth')
  
temp = df['VIP'] == True
df.loc[temp, col] = df.loc[temp, col].fillna('Europa')

#check for outliers
sb.boxplot(df['Age'])
plt.show()

#exclude outliers while substituting null values 
temp = df[df['Age'] < 61]['Age'].mean()
df['Age'] = df['Age'].fillna(temp)

#check relationship between Transported and CryoSleep 
sb.countplot(data=df,
             x='Transported',
             hue='CryoSleep')
plt.show()

#check for the null values again 
df.isnull().sum().plot.bar()
plt.show()

#fill them all with the naive method 
for col in df.columns:
    if df[col].isnull().sum() == 0:
        continue
          
    if df[col].dtype == object or df[col].dtype == bool:
        df[col] = df[col].fillna(df[col].mode()[0])
          
    else:
        df[col] = df[col].fillna(df[col].mean())

#this should return 0, meaning no null values are left 
df.isnull().sum().sum()

#part 3
#--------------------------------------------------------------------
#feature engineering

#passenger id and room no represent the same kind of information
new = df["PassengerId"].str.split("_", n=1, expand=True)
df["RoomNo"] = new[0].astype(int)
df["PassengerNo"] = new[1].astype(int)
  
df.drop(['PassengerId', 'Name'],
        axis=1, inplace=True)

#filling room no with max passengers 
data = df['RoomNo']
for i in range(df.shape[0]):
      temp = data == data[i]
      df['PassengerNo'][i] = (temp).sum()

#removing roomno 
df.drop(['RoomNo'], axis=1,
        inplace=True)
  
sb.countplot(data=df,
             x = 'PassengerNo',
             hue='VIP')
plt.show()

#not much relation in VIP sharing a room 
new = df["Cabin"].str.split("/", n=2, expand=True)
data["F1"] = new[0]
df["F2"] = new[1].astype(int)
df["F3"] = new[2]
  
df.drop(['Cabin'], axis=1,
        inplace=True)

#combining all expenses 
df['LeasureBill'] = df['RoomService'] + df['FoodCourt']\
 + df['ShoppingMall'] + df['Spa'] + df['VRDeck']

#part 4
#--------------------------------------------------------------------
#EDA

#checking if the data is balanced 
x = df['Transported'].value_counts()
plt.pie(x.values,
        labels=x.index,
        autopct='%1.1f%%')
plt.show()

#relation bw VIP and leasureBill
df.groupby('VIP').mean()['LeasureBill'].plot.bar()
plt.show()

#encoding and binary conversion 
for col in df.columns:
     
    if df[col].dtype == object:
        le = LabelEncoder()
        df[col] = le.fit_transform(df[col])
  
   
    if df[col].dtype == 'bool':
        df[col] = df[col].astype(int)
  
df.head()

#checking correlated features with a heatmap
plt.figure(figsize=(10,10))
sb.heatmap(df.corr()>0.8,
           annot=True,
           cbar=False)
plt.show()

#part 5
#--------------------------------------------------------------------
#model training 

#split the data
features = df.drop(['Transported'], axis=1)
target = df.Transported
  
X_train, X_val,\
    Y_train, Y_val = train_test_split(features, target,
                                      test_size=0.1,
                                      random_state=22)
  
X_train.shape, X_val.shape

#normalize the data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)

#check fitting with various ML models 
from sklearn.metrics import roc_auc_score as ras
models = [LogisticRegression(), XGBClassifier(),
          SVC(kernel='rbf', probability=True)]
  
for i in range(len(models)):
    models[i].fit(X_train, Y_train)
  
    print(f'{models[i]} : ')
  
    train_preds = models[i].predict_proba(X_train)[:, 1]
    print('Training Accuracy : ', ras(Y_train, train_preds))
  
    val_preds = models[i].predict_proba(X_val)[:, 1]
    print('Validation Accuracy : ', ras(Y_val, val_preds))
    print()
    
#part 6
#--------------------------------------------------------------------
#model evaluation 

#plot confusion matrix using the best model 
y_pred = models[1].predict(X_val)
cm = confusion_matrix(Y_val, y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
disp.plot()
plt.show()

print(metrics.classification_report
      (Y_val, models[1].predict(X_val)))

一旦所有庫都匯入,資料集就會載入到一個數據框中,其中資料集被處理以處理缺失值和異常值。隨後,識別資料集中空值,並建立條形圖以視覺化每列中空值的計數,並繪製傳輸和冷凍睡眠之間的關係。

PassengerId 列被拆分為兩列:RoomNo 和 PassengerNo,然後將這些列中的值轉換為整數。目標變數 Transported 的平衡作為餅圖繪製,VIP 和 LeasureBill 之間的關係也作為條形圖顯示。

在後面的部分,對資料集執行標籤編碼和二進位制轉換,以將分類列轉換為數值。然後,建立一個熱圖以視覺化資料集中特徵之間的關係。

然後,每個模型都在訓練集上進行訓練,並使用 roc_auc_score 變數評估驗證準確性。之後,繪製混淆矩陣以及分類報告(包括精確度)、F1 分數和報告,使用模型列印。

輸出

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 254 entries, 0 to 253
Data columns (total 14 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   PassengerId   254 non-null    object 
 1   HomePlanet    249 non-null    object 
 2   CryoSleep     247 non-null    object 
 3   Cabin         248 non-null    object 
 4   Destination   251 non-null    object 
 5   Age           248 non-null    float64
 6   VIP           250 non-null    object 
 7   RoomService   247 non-null    float64
 8   FoodCourt     252 non-null    float64
 9   ShoppingMall  242 non-null    float64
 10  Spa           251 non-null    float64
 11  VRDeck        250 non-null    float64
 12  Name          247 non-null    object 
 13  Transported   254 non-null    bool   
dtypes: bool(1), float64(6), object(7)
memory usage: 26.2+ KB

LogisticRegression() 

Training Accuracy :  0.8922982036851439
Validation Accuracy :  0.8060606060606061

XGBClassifier() 

Training Accuracy :  1.0
Validation Accuracy :  0.7454545454545454

SVC(probability=True) 

Training Accuracy :  0.9266825996453628
Validation Accuracy :  0.7878787878787878

使用效能矩陣,您可以得出結論,該模型能夠輕鬆地將正值預測為正值,但負值並非如此。

結論

為了完成這個宇宙飛船泰坦尼克號專案,您還可以使用其他模型,如 K 最近鄰 (KNN)、支援向量機 (SVM)、隨機森林 (RF) 和樸素貝葉斯等。此外,我們在這裡自己預處理了資料。但是,您可以使用網際網路上提供的其他已預處理的資料集。這將為我們節省許多步驟,並使我們的任務更容易。

更新於: 2023-07-21

274 次檢視

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告