具有多个输出和自定义损失功能的Keras模型

时间:2019-09-12 07:45:03

标签: r keras

在安装Keras神经网络进行分位数回归的背景下,我遇到了this postthis。不幸的是,每个分位数只能创建一个模型。这可能会导致分位数交叉。我只是想知道,能否使用Keras和R拟合多输出ANN,其中不同的输出对应不同的分位数?

这是引用的第一个链接中可再现的代码:

quantile <- 0.5
tilted_loss <- function(q, y, f) {
  e <- y - f
  k_mean(k_maximum(q * e, (q - 1) * e), axis = 2)
}

sess <- k_get_session()
ys <- k_constant(c(1,2,3,4), shape = c(2,2))
yhats <- k_constant(c(1,3,3,4), shape = c(2,2))
sess$run(tilted_loss(quantile, ys, yhats))

x_train <-
  iris[1:120, c("Petal.Length", "Sepal.Length")] %>% as.matrix()
y_train <-
  iris[1:120, c("Petal.Width", "Sepal.Width")] %>% as.matrix()
x_test <-
  iris[121:150, c("Petal.Length", "Sepal.Length")] %>% as.matrix()
y_test <-
  iris[121:150, c("Petal.Width", "Sepal.Width")] %>% as.matrix()

model <- keras_model_sequential()
model %>%
  layer_dense(units = 32, input_shape = 2) %>%
  layer_activation_leaky_relu() %>%
  layer_dropout(rate = 0.2) %>%
  layer_dense(units = 2)

model %>% compile(
  optimizer = "adam",
  loss = function(y_true, y_pred)
    tilted_loss(quantile, y_true, y_pred),
  metrics = "mae"
)

history <-
  model %>% fit(x_train,
                y_train,
                batch_size = 10,
                epochs = 120)

plot(history) 

0 个答案:

没有答案