Tensorflow2.0學習(四) — Keras基礎應用(泰坦尼克生存率預測)

前幾節分享的內容都是基於圖片數據進行了簡單的分類工作,這節內容將應用keras對泰坦尼克旅客的文本數據進行預測,主要是做一個二分類的工作,根據官方提供的數據中的各項特徵預測每個旅客生存的概率是多少。

一.Titanic3數據集的下載

1.導入相關使用到的庫。這裏的urllib庫的作用主要是用於下載數據,os庫用於判斷文件是否存在,sklearn的preprocessing用於對文本數據進行預處理。

import os
import urllib.request
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import layers
from sklearn import preprocessing
import matplotlib.pyplot as plt

2.下載數據集。

#下載的網頁路徑
url='http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.xls'
filepath="titanic3.xls" #文件路徑
if not os.path.isfile(filepath):
    result = urllib.request.urlretrieve(url,filepath) #該函數可以將遠程數據下載到本地
    print(result)

3.使用pandas讀取文件,並顯示查看。

all_df = pd.read_excel(filepath)

4.數據集特徵名字的解釋。survival:是否生存,pclass:艙級別,如一等二等艙等,name:名字,sex:性別,age:年齡,sibsp:手足或配偶也在船上的數量,parch:雙親或子女也在船上的數量,fare:旅客費用,embarked:登船港口地點。

二.Titanic3數據集的預處理

1.選取有用的特徵信息。數據集的特徵不一定都有用,冗餘的特徵對於分析幫助不大且會增加訓練參數量,因此我們第一步根據需求選取指定特徵。

cols = ['survived','name','pclass','sex','age','sibsp','parch','fare','embarked']
all_df=all_df[cols]

2.數據集中有很多特徵值爲空值NULL,這種數據信息缺失的情況在絕大多數數據集中都可能會存在,因此我們需要填補上這些空缺的信息。我們可以用下面這個函數進行查看缺失數據的特徵對象和數量。

all_df.isnull().sum()

3.接下來這一步,我直接包裝了一個函數方便使用。首先我們去除名字信息,名字在訓練中沒有用到,但在預測時需要使用。另外在知道了缺失的特徵之後我們需要補充其它值上去,很多人會補充0,但比如在年齡、費用這些特徵上,0值是不符合實際情況的,比較合理的一個補充方式是補充它們的平均值上去。然後接着我們會發現性別特徵和embarked特徵上的值是字母地點,由於深度學習模型只能處理數字信息,因此我們先要用map函數將性別值映射爲數字1和0,接着對embarked這個特徵進行One-Hot編碼將其轉爲數字。其次我們要將pandas的DataFrame格式轉爲數值矩陣以便神經網絡可以訓練。最後我們提取出數據中的特徵和標籤並用preprocessing對所有值進行標準化。

流程:去除名字信息->用平均值補充缺失值->map將性別映射爲數字->對embarked特徵進行One-Hot編碼->DataFrame轉數值矩陣->所有特徵標準化。

def Processing_Data(raw_df):
    df = raw_df.drop(['name'],axis=1)  #去除名字特徵
    age_mean = df['age'].mean() #求年齡平均值
    df['age'] = df['age'].fillna(age_mean) #用fillna填充缺失值
    fare_mean = df['fare'].mean() #求費用平均值
    df['fare'] = df['fare'].fillna(fare_mean) #填充缺失值
    df['sex'] = df['sex'].map({'female':0,'male':1}).astype(int) #map映射性別爲數字
    X_Onehot_df = pd.get_dummies(data=df,columns=['embarked']) #One-Hot編碼embarked特徵
    ndarray = X_Onehot_df.values #轉爲array
    Features = ndarray[:,1:] #提取特徵
    Labels = ndarray[:,0] #提取標籤
    minmax_scale = preprocessing.MinMaxScaler(feature_range=(0,1)) 
    scaledFeature = minmax_scale.fit_transform(Features) #所有特徵標準化
    
    return scaledFeature,Labels

顯示前五行預處理後的特徵的數值。

feature,label = Processing_Data(all_df)
print(feature[:5])

4.按8:2的比例隨機將數據集分割訓練集和測試集。

msk = np.random.rand(len(all_df))<0.8 #使用numpy生成正態分佈的點,並取80%
train_df = all_df[msk]
test_df = all_df[~msk]
train_Features,train_Label = Processing_Data(train_df)
test_Featuress,test_Label = Processing_Data(test_df)
print(train_Features.shape)
print(test_Featuress.shape)

三.模型搭建

1.構建Sequential線性堆疊模型。

model = tf.keras.models.Sequential()

2.疊加相關層。

model.add(layers.Dense(units=30,input_dim=9,activation='relu',kernel_initializer='uniform'))
model.add(layers.Dense(units=20,kernel_initializer='uniform',activation='relu'))
model.add(layers.Dense(units=1,kernel_initializer='uniform',activation='sigmoid'))

四.模型訓練

1.模型設置及訓練。因爲最後判別的結果是0(死)或1(生),因此這裏要使用二值損失函數。

model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
train_history = model.fit(x=train_Features,y=train_Label,validation_split=0.2,epochs=100,batch_size=30,verbose=1)

 

2.定義曲線顯示函數並顯示。

def show_train_history(train_history,train,validation):
    plt.plot(train_history.history[train])
    plt.plot(train_history.history[validation])
    plt.title('Train History')
    plt.xlabel('epoch')
    plt.ylabel(train)
    plt.legend(['train','validation'],loc='upper left')

show_train_history(train_history,'accuracy','val_accuracy')

 

五.模型測試及預測

1.模型測試。

scores = model.evaluate(x=test_Featuress,y=test_Label,verbose=2)
print(scores[1])

 

2.模型預測。

這裏我們根據指定信息人爲的生成兩個數據點Jack和Rose進行測試,也就是大家熟知的電影男女主角。

Jack = pd.Series([0,'Jack','3','male',23,1,0,5,'S'])
Rose = pd.Series([1,'Rose','1','female',23,1,0,5,'S'])
JR_df = pd.DataFrame([list(Jack),list(Rose)],columns=['survived','name','pclass','sex','age','sibsp','parch','fare','embarked'])

將生成數據放到原數據中,並重新對數據進行標準化處理。

all_df = pd.concat([all_df,JR_df])
all_Features,Label = Processing_Data(all_df)

最後對模型進行預測,顯示最後兩個點也就是Jack和Rose的生存概率。從值中我們可以看到,Rose生存率遠大於Jack,符合電影最後結局。

all_Features,Label = Processing_Data(all_df)
all_probabiblity = model.predict(all_Features)
all_probabiblity[-2:]

 

以上是這一節的所有內容的分享,謝謝大家的觀看。如有不足或有疑問的地方可以一起探討,謝謝。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章