自定义多输入验证的损失函数

我正在按照这里的说明创建一个自定义损失函数。当我添加验证数据时,会收到一个关于ValueError的错误消息。当我设置validation_data=None时,这个错误就会消失。我在Stackoverflow上找到了一个类似的问题,但我认为我的问题有所不同,因为我试图使用一个自定义损失函数。

这是我的代码:

from tensorflow.keras.layers import *from tensorflow.keras.models import Modelimport numpy as npimport tensorflow.keras.backend as Kfrom tensorflow.keras import regularizersdef loss_fcn(y_true, y_pred, w):    loss = K.mean(K.square((y_true-y_pred)*w))    return loss# 由于TensorFlow将批次大小默认设置为32,当样本数量大于32时,必须是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...

回答:

将训练和验证数据改为列表形式,而不是元组:

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注