【发布时间】:2020-02-01 23:12:55
【问题描述】:
当我尝试在 Keras 中编译一个带有来自 here 的损失函数的模型时,我遇到了一个错误
ValueError:形状必须为 2 级,但对于输入形状为 [?]、[?] 的“loss/activation_10_loss/MatMul”(操作:“MatMul”)为 1 级。
我已尝试在this 回答后修复此错误。
def get_loss_function(weights):
def loss(y_pred, y_true):
return (y_pred - y_true) * weights # or whatever your loss function should be
return loss
model.compile(loss=get_loss_function(conv_weights), optimizer=SGD(lr=0.1))
复制问题的最简单方法:
from segmentation_models.metrics import iou_score
from segmentation_models import Unet
import keras
class Losses:
def __init__(self):
pass
@staticmethod
def IoULoss(targets, inputs, smooth=1e-6):
logger=logging.getLogger("Losses.IoULoss")
logger.setLevel(Debug_param.debug_scope())
# flatten label and prediction tensors
# logger.critical(("targets.shape",targets.get_shape().as_list(), "inputs.shape",inputs.shape))
inputs = K.flatten(inputs)
targets = K.flatten(targets)
logger.critical(("flatten", "targets.shape", targets.shape, "inputs.shape", inputs.shape))
intersection = K.sum(K.dot(targets, inputs))
total = K.sum(targets) + K.sum(inputs)
union = total - intersection
IoU = (intersection + smooth) / (union + smooth)
return 1 - IoU
model = Unet("resnet34", backend=None, classes=1, activation='softmax')
opt = keras.optimizers.Adam(lr=config.lr)
model.compile(loss=Losses.IoULoss, optimizer=opt,
metrics=[iou_score, "accuracy"])
如何编译带有自定义损失函数的模型或如何防止错误?
Python 版本 3.7.4、keras 2.3.0、TF 1.14、分段模型 0.2.1
【问题讨论】:
标签: python tensorflow keras semantic-segmentation