Use “Flatten” or “Reshape” to get 1D output of unknown input shape in keras

后端 未结 1 1543
北恋
北恋 2021-01-01 03:21

I want to use the keras layer Flatten() or Reshape((-1,)) at the end of my model to output an 1D vector like [0,0,1,0,0, ... ,0,0,1,0]

相关标签:
1条回答
  • 2021-01-01 03:50

    You can try K.batch_flatten() wrapped in a Lambda layer. The output shape of K.batch_flatten() is dynamically determined at runtime.

    model.add(Lambda(lambda x: K.batch_flatten(x)))
    model.summary()
    
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    conv2d_5 (Conv2D)            (None, 4, None, 32)       4128      
    _________________________________________________________________
    batch_normalization_3 (Batch (None, 4, None, 32)       128       
    _________________________________________________________________
    leaky_re_lu_3 (LeakyReLU)    (None, 4, None, 32)       0         
    _________________________________________________________________
    conv2d_6 (Conv2D)            (None, 1, None, 1)        65        
    _________________________________________________________________
    activation_3 (Activation)    (None, 1, None, 1)        0         
    _________________________________________________________________
    lambda_5 (Lambda)            (None, None)              0         
    =================================================================
    Total params: 4,321
    Trainable params: 4,257
    Non-trainable params: 64
    _________________________________________________________________
    
    
    X = np.random.rand(32, 4, 256, 1)
    print(model.predict(X).shape)
    (32, 256)
    
    X = np.random.rand(32, 4, 64, 1)
    print(model.predict(X).shape)
    (32, 64)
    
    0 讨论(0)
提交回复
热议问题