titanic数据集_TF2.0结构化数据建模流程范例
盡管TensorFlow設(shè)計(jì)上足夠靈活,可以用于進(jìn)行各種復(fù)雜的數(shù)值計(jì)算。但通常人們使用TensorFlow來(lái)實(shí)現(xiàn)機(jī)器學(xué)習(xí)模型,尤其常用于實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)模型。
從原理上說(shuō)可以使用張量構(gòu)建計(jì)算圖來(lái)定義神經(jīng)網(wǎng)絡(luò),并通過(guò)自動(dòng)微分機(jī)制訓(xùn)練模型。但為簡(jiǎn)潔起見(jiàn),一般推薦使用TensorFlow的高層次keras接口來(lái)實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)網(wǎng)模型。
使用TensorFlow實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)模型的一般流程包括:
1,準(zhǔn)備數(shù)據(jù)
2,定義模型
3,訓(xùn)練模型
4,評(píng)估模型
5,使用模型
6,保存模型。
對(duì)新手來(lái)說(shuō),其中最困難的部分實(shí)際上是準(zhǔn)備數(shù)據(jù)過(guò)程。
我們?cè)趯?shí)踐中通常會(huì)遇到的數(shù)據(jù)類(lèi)型包括結(jié)構(gòu)化數(shù)據(jù),圖片數(shù)據(jù),文本數(shù)據(jù)。
我們將分別以titanic生存預(yù)測(cè)問(wèn)題,cifar2圖片分類(lèi)問(wèn)題,imdb電影評(píng)論分類(lèi)問(wèn)題為例,演示應(yīng)用tensorflow對(duì)這三類(lèi)數(shù)據(jù)的建模方法。
本篇以titanic生存預(yù)測(cè)問(wèn)題為例,演示應(yīng)用tensorflow對(duì)結(jié)構(gòu)化數(shù)據(jù)進(jìn)行建模的方法。
一,準(zhǔn)備數(shù)據(jù)
titanic數(shù)據(jù)集的目標(biāo)是根據(jù)乘客信息預(yù)測(cè)他們?cè)赥itanic號(hào)撞擊冰山沉沒(méi)后能否生存。
結(jié)構(gòu)化數(shù)據(jù)一般會(huì)使用Pandas中的DataFrame進(jìn)行預(yù)處理。
import?numpy?as?np?import?pandas?as?pd?
import?matplotlib.pyplot?as?plt
import?tensorflow?as?tf?
from?tensorflow.keras?import?models,layers
dftrain_raw?=?pd.read_csv('./data/titanic/train.csv')
dftest_raw?=?pd.read_csv('./data/titanic/test.csv')
dftrain_raw.head(10)
字段說(shuō)明:
Survived:0代表死亡,1代表存活【y標(biāo)簽】
Pclass:乘客所持票類(lèi),有三種值(1,2,3) 【轉(zhuǎn)換成onehot編碼】
Name:乘客姓名 【舍去】
Sex:乘客性別 【轉(zhuǎn)換成bool特征】
Age:乘客年齡(有缺失) 【數(shù)值特征,添加“年齡是否缺失”作為輔助特征】
SibSp:乘客兄弟姐妹/配偶的個(gè)數(shù)(整數(shù)值) 【數(shù)值特征】
Parch:乘客父母/孩子的個(gè)數(shù)(整數(shù)值)【數(shù)值特征】
Ticket:票號(hào)(字符串)【舍去】
Fare:乘客所持票的價(jià)格(浮點(diǎn)數(shù),0-500不等) 【數(shù)值特征】
Cabin:乘客所在船艙(有缺失) 【添加“所在船艙是否缺失”作為輔助特征】
Embarked:乘客登船港口:S、C、Q(有缺失)【轉(zhuǎn)換成onehot編碼,四維度 S,C,Q,nan】
利用Pandas的數(shù)據(jù)可視化功能我們可以簡(jiǎn)單地進(jìn)行探索性數(shù)據(jù)分析EDA(Exploratory Data Analysis)。
label分布情況
%matplotlib?inline%config?InlineBackend.figure_format?=?'png'
ax?=?dftrain_raw['Survived'].value_counts().plot(kind?=?'bar',
?????figsize?=?(12,8),fontsize=15,rot?=?0)
ax.set_ylabel('Counts',fontsize?=?15)
ax.set_xlabel('Survived',fontsize?=?15)
plt.show()
年齡分布情況
%matplotlib?inline%config?InlineBackend.figure_format?=?'png'
ax?=?dftrain_raw['Age'].plot(kind?=?'hist',bins?=?20,color=?'purple',
????????????????????figsize?=?(12,8),fontsize=15)
ax.set_ylabel('Frequency',fontsize?=?15)
ax.set_xlabel('Age',fontsize?=?15)
plt.show()
年齡和label的相關(guān)性
%matplotlib?inline%config?InlineBackend.figure_format?=?'png'
ax?=?dftrain_raw.query('Survived?==?0')['Age'].plot(kind?=?'density',
??????????????????????figsize?=?(12,8),fontsize=15)
dftrain_raw.query('Survived?==?1')['Age'].plot(kind?=?'density',
??????????????????????figsize?=?(12,8),fontsize=15)
ax.legend(['Survived==0','Survived==1'],fontsize?=?12)
ax.set_ylabel('Density',fontsize?=?15)
ax.set_xlabel('Age',fontsize?=?15)
plt.show()
下面為正式的數(shù)據(jù)預(yù)處理
def?preprocessing(dfdata):????dfresult=?pd.DataFrame()
????#Pclass
????dfPclass?=?pd.get_dummies(dfdata['Pclass'])
????dfPclass.columns?=?['Pclass_'?+str(x)?for?x?in?dfPclass.columns?]
????dfresult?=?pd.concat([dfresult,dfPclass],axis?=?1)
????#Sex
????dfSex?=?pd.get_dummies(dfdata['Sex'])
????dfresult?=?pd.concat([dfresult,dfSex],axis?=?1)
????#Age
????dfresult['Age']?=?dfdata['Age'].fillna(0)
????dfresult['Age_null']?=?pd.isna(dfdata['Age']).astype('int32')
????#SibSp,Parch,Fare
????dfresult['SibSp']?=?dfdata['SibSp']
????dfresult['Parch']?=?dfdata['Parch']
????dfresult['Fare']?=?dfdata['Fare']
????#Carbin
????dfresult['Cabin_null']?=??pd.isna(dfdata['Cabin']).astype('int32')
????#Embarked
????dfEmbarked?=?pd.get_dummies(dfdata['Embarked'],dummy_na=True)
????dfEmbarked.columns?=?['Embarked_'?+?str(x)?for?x?in?dfEmbarked.columns]
????dfresult?=?pd.concat([dfresult,dfEmbarked],axis?=?1)
????return(dfresult)
x_train?=?preprocessing(dftrain_raw)
y_train?=?dftrain_raw['Survived'].values
x_test?=?preprocessing(dftest_raw)
y_test?=?dftest_raw['Survived'].values
print("x_train.shape?=",?x_train.shape?)
print("x_test.shape?=",?x_test.shape?)
二,定義模型
使用Keras接口有以下3種方式構(gòu)建模型:使用Sequential按層順序構(gòu)建模型,使用函數(shù)式API構(gòu)建任意結(jié)構(gòu)模型,繼承Model基類(lèi)構(gòu)建自定義模型。
此處選擇使用最簡(jiǎn)單的Sequential,按層順序模型。
tf.keras.backend.clear_session()model?=?models.Sequential()
model.add(layers.Dense(20,activation?=?'relu',input_shape=(15,)))
model.add(layers.Dense(10,activation?=?'relu'?))
model.add(layers.Dense(1,activation?=?'sigmoid'?))
model.summary()
三,訓(xùn)練模型
訓(xùn)練模型通常有3種方法,內(nèi)置fit方法,內(nèi)置train_on_batch方法,以及自定義訓(xùn)練循環(huán)。此處我們選擇最常用也最簡(jiǎn)單的內(nèi)置fit方法。
#?二分類(lèi)問(wèn)題選擇二元交叉熵?fù)p失函數(shù)model.compile(optimizer='adam',
????????????loss='binary_crossentropy',
????????????metrics=['AUC'])
history?=?model.fit(x_train,y_train,
????????????????????batch_size=?64,
????????????????????epochs=?30,
????????????????????validation_split=0.2?#分割一部分訓(xùn)練數(shù)據(jù)用于驗(yàn)證
???????????????????)
四,評(píng)估模型
我們首先評(píng)估一下模型在訓(xùn)練集和驗(yàn)證集上的效果。
%matplotlib?inline%config?InlineBackend.figure_format?=?'svg'
import?matplotlib.pyplot?as?plt
def?plot_metric(history,?metric):
????train_metrics?=?history.history[metric]
????val_metrics?=?history.history['val_'+metric]
????epochs?=?range(1,?len(train_metrics)?+?1)
????plt.plot(epochs,?train_metrics,?'bo--')
????plt.plot(epochs,?val_metrics,?'ro-')
????plt.title('Training?and?validation?'+?metric)
????plt.xlabel("Epochs")
????plt.ylabel(metric)
????plt.legend(["train_"+metric,?'val_'+metric])
????plt.show()
我們?cè)倏匆幌履P驮跍y(cè)試集上的效果.
五,使用模型
六,保存模型
可以使用Keras方式保存模型,也可以使用TensorFlow原生方式保存。前者僅僅適合使用Python環(huán)境恢復(fù)模型,后者則可以跨平臺(tái)進(jìn)行模型部署。
推薦使用后一種方式進(jìn)行保存。
1,Keras方式保存
2,TensorFlow原生方式保存
總結(jié)
以上是生活随笔為你收集整理的titanic数据集_TF2.0结构化数据建模流程范例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 购买二手房的购房发票在哪里
- 下一篇: aes key长度_Go 语言 map