0

背景

目前,我正在使用 LSTM 执行回归。我正在使用具有相当大的时间步长的小批量(但比我拥有的时间步数要少得多)。

我正在尝试过渡到时间步长更少但启用状态的更大批次,以允许使用大量生成的训练数据。

但是,我目前正在使用基于 sqrt(timestep) 的正则化,(这是经过消融测试的,有助于提高收敛速度,它之所以有效,是因为问题的统计性质,预期误差会减少 sqrt(timestep) 的一个因子) . 这是通过使用tf.range在损失函数中生成适当大小的列表来执行的。当启用有状态时,这种方法将不正确,因为它会计算错误的时间步数(此批次中的时间步数,而不是到目前为止的整体)。

问题

有没有办法将整数或浮点数的偏移量或列表传递给损失函数?最好不要修改模型,但我认识到可能需要这种性质的 hack。

代码

简化模型:

def create_model():    
    inputs = Input(shape=(None,input_nodes))
    next_input = inputs
    for i in range(dense_layers):
        dense = TimeDistributed(Dense(units=dense_nodes,
                activation='relu',
                kernel_regularizer=l2(regularization_weight),
                activity_regularizer=l2(regularization_weight)))\
            (next_input)
        next_input = TimeDistributed(Dropout(dropout_dense))(dense)

    for i in range(lstm_layers):
        prev_input = next_input
        next_input = LSTM(units=lstm_nodes,
                dropout=dropout_lstm,
                recurrent_dropout=dropout_lstm,
                kernel_regularizer=l2(regularization_weight),
                recurrent_regularizer=l2(regularization_weight),
                activity_regularizer=l2(regularization_weight),
                stateful=True,
                return_sequences=True)\
            (prev_input)
        next_input = add([prev_input, next_input])

    outputs = TimeDistributed(Dense(output_nodes,
            kernel_regularizer=l2(regularization_weight),
            activity_regularizer=l2(regularization_weight)))\
        (next_input)

    model = Model(inputs=inputs, outputs=outputs)

损失函数

def loss_function(y_true, y_pred):
    length = K.shape(y_pred)[1]

    seq = K.ones(shape=(length,))
    if use_sqrt_loss_scaling:
        seq = tf.range(1, length+1, dtype='int32')
        seq = K.sqrt(tf.cast(seq, tf.float32))

    seq = K.reshape(seq, (-1, 1))

    if separate_theta_phi:
        angle_loss = phi_loss_weight * phi_metric(y_true, y_pred, angle_loss_fun)
        angle_loss += theta_loss_weight * theta_metric(y_true, y_pred, angle_loss_fun)
    else:
        angle_loss = angle_loss_weight * total_angle_metric(y_true, y_pred, angle_loss_fun)

    norm_loss = norm_loss_weight * norm_loss_fun(y_true, y_pred)
    energy_loss = energy_loss_weight * energy_metric(y_true, y_pred)
    stability_loss = stability_loss_weight * stab_loss_fun(y_true, y_pred)
    act_loss = act_loss_weight * act_loss_fun(y_true, y_pred)

    return K.sum(K.dot(0
        + angle_loss
        + norm_loss
        + energy_loss
        + stability_loss
        + act_loss
        , seq))

(计算损失函数片段的函数不应该是超级相关的。简单地说,它们也是损失函数。)

4

1 回答 1

1

为此,您可以使用方法sample_weight参数fit并传递sample_weight_mode='temporal'compile方法,以便您可以为批次中每个样本的每个时间步分配权重:

model.compile(..., sample_weight_mode='temporal')
model.fit(..., sample_weight=sample_weight)

sample_weight应该是一个 shape(num_samples, num_timesteps)数组。

请注意,如果您使用的是输入数据生成器或 的实例,则需要将样本权重作为生成器或实例Sequence中生成的元组/列表的第三个元素传递。Sequence

于 2020-04-15T01:23:26.913 回答