TensorFlow2.0 Keras泰坦尼克数据集预测

import urllib.request
import os

url = 'http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.xls'
filepath = './data/titanic3.xls'
if not os.path.isfile(filepath):
    result = urllib.request.urlretrieve(url, filepath)
    print('downloaded:', result)
downloaded: ('./data/titanic3.xls', <http.client.HTTPMessage object at 0x00000214763EAEB8>)
import numpy as np
import pandas as pd

all_df = pd.read_excel('./data/titanic3.xls')
cols = [
    'survived', 'name', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'fare',
    'embarked'
]
all_df = all_df[cols]
all_df[:2]
survivednamepclasssexagesibspparchfareembarked
01Allen, Miss. Elisabeth Walton1female29.000000211.3375S
11Allison, Master. Hudson Trevor1male0.916712151.5500S
df = all_df.drop(['name'], axis=1)
all_df.isnull().sum()
survived      0
name          0
pclass        0
sex           0
age         263
sibsp         0
parch         0
fare          1
embarked      2
dtype: int64
age_mean = df['age'].mean()
df['age'] = df['age'].fillna(age_mean)
fare_mean = df['fare'].mean()
df['fare'] = df['fare'].fillna(fare_mean)
df['sex'] = df['sex'].map({'female':0, 'male': 1}).astype(int)
x_Onehot_df = pd.get_dummies(data=df, columns=['embarked'])
x_Onehot_df[:2]
survivedpclasssexagesibspparchfareembarked_Cembarked_Qembarked_S
011029.000000211.3375001
11110.916712151.5500001
ndarray = x_Onehot_df.values
ndarray.shape
(1309, 10)
ndarray[:2]
array([[  1.    ,   1.    ,   0.    ,  29.    ,   0.    ,   0.    ,
        211.3375,   0.    ,   0.    ,   1.    ],
       [  1.    ,   1.    ,   1.    ,   0.9167,   1.    ,   2.    ,
        151.55  ,   0.    ,   0.    ,   1.    ]])
Label = ndarray[:,0]
Features = ndarray[:, 1:]
Label[:2]
array([1., 1.])
Features[:2]
array([[  1.    ,   0.    ,  29.    ,   0.    ,   0.    , 211.3375,
          0.    ,   0.    ,   1.    ],
       [  1.    ,   1.    ,   0.9167,   1.    ,   2.    , 151.55  ,
          0.    ,   0.    ,   1.    ]])
from sklearn import preprocessing
minmax_Scale = preprocessing.MinMaxScaler(feature_range=(0, 1))
scaledFeatures = minmax_Scale.fit_transform(Features)
scaledFeatures[:2]
array([[0.        , 0.        , 0.36116884, 0.        , 0.        ,
        0.41250333, 0.        , 0.        , 1.        ],
       [0.        , 1.        , 0.00939458, 0.125     , 0.22222222,
        0.2958059 , 0.        , 0.        , 1.        ]])
msk = np.random.rand(len(all_df)) < 0.8
train_df = all_df[msk]
test_df = all_df[~msk]
print('total:', len(all_df), 'train:', len(train_df), 'test:', len(test_df))
total: 1309 train: 1071 test: 238
def PreprocessData(raw_df):
    df = raw_df.drop(['name'], axis=1)
    age_mean = df['age'].mean()
    df['age'] = df['age'].fillna(age_mean)
    fare_mean = df['fare'].mean()
    df['fare'] = df['fare'].fillna(age_mean)
    df['sex'] = df['sex'].map({'female': 0, 'male': 1}).astype(int)
    x_Onehot_df = pd.get_dummies(data=df, columns=['embarked'])
    
    ndarray = x_Onehot_df.values
    Features = ndarray[:, 1:]
    Label = ndarray[:, 0]
    
    minmax_scale = preprocessing.MinMaxScaler(feature_range=(0, 1))
    scaledFeatures = minmax_scale.fit_transform(Features)
    
    return scaledFeatures, Label
train_Features, train_Label = PreprocessData(train_df)
test_Features, test_Label = PreprocessData(test_df)
train_Features[:2]
array([[0.        , 0.        , 0.0229641 , 0.125     , 0.22222222,
        0.2958059 , 0.        , 0.        , 1.        ],
       [0.        , 1.        , 0.37369494, 0.125     , 0.22222222,
        0.2958059 , 0.        , 0.        , 1.        ]])
