You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言Keras内置函数式模型上添加自定义输出层

错误原因说明

%>%运算符仅支持连接张量/层对象,不能直接作用于Model类型的对象,你两次报错都是因为将预训练模型N1、自定义模型N2直接放到了管道右侧/左侧,需要先提取模型的输出张量再做拼接。


方案1:直接追加自定义输出层

预训练模型输出为4维卷积张量,需先通过全局池化压平才能适配全连接层,正确实现如下:

library(keras)

# 定义输入层
inlayer <- layer_input(shape = c(75, 75, 1))
# 加载无顶层的InceptionV3
N1 <- application_inception_v3(weights = NULL,
                               input_tensor = inlayer,
                               include_top = FALSE)
# 堆叠后续层
fullnet_output <- N1$output %>% 
  layer_global_average_pooling_2d() %>% # 将4维卷积输出转换为2维特征向量
  layer_dense(units = 2, activation = 'sigmoid')
# 函数式API生成完整模型
fullnet <- keras_model(inputs = inlayer, outputs = fullnet_output)

方案2:合并两个独立定义的模型

如果已经提前定义好了N1和N2两个模型,可通过提取各自的输入输出张量完成拼接:

library(keras)

# 你预先定义的N1
inlayer <- layer_input(shape = c(75, 75, 1))
N1 <- application_inception_v3(weights = NULL,
                               input_tensor = inlayer,
                               include_top = FALSE)

# 你预先定义的N2
N2_in <-  layer_input(shape = c(2048))
N2_out <- N2_in %>% layer_dense(units = 2, activation = 'sigmoid')
N2 <- keras_model(N2_in, N2_out)

# 模型合并逻辑
combined_output <- N1$output %>%
  layer_global_average_pooling_2d() %>% # 输出维度为(None,2048),刚好匹配N2的输入要求
  N2()
# 生成完整合并模型
fullnet <- keras_model(inputs = inlayer, outputs = combined_output)

完成后可执行summary(fullnet)验证模型结构是否符合预期。

内容的提问来源于stack exchange,提问作者AHP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:18:04