对于比平时更长的介绍,我深表歉意,但对于这个问题很重要:
我最近被分配到一个现有项目上工作,该项目使用 Keras+Tensorflow 创建一个完全连接的网络。
总的来说,该模型有 3 个全连接层,有 500 个神经元,并有 2 个输出类。第一层有 500 个神经元,它们连接到 82 个输入特征。该模型用于生产并每周重新训练,使用由外部来源生成的本周信息。
设计模型的工程师不再在这里工作,我正在尝试逆向工程并了解模型的行为。
我为自己定义的几个目标是:
了解特征选择过程和特征重要性。
了解并控制每周的再培训过程。
为了尝试回答这两个问题,我实施了一个实验,我用两个模型输入我的代码:一个来自前一周,另一个来自本周:
import pickle
import numpy as np
import matplotlib.pyplot as plt
from keras.models import model_from_json
path1 = 'C:/Model/20190114/'
path2 = 'C:/Model/20190107/'
model_name1 = '0_10.1'
model_name2 = '0_10.2'
models = [path1 + model_name1, path2 + model_name2]
features_cum_weight = {}
然后我取每个特征并尝试对将其连接到第一个隐藏层的所有权重(它们的绝对值)求和。通过这种方式,我创建了两个包含 82 个值的向量:
for model_name in models:
structure_filename = model_name + "_structure.json"
weights_filename = model_name + "_weights.h5"
with open(structure_filename, 'r') as model_json:
model = model_from_json(model_json.read())
model.load_weights(weights_filename)
in_layer_weights = model.layers[0].get_weights()[0]
in_layer_weights = abs(in_layer_weights)
features_cum_weight[model_name] = in_layer_weights.sum(axis=1)
然后我使用 MatplotLib 绘制它们:
# Plot the Evolvement of Input Neuron Weights:
keys = list(features_cum_weight.keys())
weights_1 = features_cum_weight[keys[0]]
weights_2 = features_cum_weight[keys[1]]
fig, ax = plt.subplots(nrows=2, ncols=2)
width = 0.35 # the width of the bars
n_plots = 4
batch = int(np.ceil(len(weights_1)/n_plots))
for i in range(n_plots):
start = i*(batch+1)
stop = min(len(weights_1), start + batch + 1)
cur_w1 = weights_1[start:stop]
cur_w2 = weights_2[start:stop]
ind = np.arange(len(cur_w1))
cur_ax = ax[i//2][i%2]
cur_ax.bar(ind - width/2, cur_w1, width, color='SkyBlue', label='Current Model')
cur_ax.bar(ind + width/2, cur_w2, width, color='IndianRed', label='Previous Model')
cur_ax.set_ylabel('Sum of Weights')
cur_ax.set_title('Sum of all weights connected by feature')
cur_ax.set_xticks(ind)
cur_ax.legend()
cur_ax.set_ylim(0, 30)
plt.show()
米脂
相关分类