首页 > 解决方案 > 如何在 keras 中将 LSTM 的权重提取到 csv?

问题描述

我使用此代码get_weights()提取权重。我可以检查每个重量。但我不能将每个权重发送到 csv。我想在 Matlab 中使用提取的权重。

我试图在 Jupyter 笔记本中提取权重。但我不能划分每个权重。

for name, weight in zip(names, weights):
    print(name, weight.shape)
    print(weight)
    weight_i = pd.DataFrame(weights).to_csv('C:/deeplearning/weighttest.csv')

layer_type = name.split('/')[1]
if layer_type == 'kernel:0':
    kernel_0 = weight

if layer_type == 'recurrent_kernel:0':
    recurrent_kernel_0 = weight

elif layer_type == 'bias:0':
    bias_0 = weight

print()

n=[]   
units = 128  # LSTM layers


Wi = kernel_0[:, 0:units]
Wf = kernel_0[:, units:2 * units]
Wc = kernel_0[:, 2 * units:3 * units]
Wo = kernel_0[:, 3 * units:]


Ui = recurrent_kernel_0[:, 0:units]
Uf = recurrent_kernel_0[:, units:2 * units]
Uc = recurrent_kernel_0[:, 2 * units:3 * units]
Uo = recurrent_kernel_0[:, 3 * units:]


bi = bias_0[0:units]
bf = bias_0[units:2 * units]
bc = bias_0[2 * units:3 * units]
bo = bias_0[3 * units:]


ht_1 = np.zeros(n * units).reshape(n, units)
Ct_1 = np.zeros(n * units).reshape(n, units)

results = []

for t in range(0, len(x_data[0, :])):
xt = np.array(x_data[0, t])

ft = hard_sigmoid(np.dot(xt, Wf) + np.dot(ht_1, Uf) + bf)  # forget gate
it = hard_sigmoid(np.dot(xt, Wi) + np.dot(ht_1, Ui) + bi)  # input gate
ot = hard_sigmoid(np.dot(xt, Wo) + np.dot(ht_1, Uo) + bo)  # output gate
Ct = ft * Ct_1 + it * np.tanh(np.dot(xt, Wc) + np.dot(ht_1, Uc) + bc)
ht = ot * np.tanh(Ct)

ht_1 = ht  # hidden state, previous memory state
Ct_1 = Ct  # cell state, previous carry state

results.append(ht)
print(t, ht)

输入权重为(5,512)。经常性体重是(128,512)

我想通过除法提取输入权重,循环权重。

我想通过 csv 看到它。

标签: pandastensorflowkeras

解决方案


推荐阅读