test_Label[:2]
array([1., 1.])
# 建立模型
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
model = Sequential()
model.add(
    Dense(units=40,
          input_dim=9,
          kernel_initializer='uniform',
          activation='relu'))

model.add(Dense(units=30, kernel_initializer='uniform', activation='relu'))
model.add(Dense(units=1,kernel_initializer='uniform', activation='sigmoid'))
model.compile(loss='binary_crossentropy',
             optimizer='adam',
             metrics=['accuracy'])
W0819 11:23:43.940761  6100 deprecation_wrapper.py:119] From E:\Anaconda3\envs\ml\lib\site-packages\keras\optimizers.py:790: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.

W0819 11:23:43.970712  6100 deprecation_wrapper.py:119] From E:\Anaconda3\envs\ml\lib\site-packages\keras\backend\tensorflow_backend.py:3376: The name tf.log is deprecated. Please use tf.math.log instead.

W0819 11:23:43.976665  6100 deprecation.py:323] From E:\Anaconda3\envs\ml\lib\site-packages\tensorflow\python\ops\nn_impl.py:180: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
train_history = model.fit(x=train_Features,
                          y=train_Label,
                          validation_split=0.1,
                          batch_size=30,
                          epochs=30,
                          verbose=2)
Train on 963 samples, validate on 108 samples
Epoch 1/30
 - 0s - loss: 0.6645 - acc: 0.6023 - val_loss: 0.5840 - val_acc: 0.7685
Epoch 2/30
 - 0s - loss: 0.6062 - acc: 0.6594 - val_loss: 0.4936 - val_acc: 0.7870
Epoch 3/30
 - 0s - loss: 0.5513 - acc: 0.7487 - val_loss: 0.4564 - val_acc: 0.7870
Epoch 4/30
 - 0s - loss: 0.5151 - acc: 0.7747 - val_loss: 0.4487 - val_acc: 0.8056
Epoch 5/30
 - 0s - loss: 0.4968 - acc: 0.7757 - val_loss: 0.4538 - val_acc: 0.8056
Epoch 6/30
 - 0s - loss: 0.4882 - acc: 0.7736 - val_loss: 0.4354 - val_acc: 0.8056
Epoch 7/30
 - 0s - loss: 0.4839 - acc: 0.7695 - val_loss: 0.4277 - val_acc: 0.8148
Epoch 8/30
 - 0s - loss: 0.4818 - acc: 0.7788 - val_loss: 0.4254 - val_acc: 0.8148
Epoch 9/30
 - 0s - loss: 0.4796 - acc: 0.7840 - val_loss: 0.4231 - val_acc: 0.8333
Epoch 10/30
 - 0s - loss: 0.4766 - acc: 0.7819 - val_loss: 0.4247 - val_acc: 0.8148
Epoch 11/30
 - 0s - loss: 0.4733 - acc: 0.7830 - val_loss: 0.4240 - val_acc: 0.8148
Epoch 12/30
 - 0s - loss: 0.4714 - acc: 0.7840 - val_loss: 0.4174 - val_acc: 0.8333
Epoch 13/30
 - 0s - loss: 0.4684 - acc: 0.7871 - val_loss: 0.4181 - val_acc: 0.8426
Epoch 14/30
 - 0s - loss: 0.4666 - acc: 0.7871 - val_loss: 0.4169 - val_acc: 0.8426
Epoch 15/30
 - 0s - loss: 0.4643 - acc: 0.7892 - val_loss: 0.4151 - val_acc: 0.8519
Epoch 16/30
 - 0s - loss: 0.4632 - acc: 0.7892 - val_loss: 0.4134 - val_acc: 0.8426
Epoch 17/30
 - 0s - loss: 0.4618 - acc: 0.7902 - val_loss: 0.4133 - val_acc: 0.8426
Epoch 18/30
 - 0s - loss: 0.4618 - acc: 0.7913 - val_loss: 0.4145 - val_acc: 0.8056
Epoch 19/30
 - 0s - loss: 0.4606 - acc: 0.7944 - val_loss: 0.4160 - val_acc: 0.8426
Epoch 20/30
 - 0s - loss: 0.4606 - acc: 0.7934 - val_loss: 0.4155 - val_acc: 0.8148
Epoch 21/30
 - 0s - loss: 0.4588 - acc: 0.7944 - val_loss: 0.4124 - val_acc: 0.8426
