【发布时间】:2019-06-07 21:35:27
【问题描述】:
我对 python super 的功能和继承不是很熟悉。我尝试复制并使用我找到的 keras 自定义回调示例in this post,但我收到了错误:
super(EarlyStopping, self).__init__()
TypeError: super(type, obj): obj must be an instance or subtype of type
示例代码如下:
import numpy as np
from tensorflow.keras.callbacks import Callback, EarlyStopping
class OverfitEarlyStopping(Callback):
def __init__(self, ratio=0.0,
patience=0, verbose=0):
super(EarlyStopping, self).__init__()
self.ratio = ratio
self.patience = patience
self.verbose = verbose
self.wait = 0
self.stopped_epoch = 0
self.monitor_op = np.greater
def on_train_begin(self, logs=None):
self.wait = 0 # Allow instances to be re-used
def on_epoch_end(self, epoch, logs=None):
current_val = logs.get('val_loss')
current_train = logs.get('loss')
if current_val is None:
warnings.warn('Early stopping requires %s available!' %
(self.monitor), RuntimeWarning)
# If ratio current_loss / current_val_loss > self.ratio
if self.monitor_op(np.divide(current_train,current_val),self.ratio):
self.wait = 0
else:
if self.wait >= self.patience:
self.stopped_epoch = epoch
self.model.stop_training = True
self.wait += 1
def on_train_end(self, logs=None):
if self.stopped_epoch > 0 and self.verbose > 0:
print('Epoch %05d: early stopping due to overfitting.' % (self.stopped_epoch))
overfit_callback = OverfitEarlyStopping(ratio=0.8, patience=3, verbose=1)
我正在使用 Python 3.5 和 tensorflow.keras。我使用的版本中 super 的使用是否发生了变化,还是这个回调一开始就写错了?
【问题讨论】:
-
应该是
super(OverfitEarlyStopping, self).__init__()。 -
谢谢,是的,我想这只是原帖中的一个简单的错字。
-
我发现program creek有时也有很好的例子。例如:programcreek.com/python/example/104417/keras.callbacks.Callback
标签: tensorflow callback keras python-3.5 super