Python Keras 中的“无法解释优化器标识符”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50056356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:22:44  来源:igfitidea点击:

"Could not interpret optimizer identifier" error in Keras

pythonpython-3.xtensorflowkeras

提问by Nehemia

I got this error when I tried to modify the learning rate parameter of SGD optimizer in Keras. Did I miss something in my codes or my Keras was not installed properly?

当我尝试在 Keras 中修改 SGD 优化器的学习率参数时出现此错误。我是否遗漏了代码中的某些内容,或者我的 Keras 安装不正确?

Here is my code:

这是我的代码:

from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Flatten, GlobalAveragePooling2D, Activation
import keras
from keras.optimizers import SGD

model = Sequential()
model.add(Dense(64, kernel_initializer='uniform', input_shape=(10,)))
model.add(Activation('softmax'))
model.compile(loss='mean_squared_error', optimizer=SGD(lr=0.01), metrics= ['accuracy'])*

and here is the error message:

这是错误消息:

Traceback (most recent call last): File "C:\TensorFlow\Keras\ResNet-50\test_sgd.py", line 10, in model.compile(loss='mean_squared_error', optimizer=SGD(lr=0.01), metrics=['accuracy']) File "C:\Users\nsugiant\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\keras_impl\keras\models.py", line 787, in compile **kwargs) File "C:\Users\nsugiant\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\keras_impl\keras\engine\training.py", line 632, in compile self.optimizer = optimizers.get(optimizer) File "C:\Users\nsugiant\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\keras_impl\keras\optimizers.py", line 788, in get raise ValueError('Could not interpret optimizer identifier:', identifier) ValueError: ('Could not interpret optimizer identifier:', )

回溯(最近一次调用):文件“C:\TensorFlow\Keras\ResNet-50\test_sgd.py”,第 10 行,在 model.compile(loss='mean_squared_error', optimizer=SGD(lr=0.01), metrics =['accuracy']) 文件“C:\Users\nsugiant\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\keras_impl\keras\models.py”,第 787 行,编译**kwargs) 文件“C:\Users\nsugiant\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\keras_impl\keras\engine\training.py”,第 632 行,编译自.optimizer = optimizers.get(optimizer) 文件“C:\Users\nsugiant\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\keras_impl\keras\optimizers.py”,第 788 行,在 get raise ValueError('无法解释优化器标识符:', 标识符) ValueError: ('无法解释优化器标识符:', )

回答by Priyanka Chaudhary

I recently faced similar problem.

我最近遇到了类似的问题。

The reason is you are using tensorflow.python.keras api for model and layers and keras.optimizers for SGD. They are two different keras versions of tensorflow and pure keras. They could not work together. You have to change everything to one version. Then it should work. :)

原因是您将 tensorflow.python.keras api 用于模型和层,并将 keras.optimizers 用于 SGD。它们是 tensorflow 和纯 keras 的两个不同 keras 版本。他们不能一起工作。您必须将所有内容更改为一个版本。那么它应该工作。:)

Hope this helps.

希望这可以帮助。

回答by Anju313

I am bit late here, Your issue is you have mixed Tensorflow keras and keras API in your code. The optimizer and the model should come from same layer definition. Use Keras API for everything as below:

我来晚了,您的问题是您的代码中混合了 Tensorflow keras 和 keras API。优化器和模型应该来自同一个层定义。对所有内容使用 Keras API,如下所示:

from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM, BatchNormalization
from keras.callbacks import TensorBoard
from keras.callbacks import ModelCheckpoint
from keras.optimizers import adam

# Set Model
model = Sequential()
model.add(LSTM(128, input_shape=(train_x.shape[1:]), return_sequences=True))
model.add(Dropout(0.2))
model.add(BatchNormalization())

# Set Optimizer
opt = adam(lr=0.001, decay=1e-6)

# Compile model
model.compile(
    loss='sparse_categorical_crossentropy',
    optimizer=opt,
    metrics=['accuracy']
)

I have used adam in this example. Please use your relevant optimizer as per above code.

我在这个例子中使用了 adam。请按照上面的代码使用您的相关优化器。

Hope this helps.

希望这可以帮助。

回答by Sachin Kumar

This problem is mainly caused due to different versions. The tensorflow.keras version may not be same as the keras. Thus causing the error as mentioned by @Priyanka.

