Python 在Keras中定义特定的自定义度量
我试图用Python定义一个方法,我想用它作为度量标准,特别是对于EarlyStoping(restore_best_weights)。 问题是,我试图用这种方法(使用当前参数)进行预测,但这种方法似乎不起作用。(我需要一个特定递归问题的预测) 请参见以下简化示例:Python 在Keras中定义特定的自定义度量,python,tensorflow,keras,neural-network,custom-object,Python,Tensorflow,Keras,Neural Network,Custom Object,我试图用Python定义一个方法,我想用它作为度量标准,特别是对于EarlyStoping(restore_best_weights)。 问题是,我试图用这种方法(使用当前参数)进行预测,但这种方法似乎不起作用。(我需要一个特定递归问题的预测) 请参见以下简化示例: import tensorflow as tf from tensorflow.keras.layers import * from tensorflow.keras.activations import * from tensor
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.activations import *
from tensorflow.keras.models import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.initializers import *
from tensorflow.keras.callbacks import *
import numpy as np
x_train = np.zeros((100, 7))
y_train = np.zeros(100)
model = Sequential()
model.add(Dense(units=7, input_shape=(x_train.shape[1], )))
model.add(Dense(units=1))
model.add(Activation('sigmoid'))
input1 = np.zeros((5, 7), dtype=np.float32)
y_hat = model.predict(input1)
print(y_hat)
def testMetric(y_true, y_pred):
#input1 = np.zeros((5, 7), dtype=np.float32)
#y_hat = model.predict(input1)
return 5
model.compile(
loss="binary_crossentropy",
optimizer=Adam(0.05),
metrics=['binary_accuracy', testMetric]
)
reduce_lr = ReduceLROnPlateau(monitor='testMetric', min_delta=0, factor=0.7, patience=1, verbose=1, mode='max')
early = EarlyStopping(monitor='testMetric', min_delta=0, patience=7, verbose=1, mode='max', baseline=None, restore_best_weights=True)
model.fit(
x=x_train,
y=y_train,
epochs=3,
callbacks=[early, reduce_lr]
)
当我在方法“testMetric”中不使用预测时,一切都很顺利。但是当我使用prediciton(取消注释)时,我得到了一条错误消息
RuntimeError: Method requires being in cross-replica context, use get_replica_context().merge_call()
有可能在我的方法中使用预测吗
我使用的是Tensorflow 2.2.0
这对我很有帮助:)你也可以发布错误消息吗,我在colab上尝试了这个方法,得到了与副本上下文相关的错误(我认为这与分布式策略有关)。当我在方法中使用预测时,我得到了以下错误:“RuntimeError:方法需要在跨副本上下文中,使用get\u replica\u context().merge_call()”。我不知道该怎么办。你也可以发布错误消息吗,我在colab上尝试了这个,得到了与副本上下文相关的错误(我认为这与分布式策略有关)。当我在方法中使用预测时,我得到了以下错误:“RuntimeError:方法需要处于跨副本上下文中,使用get_replica_context().merge_call()”。我不知道该怎么办。