ValueError: class_weight is only supported for Models with a single output.
问题描述
在使用keras时,由于正负样本不平衡,打算在fit函数中使用参数class_weight进行正负样本权重的调节。
cw = {0: 1, 1: 20}
self.model.fit({"g_input": g, "p_input": p}, {"out": y}, epochs=self.args.epochs, batch_size=self.args.batch_size, verbose=1, class_weight=cw)
结果运行时报错:
ValueError: `class_weight` is only supported for Models with a single output.
解决
报错位置:
if nest.is_nested(y):
raise ValueError(
"`class_weight` is only supported for Models with a single output.")
def is_nested(seq):
"""Returns true if its input is a collections.abc.Sequence (except strings).
>>> tf.nest.is_nested("1234")
False
>>> tf.nest.is_nested([1, 3, [4, 5]])
True
>>> tf.nest.is_nested(((7, 8), (5, 6)))
True
>>> tf.nest.is_nested([])
True
>>> tf.nest.is_nested({"a": 1, "b": 2})
True
>>> tf.nest.is_nested({"a": 1, "b": 2}.keys())
True
>>> tf.nest.is_nested({"a": 1, "b": 2}.values())
True
>>> tf.nest.is_nested({"a": 1, "b": 2}.items())
True
>>> tf.nest.is_nested(set([1, 2]))
False
>>> ones = tf.ones([2, 3])
>>> tf.nest.is_nested(ones)
False
处理
当时使用函数式api写模型时,由于是多输入的,因此使用了字典的方式赋值,这里由于输出是字典(is a collections)因此上面报错。改成如下形式即可。
cw = {0: 1, 1: 1}
self.model.fit(x, y, epochs=self.args.epochs,
batch_size=self.args.batch_size, verbose=1, class_weight=cw)
版权声明:本文为qq_25408127原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。