如何更改 Keras 优化器代码 [英] How to change Keras optimizer code
问题描述
我对 Keras 真的很陌生,所以如果我的查询有点愚蠢,请原谅我.我使用默认方法在我的系统中安装了 Keras,它运行良好.我想在 Keras 中添加一个新的优化器,以便我可以在 model.compile 函数下轻松提及optimizer = mynewone".如何更改 Keras 中的optimizer.py"代码并确保更改反映在我的 Keras 环境中.这是我尝试过的:
I am really new to Keras so forgive me if my query is a bit silly. I installed Keras in my system using the default methods and it works fine. I want to add a new optimizer to Keras so that I can easily mention "optimizer = mynewone " under the model.compile function. How do I go about changing the " optimizer.py " code in Keras and ensuring that the change is reflected on my Keras environment. Here is what I tried:
假设我在代码中将优化器名称从 rmsprop 更改为 rmsprops,我收到以下错误:
Suppose I change the optimizer name from rmsprop to rmsprops in the code I get the following error:
model.compile(loss='binary_crossentropy', optimizer='rmsprops', metrics= ['accuracy'])
Traceback (most recent call last):
File "<ipython-input-33-40773d534448>", line 1, in <module>
model.compile(loss='binary_crossentropy', optimizer='rmsprops', metrics=['accuracy'])
File "/home/kiran/anaconda/lib/python3.5/site-packages/keras/models.py", line 589, in compile
**kwargs)
File "/home/kiran/anaconda/lib/python3.5/site-packages/keras/engine/training.py", line 469, in compile
self.optimizer = optimizers.get(optimizer)
File "/home/kiran/anaconda/lib/python3.5/site-packages/keras/optimizers.py", line 614, in get
# Instantiate a Keras optimizer
File "/home/kiran/anaconda/lib/python3.5/site-packages/keras/utils/generic_utils.py", line 16, in get_from_module
str(identifier))
ValueError: Invalid optimizer: rmsprops
然后当我点击 optimizers.py 时,我会在我的环境中获得 Keras 开发的代码.之后在代码中,我用rmsprops"替换了所有rmsprop"关键字并保存了文件.所以我想我的系统中必须有更新的 optimizers.py.但是当我回到我的原始文件并运行 model.compile 时,它会抛出同样的错误.
Then when I click on optimizers.py I get the code developed by Keras in my environment. After that in the code I replaced all "rmsprop" keywords with "rmsprops" and saved the file. So I thought I must have the updated optimizers.py in my system. But when I go back to my original file and run model.compile it throws the same error.
任何帮助将不胜感激.提前致谢.
Any help would be really appreciated. Thanks in advance.
推荐答案
我认为您的方法很复杂,而且不必如此.假设您通过继承 keras.optimizers.Optimizer 来实现自己的优化器:
I think your approach is complicated and it doesn't have to be. Let's say you implement your own optimizer by subclassing keras.optimizers.Optimizer:
class MyOptimizer(Optimizer):
optimizer functions here.
然后在你的模型中实例化它,你可以这样做:
Then to instantiate it in your model you can do this:
myOpt = MyOptimizer()
model.compile(loss='binary_crossentropy', optimizer=myOpt, metrics= ['accuracy'])
只需将优化器的一个实例作为 model.compile 的优化器参数传递即可,Keras 现在将使用您的优化器.
Just pass an instance of your optimizer as the optimizer parameter of model.compile and that's it, Keras will now use your optimizer.
这篇关于如何更改 Keras 优化器代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!