这个问题主要是由于版本不同造成的。tensorflow.keras 版本可能与 keras 不同。从而导致@Priyanka 提到的错误。

For me, whenever this error arises, I pass in the name of the optimizer as a string, and the backend figures it out. For example instead of

对我来说,每当出现此错误时,我都会将优化器的名称作为字符串传入,然后后端会计算出来。例如代替

tf.keras.optimizers.Adam

or

或者

keras.optimizers.Adam

I do

我愿意

model.compile(optimizer= 'adam' , loss= keras.losses.binary_crossentropy, metrics=['accuracy'])

回答by Elazar

For some libraries (e.g. keras_radam) you'll need to set up an environment variable before the import:

对于某些库(例如keras_radam),您需要在导入之前设置一个环境变量:

import os
os.environ['TF_KERAS'] = '1'

import tensorflow
import your_library

回答by JUNG EUN CHOI

from tensorflow.keras.optimizers import SGD

This works well.

这很好用。

Since Tensorflow 2.0, there is a new API available directly via tensorflow:

从 Tensorflow 2.0 开始,有一个新的 API 可以直接通过tensorflow

Solution works for tensorflow==2.2.0rc2, Keras==2.2.4(on Win10)

解决方案适用于tensorflow==2.2.0rc2Keras==2.2.4(在 Win10 上)

Please also note that the version above uses learning_rateas parameter and no longer lr.

另请注意,上面的版本learning_rate用作参数而不是lr

回答by partizanos

Running the Keras documentaion example https://keras.io/examples/cifar10_cnn/and installing the latest keras and tensor flow versions

运行 Keras 文档示例https://keras.io/examples/cifar10_cnn/并安装最新的 keras 和张量流版本

(at the time of this writing tensorflow 2.0.0a0 and Keras version 2.2.4 )

(在撰写本文时 tensorflow 2.0.0a0 和 Keras 版本 2.2.4 )

I had to import explicitly the optimizer the keras the example is using,specifically the line on top of the example :

我必须明确导入示例使用的 keras 优化器,特别是示例顶部的行:

opt = tensorflow.keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)

was replaced by

被替换了

from tensorflow.keras.optimizers import RMSprop

opt = RMSprop(lr=0.0001, decay=1e-6)

In the recent version the api "broke" and keras.stuff in a lot of cases became tensorflow.keras.stuff.

在最近的版本中,api 在很多情况下“破坏”和 keras.stuff 变成了 tensorflow.keras.stuff。

回答by user1970528

I tried the following and it worked for me:

我尝试了以下方法,它对我有用:

from keras import optimizers

从 keras 导入优化器

sgd = optimizers.SGD(lr=0.01)

sgd = 优化器.SGD(lr=0.01)

model.compile(loss='mean_squared_error', optimizer=sgd)

model.compile(loss='mean_squared_error', 优化器=sgd)

回答by Qin Heyang

In my case it was because I missed the parentheses. I am using tensorflow_addons so my code was like

就我而言,这是因为我错过了括号。我正在使用 tensorflow_addons 所以我的代码就像

model.compile(optimizer=tfa.optimizers.LAMB, loss='binary_crossentropy',
              metrics=['binary_accuracy'])

And it gives

它给

ValueError: ('Could not interpret optimizer identifier:', <class tensorflow_addons.optimizers.lamb.LAMB'>)

ValueError: ('Could not interpret optimizer identifier:', <class tensorflow_addons.optimizers.lamb.LAMB'>)

Then I changed my code into:

然后我将代码更改为:

model.compile(optimizer=tfa.optimizers.LAMB(), loss='binary_crossentropy',
              metrics=['binary_accuracy'])

and it works.

它有效。

回答by Sameer Chauhan

use

from tensorflow.keras import optimizers

从 tensorflow.keras 导入优化器

instead of

代替

from keras import optimizers

从 keras 导入优化器

回答by Hrushi

I have misplaced parenthesis and got this error,

我放错了括号并得到这个错误,

Initially it was

最初是

x=Conv2D(filters[0],(3,3),use_bias=False,padding="same",kernel_regularizer=l2(reg),x))

The corrected version was

修正后的版本是

x=Conv2D(filters[0],(3,3),use_bias=False,padding="same",kernel_regularizer=l2(reg))(x)