【发布时间】:2020-06-05 18:58:15
【问题描述】:
我尝试为顺序模型构建自定义损失函数。在这个损失函数中,y_true 和 y_pred 用于计算误差。当我尝试替换 y_true 张量时,模型中的所有真实值都应该是相同的外部真实值,我得到不同的结果(大约是预期值的一半)。 为了更清楚地说明这一点,这是我正在运行的代码的一部分:
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import tensorflow as tf
from tensorflow import keras
def custom_loss(y_true, y_pred):
loss = tf.square(y_pred - y_true) + tf.square(y_pred - y_true)
return loss
model = Sequential()
model.add(Dense(5, input_dim=4, activation='tanh', use_bias=True)) # 1
model.add(Dense(5, activation='tanh')) # 2
model.add(Dense(5, activation='tanh')) # 3
model.add(Dense(5, activation='tanh')) # 4
model.add(Dense(5, activation='tanh')) # 5
model.add(Dense(1))
model.compile(loss=custom_loss, optimizer='adam', metrics=['accuracy'])
当我现在尝试用转换为张量的外部变量替换 y_true 之一时,我没有得到相同的结果。 input_scaled 与 model.fit 中也使用了相同的 numpy 数组,所以我希望这两个自定义损失函数会产生相同的输出。
input_as_tensor = tf.convert_to_tensor(np.float32(input_scaled))
def custom_loss(y_true, y_pred):
loss = tf.square(y_pred - y_true) + tf.square(y_pred - input_as_tensor)
return loss
# ...as above...
hist = model.fit(input_to_fit, input_scaled, epochs=300, callbacks=[tensorboard_callback], validation_split=0.2)
我使用的是 TensorFlow 版本:2.0.0。 任何解释差异的想法将不胜感激。
编辑:
我认识到 Keras 正在以标准批量大小 32 处理我的输入数据,因此我的 input_as_tensor 和大小不同的 y_true 之间存在维度不匹配。我必须弄清楚如何从我的input_as_tensor 中减去正确的值。
【问题讨论】:
标签: python tensorflow keras tensor loss-function