如何更改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屋!