Epoch 22/30
 - 0s - loss: 0.4568 - acc: 0.7954 - val_loss: 0.4136 - val_acc: 0.8426
Epoch 23/30
 - 0s - loss: 0.4571 - acc: 0.7985 - val_loss: 0.4152 - val_acc: 0.8333
Epoch 24/30
 - 0s - loss: 0.4585 - acc: 0.7923 - val_loss: 0.4190 - val_acc: 0.8056
Epoch 25/30
 - 0s - loss: 0.4577 - acc: 0.7923 - val_loss: 0.4162 - val_acc: 0.8426
Epoch 26/30
 - 0s - loss: 0.4610 - acc: 0.7882 - val_loss: 0.4192 - val_acc: 0.8426
Epoch 27/30
 - 0s - loss: 0.4553 - acc: 0.8006 - val_loss: 0.4156 - val_acc: 0.8333
Epoch 28/30
 - 0s - loss: 0.4580 - acc: 0.7902 - val_loss: 0.4186 - val_acc: 0.7963
Epoch 29/30
 - 0s - loss: 0.4590 - acc: 0.7975 - val_loss: 0.4145 - val_acc: 0.8426
Epoch 30/30
 - 0s - loss: 0.4550 - acc: 0.7934 - val_loss: 0.4165 - val_acc: 0.8241
