06. Basic example

 7 import numpy as np
 8 import tensorflow as tf
 9 from tensorflow.keras.models import Sequential
10 from tensorflow.keras.layers import Dense, Dropout, BatchNormalization, LSTM
11 import shap
12
13 # Create random training values.
14 #
15 # train_x is [
16 #   [
17 #        [0.3, 0.54 ... 0.8],
18 #        [0.4, 0.6 ... 0.55],
19 #        ...
20 #   ],
21 #   [
22 #        [0.3, 0.54 ... 0.8],
23 #        [0.4, 0.6 ... 0.55],
24 #        ...
25 #   ],
26 #   ...
27 # ]
28 #
29 # train_y is corresponding classification of train_x sequences, always 0 or 1
30 # [0, 1, 0, 1, 0, ... 0]
31 """
32 SAMPLES_CNT = 1000
33
34 train_x = np.random.rand(SAMPLES_CNT,5,4)
35 train_y = np.vectorize(lambda x: int(round(x)))(np.random.rand(SAMPLES_CNT))
36
37 val_x = np.random.rand(int(SAMPLES_CNT * 0.1),5,4)
38 val_y = np.vectorize(lambda x: int(round(x)))(np.random.rand(int(SAMPLES_CNT * 0.1)))
39
40 # Train model
41
42 model = Sequential()
43 model.add(LSTM(32,input_shape=train_x.shape[1:], return_sequences=False, stateful=False))
44 model.add(Dense(1, activation='sigmoid'))
45
46 model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001),
47               loss='binary_crossentropy',metrics=['accuracy'])
48
49 fit = model.fit(train_x, train_y, batch_size=64, epochs=2,
50                 validation_data=(val_x, val_y), shuffle=False)
51
52 explainer = shap.DeepExplainer(model, train_x[:10])
53 shap_vals = explainer.shap_values(val_x[:10][:, 0, :])
54 """

Total running time of the script: ( 0 minutes 0.000 seconds)

Gallery generated by Sphinx-Gallery