我想将欧氏距离设置为 LSTM 或 RNN 的损失函数。
这样的函数应该有什么输出:float、(batch_size) 或 (batch_size, timesteps)?
模型输入 X_train 是 (n_samples, timesteps, data_dim)。 Y_train 具有相同的维度。
示例代码:
def euc_dist_keras(x, y):
return K.sqrt(K.sum(K.square(x - y), axis=-1, keepdims=True))
model = Sequential()
model.add(SimpleRNN(n_units, activation='relu', input_shape=(timesteps, data_dim), return_sequences=True))
model.add(Dense(n_output, activation='linear'))
model.compile(loss=euc_dist_keras, optimizer='adagrad')
model.fit(y_train, y_train, batch_size=512, epochs=10)
那么,我应该根据时间步长维度和/或 batch_size 平均损失吗?
最佳答案
损失函数将采用预测标签和真实标签,并将输出一个标量,在 Keras 中:
from keras import backend as K
def euc_dist_keras(y_true, y_pred):
return K.sqrt(K.sum(K.square(y_true - y_pred), axis=-1, keepdims=True))
请注意,它不会将 X_train
作为输入。损失计算遵循前向传播步骤,其值提供预测标签与真实标签相比的优度。
What output should such function have: float, (batch_size) or (batch_size, timesteps)?
损失函数应该有标量输出。
So, should I average loss over timesteps dimension and/or batch_size?
这不需要能够使用欧氏距离作为损失函数。
旁注:对于您的情况,我认为问题可能出在神经网络架构上,而不是损失。给定 (batch_size, timesteps, data_dim)
SimpleRNN
的输出将是 (batch_size, timesteps, n_units)
,而 的输出>密集
层将是(batch_size, n_output)
。因此,鉴于您的 Y_train
具有 (batch_size, timesteps, data_dim)
形状,您可能需要使用 TimeDistributed
wrapper对每个时间切片应用Dense
,并调整全连接层中隐藏单元的数量。
关于keras - RNN (keras) 的欧氏距离损失函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46594115/