简体   繁体   English

获取 keras 自定义损失 function 内部的训练数据形状

[英]Get training data shape inside keras custom loss function

I have written the below custom loss function, where I need to create a factor by dividing the input shape with the output shape.我已经编写了下面的自定义损失 function,其中我需要通过将输入形状除以 output 形状来创建一个因子。

def distance_loss(x,y):
    x_shape = K.int_shape(x)[1]
    y_shape = K.int_shape(y)[1]
    print(x_shape,y_shape)
    factor = x_shape/y_shape
    loss = tf.sqrt(factor) * tf.norm(x-y)
    return tf.math.abs(loss)

This is the model architecture is:这是 model 架构是:

model = Sequential()
model.add(Dense(32,input_dim=4))
model.add(Dense(64,activation='relu'))
model.add(Dense(128,activation='relu'))
model.add(Dense(64,activation='relu'))
model.add(Dense(2,activation='relu'))
opt = Adam(lr = 0.001)
model.compile(optimizer = opt, loss=distance_loss,metrics=['accuracy'])

When I ran the model.compile line.当我运行model.compile行时。 The custom loss prints自定义损失打印

None 2无 2

and throws an error并抛出错误

TypeError: unsupported operand type(s) for /: 'NoneType' and 'int' TypeError:不支持的操作数类型/:'NoneType'和'int'

I read that the input shape of the training data is only known during the training phase.我读到训练数据的输入形状只有在训练阶段才知道。 Is there any way to bypass this issue?有没有办法绕过这个问题?

Use K.shape instead:改用K.shape

def distance_loss(x,y):
    x_shape = K.shape(x)[1]
    y_shape = K.shape(y)[1]
    factor = K.cast(x_shape, x.dtype) / K.cast(y_shape, y.dtype)
    loss = tf.sqrt(factor) * tf.norm(x-y)
    return tf.math.abs(loss)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Keras自定义丢失函数错误:'AttributeError:'function'对象没有属性'get_shape' - Keras custom loss function error: 'AttributeError: 'function' object has no attribute 'get_shape' 在自定义损失函数中使用Keras层 - Using Keras layers inside custom loss function 在 Keras 训练期间如何在损失函数内打印? - How do I print inside the loss function during training in Keras? 使用自定义 Keras 数据生成器和损失 function 时地面实况标签的形状(无,无) - Shape (None, None) of ground truth labels when using custom Keras data generator and loss function TensorFlow中的自定义损失函数用于对训练数据进行加权 - Custom Loss Function in TensorFlow for weighting training data 如何在 Keras 的自定义批量训练中获得每个时期的损失? - How to get the loss for each epoch in custom batch training in Keras? Keras 自定义损失 Function InvalidArgumentError: In[1] 不是矩阵。 相反,它具有形状 [] - Keras Custom Loss Function InvalidArgumentError: In[1] is not a matrix. Instead it has shape [] 创建 keras 张量,其形状与 model output 用于自定义损失 ZC1C425268E68385D1ABZA77 - Create keras tensor with shape as same as model output for custom loss function Keras误解了训练数据的形状 - Keras misinterprets training data shape Keras 上的自定义损失 function - Custom loss function on Keras
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM