当我尝试使用here中的损失函数在Keras中编译模型时,出现错误
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
答案 0 :(得分:1)
当我重现您的错误时,我发现函数for x in * ; do
mv $x $(echo $x | sed "s/\?.*//")
done
上出现了问题。看起来Keras希望该函数具有两个2级张量(即矩阵或2D数组)。您正在使用K.dot()
使inputs
和targets
成为一维张量(向量)。这是一个如何从数据中制作二维张量的示例:
K.flatten()