python - 如何使用 Keras 手动更新权重

标签 python performance keras recurrent-neural-network reinforcement-learning

我正在使用 Keras 构建一个 LSTM 并通过使用外部成本函数进行梯度下降来调整它。所以权重更新为:

weights := weights + alpha* gradient(cost)

我知道我可以通过 keras.getweights() 获得权重,但是我怎样才能进行梯度下降并更新所有权重并相应地更新权重。我尝试使用 initializer ,但我还是没弄明白。我只找到了一些与 tensorflow 相关的代码,但我不知道如何将其转换为 Keras。

任何帮助、提示或建议将不胜感激!

最佳答案

keras.layer.set_weights()是你要找的:

import numpy as np
from keras.layers import Dense
from keras.models import Sequential

model = Sequential()
model.add(Dense(10, activation='relu', input_shape=(10,)))
model.add(Dense(5, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='categorical_crossentropy')

a = np.array(model.get_weights())         # save weights in a np.array of np.arrays
model.set_weights(a + 1)                  # add 1 to all weights in the neural network
b = np.array(model.get_weights())         # save weights a second time in a np.array of np.arrays
print(b - a)                              # print changes in weights
查看 keras 文档的相应页面 here .

关于python - 如何使用 Keras 手动更新权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51354186/

相关文章:

tensorflow - 是否可以使用分类器模型的输出分支到不同的模型?

python - Keras Dense层形状错误

c++ - 使用 Python 访问 USB 硬件(具有 native C++ API 的压力传感器矩阵)

python - sqlalchemy.exc.ArgumentError : columns argument to select() must be a Python list or other iterable

python - 是否有更简单的方法来完成以下练习?我根据三个条件向字符串添加元素

ruby-on-rails - 为什么我的 Rails 服务器渲染时间不加起来?

iphone - 在运行时测量和跟踪各种调用的性能的最佳方法是什么?

绘制频谱图时的性能问题

python - 运行 Keras/tensorflow-gpu 时 GPU 崩溃,特别是当时钟速度以 0 MHz 空闲时

python - 错误: (-215) reprojectImageTo3D opencv