scores = model.evaluate(x=test_Features, y= test_Label)
238/238 [==============================] - 0s 21us/step
scores[1]
0.8025210089042407
Jack = pd.Series([0, 'Jack', 3, 'male', 23, 1, 0, 5.000, 'S'])
Rose = pd.Series([1, 'Rose', 1, 'female', 20, 1, 0, 100.000, '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_df[~2:]
survivednamepclasssexagesibspparchfareembarked
13080Zimmerman, Mr. Leo3male29.0007.875S
00Jack3male23.0105.000S
11Rose1female20.010100.000S
all_Features, Label = PreprocessData(all_df)

all_probability = model.predict(all_Features)
all_probability[:10]
array([[0.97387624],
       [0.36760893],
       [0.9653297 ],
       [0.29578814],
       [0.96136355],
       [0.26288155],
       [0.93404984],
       [0.27685004],
       [0.92254674],
       [0.30783302]], dtype=float32)
pd = all_df
pd.insert(len(all_df.columns),
         'probability', all_probability)
pd[~2:]
survivednamepclasssexagesibspparchfareembarkedprobability
13080Zimmerman, Mr. Leo3male29.0007.875S0.132631
00Jack3male23.0105.000S0.130663
11Rose1female20.010100.000S0.963028
pd[(pd['survived'] == 0) ]
survivednamepclasssexagesibspparchfareembarkedprobability
20Allison, Miss. Helen Loraine1female2.012151.5500S0.965330
30Allison, Mr. Hudson Joshua Creighton1male30.012151.5500S0.295788
40Allison, Mrs. Hudson J C (Bessie Waldo Daniels)1female25.012151.5500S0.961364
70Andrews, Mr. Thomas Jr1male39.0000.0000S0.276850
90Artagaveytia, Mr. Ramon1male71.00049.5042C0.307833
100Astor, Col. John Jacob1male47.010227.5250C0.382211
150Baumann, Mr. John D1maleNaN0025.9250S0.303370
160Baxter, Mr. Quigg Edmond1male24.001247.5208C0.568902
190Beattie, Mr. Thomson1male36.00075.2417C0.418435
250Birnbaum, Mr. Jakob1male25.00026.0000C0.446399
300Blackwell, Mr. Stephen Weart1male45.00035.5000S0.271255
340Borebank, Mr. John James1male42.00026.5500S0.275931
380Brady, Mr. John Bertram1male41.00030.5000S0.278998
390Brandeis, Mr. Emil1male48.00050.4958C0.364540
400Brewe, Dr. Arthur Jackson1maleNaN0039.6000C0.429713
450Butt, Major. Archibald Willingham1male45.00026.5500S0.269356
460Cairns, Mr. Alexander1maleNaN0031.0000S0.304525
510Carlsson, Mr. Frans Olof1male33.0005.0000S0.291429
520Carrau, Mr. Francisco M1male28.00047.1000S0.312617
530Carrau, Mr. Jose Pedro1male17.00047.1000S0.339315
580Case, Mr. Howard Brown1male49.00026.0000S0.260632
600Cavendish, Mr. Tyrell William1male36.01078.8500S0.271148
620Chaffee, Mr. Herbert Fuller1male46.01061.1750S0.246321
700Chisholm, Mr. Roderick Robert Crispin1maleNaN000.0000S0.297509
710Clark, Mr. Walter Miller1male27.010136.7792C0.426140
740Clifford, Mr. George Quincy1maleNaN0052.0000S0.309330
750Colley, Mr. Edward Pomeroy1male47.00025.5875S0.264827
770Compton, Mr. Alexander Taylor Jr1male37.01183.1583C0.365659
800Crafton, Mr. John Bertram1maleNaN0026.5500S0.303512
810Crosby, Capt. Edward Gifford1male70.01171.0000S0.200277
.................................
12760Vander Planke, Mrs. Julius (Emelia Maria Vande...3female31.01018.0000S0.390119
12780Vendel, Mr. Olof Edvin3male20.0007.8542S0.144151
12790Vestrom, Miss. Hulda Amanda Adolfina3female14.0007.8542S0.541694
12800Vovk, Mr. Janko3male22.0007.8958S0.141521
12810Waelens, Mr. Achille3male22.0009.0000S0.141519
12820Ware, Mr. Frederick3maleNaN008.0500S0.131565
12830Warren, Mr. Charles William3maleNaN007.5500S0.131566
12840Webber, Mr. James3maleNaN008.0500S0.131565
12850Wenzel, Mr. Linhart3male32.5009.5000S0.128364
12870Widegren, Mr. Carl/Charles Peter3male51.0007.7500S0.107727
12880Wiklund, Mr. Jakob Alfred3male18.0106.4958S0.136882
12890Wiklund, Mr. Karl Johan3male21.0106.4958S0.133120
12910Willer, Mr. Aaron ("Abi Weller")3maleNaN008.7125S0.131564
12920Willey, Mr. Edward3maleNaN007.5500S0.131566
12930Williams, Mr. Howard Hugh "Harry"3maleNaN008.0500S0.131565
12940Williams, Mr. Leslie3male28.50016.1000S0.133237
12950Windelov, Mr. Einar3male21.0007.2500S0.142832
12960Wirz, Mr. Albert3male27.0008.6625S0.135120
12970Wiseman, Mr. Phillippe3maleNaN007.2500S0.131567
12980Wittevrongel, Mr. Camille3male36.0009.5000S0.124216
12990Yasbeck, Mr. Antoni3male27.01014.4542C0.161984
13010Youseff, Mr. Gerious3male45.5007.2250C0.147109
13020Yousif, Mr. Wazli3maleNaN007.2250C0.169266
13030Yousseff, Mr. Gerious3maleNaN0014.4583C0.169295
13040Zabour, Miss. Hileni3female14.51014.4542C0.674486
13050Zabour, Miss. Thamine3femaleNaN1014.4542C0.603369
13060Zakarian, Mr. Mapriededer3male26.5007.2250C0.174369
13070Zakarian, Mr. Ortin3male27.0007.2250C0.173603
13080Zimmerman, Mr. Leo3male29.0007.8750S0.132631
00Jack3male23.0105.0000S0.130663

810 rows × 10 columns

pd[(pd['survived'] == 0) & (pd['probability'] > 0.9)]
survivednamepclasssexagesibspparchfareembarkedprobability
20Allison, Miss. Helen Loraine1female2.012151.5500S0.965330
40Allison, Mrs. Hudson J C (Bessie Waldo Daniels)1female25.012151.5500S0.961364
1050Evans, Miss. Edith Corse1female36.00031.6792C0.973539
1690Isham, Miss. Ann Elizabeth1female50.00028.7125C0.971705
2860Straus, Mrs. Isidor (Rosalie Ida Blun)1female63.010221.7792S0.954021
pd[:5]
survivednamepclasssexagesibspparchfareembarkedprobability
01Allen, Miss. Elisabeth Walton1female29.000000211.3375S0.973876
11Allison, Master. Hudson Trevor1male0.916712151.5500S0.367609
20Allison, Miss. Helen Loraine1female2.000012151.5500S0.965330
30Allison, Mr. Hudson Joshua Creighton1male30.000012151.5500S0.295788
40Allison, Mrs. Hudson J C (Bessie Waldo Daniels)1female25.000012151.5500S0.961364
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值