[英]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.