R keras在U网中连接层

gj3fmq9x  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(148)

当我想连接当前层和模型中指定的前一层时,我无法使keras::layer_concatenate工作。例如:

model = keras::keras_model_sequential(input_shape = inputShape, 
                                      batch_size = batchSize)

keras::layer_conv_2d(model, filters = 32, kernel_size = list(3L, 3L),
                     padding = "same", activation = "relu", name = "conv1")

keras::layer_max_pooling_2d(model, pool_size = c(2L, 2L), name = "pool1")

up1 = keras::layer_upsampling_2d(model, size = c(2L, 2L), name = "tmpUp1")

# Now I want to concatenate tmpUp1 and conv1:
keras::layer_concatenate(list(model$get_layer("conv1"), 
                              model$get_layer("tmpUp1")))

# Error in py_call_impl(callable, dots$args, dots$keywords) : 
# TypeError: object of type 'NoneType' has no len()

这怎么解决呢?
谢谢你!

dm7nw8vv

dm7nw8vv1#

layer_concatenate()采用Tensor,而不是层。您可以使用layer$output访问层的输出Tensor。

library(keras)

model <- 
  keras_model_sequential(input_shape = c(6, 6, 3), batch_size = 5) %>% 
  layer_conv_2d(32, kernel_size = list(3, 3), padding = "same",
                activation = "relu", name = "conv1") %>% 
  layer_max_pooling_2d(pool_size = c(2, 2), name = "pool1") %>% 
  layer_upsampling_2d(size = c(2, 2), name = "tmpUp1")

layer_concatenate(model$get_layer("conv1")$output, 
                  model$get_layer("tmpUp1")$output)
#> KerasTensor(type_spec=TensorSpec(shape=(5, 6, 6, 64), dtype=tf.float32, name=None), name='concatenate/concat:0', description="created by layer 'concatenate'")

相关问题