微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

具有多个用于验证的输入的自定义损失函数

如何解决具有多个用于验证的输入的自定义损失函数

我正在按照 here 的指令创建自定义损失函数添加validation_data 时,我收到有关ValueError 的错误消息。当我设置validation_data=None 时,此错误消失。我在 Stackoverflow 上找到了 a similar question,但我认为我的问题有所不同,因为我正在尝试使用自定义损失函数

这是我的代码

from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras import regularizers

def loss_fcn(y_true,y_pred,w):
    loss = K.mean(K.square((y_true-y_pred)*w))
    return loss

# since tensor flow sets the batch_size default to 32.  The number of samples have to be a multiple of 32 when it is great than 32.
data_x = np.random.rand(32,51)
data_w = np.random.rand(32,5)
data_y = np.random.rand(32,5)

val_x = np.random.rand(4,51)
val_w = np.random.rand(4,5)
val_y = np.random.rand(4,5)

input_x = Input(shape=(51,),name="input")
y_true = Input(shape=(5,name="true_y")
w = Input(shape=(5,name="weights")

out = Dense(128,kernel_regularizer=regularizers.l2(0.001),name="HL1")(input_x)
y = Dense(5,name="HL2",activation="tanh")(out)

model = Model(inputs=[input_x,y_true,w],outputs=y)
model.add_loss(loss_fcn(y_true,y,w))

model.compile()
model.fit((data_x,data_y,data_w),validation_data=(val_x,val_y,val_w))

错误信息:

ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 3 array(s),but instead got the following list of 1 arrays: [array([[0.74785946,0.63599707,0.45929641,0.98855504,0.84815295,0.28217452,0.93502174,0.23942027,0.11885888,0.32092279,0.47407394,0.19737623,0.85962504,0.35906666,0.22262...

解决方法

您的模型有 3 个输入和一个输出。

模型拟合的参数应该是:

  • x = 3 个张量/数组的列表(或元组)
  • y = 输出值
  • validation_data = 元组(3 个输入的列表,输出值)
,

将训练和验证数据作为列表而不是元组:

model.fit([data_x,data_y,data_w],validation_data=[val_x,val_y,val_w])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。