python - tensorflow /keras中批量大小的自定义损失w权重数组

标签 python tensorflow keras loss

我正在创建一个自定义损失函数,它是一个 MAE(y_true, y_pred),由两个数组 a 和 < em>b,其中所有四个数组的大小相同(10000 个样本/时间步长)。

def custom_loss(y_true, y_pred, a, b):
        mae = K.abs(y_true - y_pred)
        loss = mae * a * b
        return loss

问题:如何将 ab 输入到函数中? 两者都应该像 y_true 和 y_pred 一样进行拆分和洗牌。

到目前为止,我使用的是在形状数据 X(样本 x 时间步长 x 变量)上训练的 LSTM。在这里,我尝试了 tf 的 add_loss 函数来完成此操作,当进一步传递 ab 时,由于数据形状不同而导致错误输入层。

#LSTM
input_layer = Input(shape=input_shape)
in = LSTM(20, activation='relu', return_sequences=True)(input_layer)
out = LSTM(1, activation='linear', return_sequences=False)(in)

layer_a = Input(shape=(10000))
layer_b = Input(shape=(10000))

model = Model(inputs = [input_layer, layer_a, layer_b], outputs = out)  
model.add_loss(custom_loss(input_layer, out, layer_a, layer_b))
model.compile(loss=None, optimizer=Adam(0.01))

# X=data of shape 20 variables x 10000 timesteps, y, a, b = data of shape 10000 timesteps
model.fit(x=[X, a, b], y=y, batch_size=1, shuffle=True)

如何正确执行此操作?

最佳答案

正如您所介绍的,您必须使用add_loss。请记住将所有变量(真实值、预测值和正确格式的额外张量)传递给您的损失。

n_sample = 100
timesteps = 30
features = 5

X = np.random.uniform(0,1, (n_sample,timesteps,features))
y = np.random.uniform(0,1, n_sample)
a = np.random.uniform(0,1, n_sample)
b = np.random.uniform(0,1, n_sample)

def custom_loss(y_true, y_pred, a, b):
    mae = K.abs(y_true - y_pred)
    loss = mae * a * b
    return loss


input_layer = Input(shape=(timesteps, features))
x = LSTM(20, activation='relu', return_sequences=True)(input_layer)
out = LSTM(1, activation='linear')(x)

layer_a = Input(shape=(1,))
layer_b = Input(shape=(1,))
target = Input(shape=(1,))

model = Model(inputs = [target, input_layer, layer_a, layer_b], outputs = out)  
model.add_loss(custom_loss(target, out, layer_a, layer_b))
model.compile(loss=None, optimizer=Adam(0.01))

model.fit(x=[y, X, a, b], y=None, shuffle=True, epochs=3)

在推理模式下使用模型(如果不需要,则删除 y 作为输入以及 a 和 b):

final_model = Model(model.inputs[1], model.output)
final_model.predict(X)

关于python - tensorflow /keras中批量大小的自定义损失w权重数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66493399/

相关文章:

python - 如何获取li的第二个span标签中存在的第二个 anchor 标签的href。 - BeautifulSoup

tensorflow - Resnet50图像预处理

python - 无法在 Django 中加载 tensorflow

keras - 如何可视化注意力权重?

python - 需要使用 Keras 的 model.predict 的帮助

python - 如何从 C++ 调用 Python

python - 包含 Unicode 字符的单词不会出现在 HTML 输出中

python - 如何错误检查 Python 统计模式功能?

python - 检查输入 : expected conv2d_1_input to have shape (3, 32, 32) 时出错,但得到形状为 (32, 32, 3) 的数组

python - “NoneType”对象没有属性 'raise_exception_on_not_ok_status'