【问题标题】:How to use different activations in output layer in Keras in R如何在 R 中 Keras 的输出层中使用不同的激活
【发布时间】:2020-03-15 01:18:46
【问题描述】:

我想在 R 的 Keras 接口的输出层中组合更多类型的激活。另外,我想对不同的输出使用不同的损失函数。假设我想让前两个神经元与 MSE 损失呈线性关系,第二个神经元 sigmoid 与 BCE 损失,最后一个输出将是具有 MAE 损失的 relu。现在我有了这个,但它不工作:

model <- keras_model_sequential()

model %>% layer_dense(units=120, activation="selu", 
           input_shape=dim(X)[2]) # this is hidden layer, this works fine

model %>% layer_dense(units=120, activation=as.list(c(rep("linear",2), 
            rep("sigmoid",2), "relu"))) # output layer which is not working

model %>% compile(loss=as.list(c(rep("mean_squared_error",2), 
             rep("binary_crossentropy",2), "mean_absolute_error")), # problem here ?
             optimizer=optimizer_adam(lr=0.001) ,metrics = "mae")

然后我用model %&gt;% fit(...) 拟合模型。

错误如下:

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  ValueError: When passing a list as loss, it should have one entry per model outputs. 
  The model has 1 outputs, but you passed loss=['mean_squared_error', 'mean_squared_error', ...

感谢任何帮助。

EDIT :仅重写代码,以便更好地阅读。

【问题讨论】:

    标签: r tensorflow keras loss-function activation-function


    【解决方案1】:

    我认为,如果您想拥有多个输出,则需要使用函数式(即而不是顺序)API - 在此处查看一些示例:https://keras.rstudio.com/articles/functional_api.html

    【讨论】:

    • 那么差异会仅仅在于实现,还是在于背后的数学?谢谢。
    • 我认为数学是一样的——函数式 API 比顺序式 API 灵活得多,后者(顾名思义)只允许构建顺序网络,其中层线性馈入下一个。使用函数式 API,您可以使用顺序 API 完成所有可能的事情,但您可以使用后者做更多事情。
    猜你喜欢
    • 2018-05-26
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2017-07-30
    相关资源
    最近更新 更多