提问人:allmen 提问时间:12/26/2022 更新时间:12/26/2022 访问量:155
“ValueError: Unknown optimizer: momentum” binary_crossentropy.请确保将此对象传递给“custom_objects”参数
"ValueError: Unknown optimizer: momentum" binary_crossentropy. Please ensure this object is passed to the `custom_objects` argument
问:
结合CNN-LSTM层,构建一个使用谐波搜索算法进行超参数调谐的模型。
设置参数似乎没问题,在运行时会出现与“custom-objects”相关的错误,这是 tensorflow 特有的。
ValueError:未知优化器:binary_crossentropy。请确保将此对象传递给参数。有关详细信息,请参阅 https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object。custom_objects
代码如下
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from keras.layers import Input, Embedding, LSTM, Dense
from keras.layers import Conv1D, MaxPooling1D, Flatten
from keras.models import Model
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
# Define the CNN-LSTM model
inputs = Input(shape=(X_train.shape[1], X_train.shape[2]))
x = Conv1D(filters=32, kernel_size=2, activation='relu')(inputs)
x = MaxPooling1D(pool_size=1)(x)
x = Flatten()(x)
x = Embedding(input_dim=24, output_dim=128, input_length=24)(x)
x = LSTM(units=128, dropout=0.2, recurrent_dropout=0.2)(x)
outputs = Dense(1, activation='sigmoid')(x)
model = Model(inputs, outputs)
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy',
metrics=['accuracy'])
# Fit the model on the training data
model.fit(X_train, y_train, epochs=10, batch_size=32)
# Evaluate the model on the test data
results = model.evaluate(X_test, y_test)
print(results)
# Define the harmony search algorithm
def harmony_search(model, X_train, y_train, X_test, y_test, n_iterations=10):
best_score = 0
for i in range(n_iterations):
# Randomly select a set of model parameters
params = {
'optimizer': np.random.choice(['adam', 'rmsprop', 'sgd']),
'loss': 'binary_crossentropy',
'metrics': np.random.choice(['accuracy', 'mae'])
}
# Compile the model with the selected parameters
model.compile(params)
# Fit the model on the training data
model.fit(X_train, y_train, epochs=10, batch_size=32)
# Evaluate the model on the test data
score = model.evaluate(X_test, y_test)[1]
# Update the best score if necessary
if score > best_score:
best_score = score
best_params = params
# Return the best set of model parameters
return best_params
# Find the best set of model parameters using the harmony search algorithm
best_params = harmony_search(model, X_train, y_train, X_test, y_test)
# Print the best set of model parameters
print(best_params)
我尝试在类级别添加特定参数,同样的错误。
ValueError:未知优化器:binary_crossentropy。请确保将此对象传递给参数。有关详细信息,请参阅 https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object。custom_objects
答:
1赞
Georgios Livanos
12/26/2022
#1
是值的字典,您将此字典传递给第一个参数,从文档中可以获得这些参数。params
.compile
compile(
optimizer='rmsprop',
loss=None,
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
jit_compile=None,
**kwargs
)
这意味着在某个步骤中尝试将此字典解析为优化器。您真正应该做的是将值传递给正确的参数。例如,使用 dict:.compile
dict['key']
params
# metrics get a list of values
compile(optimizer=params['optimizer'], loss=params['loss'], metrics=[params['metrics']])
评论
0赞
allmen
12/27/2022
我意识到使用这个函数 model.compile(**params) 可以确保平稳运行。我真的不明白✳那里在做什么
0赞
Georgios Livanos
12/27/2022
** 是开箱操作员。有什么作用是将键定义为具有相应值的关键字参数。你可以看看这个 python-reference.readthedocs.io/en/latest/docs/operators/...
评论