简体   繁体   English

连接来自 Keras 多个层的多个特征

[英]Concatenate multiple features from Keras multiple layers

I am obtaining the following error我收到以下错误

ValueError: as_list() is not defined on an unknown TensorShape.

My code looks like this我的代码看起来像这样

# define input
X_input = Input(shape=(n_features, n_channels))
   
# define features extractor model
features = Lambda(
    function=extract_features_lambda,
    output_shape=(None,)
)(X_input)

# CNN block
X = Reshape((n_steps, n_length, n_channels))(X_input)
    
X = TimeDistributed(
    Conv1D(filters=32, kernel_size=5, activation='relu'),
    input_shape=(None, n_length, n_features)
)(X)
    
X = TimeDistributed(
    Conv1D(filters=64, kernel_size=7, activation='relu')
)(X)

X = TimeDistributed(
    Conv1D(filters=32, kernel_size=5, activation='relu')
)(X)

X = TimeDistributed(Dropout(0.5))(X)
X = TimeDistributed(MaxPooling1D(pool_size=2))(X)
X = Flatten()(X)
    
# merge the 2 features
X = Concatenate()([features, X])

The Lambda layer contains a custom feature extractor function. Lambda 层包含自定义特征提取器 function。 This computes some features and returns a numpy array.这会计算一些特征并返回 numpy 数组。 The template function looks like this模板 function 看起来像这样

def extract_features(X):
    features = np.zeros(29, X.shape[1])

    # compute the features ...

    return features.flatten()

def extract_features_lambda(X):
    features = tf.py_function(
        extract_features,
        [X],
        tf.float32
    )
    
    features.set_shape = ((None, 29*12))
    
    return features

What I'm doing wrong?我做错了什么?

You using custom Fn Lamda that can customize is correct, I also doing by您使用可以自定义的自定义 Fn Lamda 是正确的,我也是这样做的

  1. Using Lamda Callback the answer will see as in below you can trails for each layer when using name.使用 Lamda 回调,答案将如下所示,您可以在使用名称时跟踪每一层。
[<KerasTensor: shape=(None, 1, 32, 32, 3) dtype=float32 (created by layer 'input_1')>]

<keras.engine.functional.Functional object at 0x0000016DB5CC51C0> <keras.engine.functional.Functional object at 0x0000016DB5CC51C0>

  1. Lamda Fn as you do the same way you have the same answer Lamda Fn 当你做同样的事情你有同样的答案
 [<KerasTensor: shape=(None, 1, 32, 32, 3) dtype=float32 (created by layer 'input_1')>]
<keras.engine.functional.Functional object at 0x0000016DB5CC51C0>
  1. You also can do by model properties when you using sequential当您使用顺序时,您也可以通过 model 属性来完成
model = tf.keras.models.Sequential([                    
tf.keras.layers.InputLayer(input_shape=(1, 32, 32, 3)), ...         
])

And more you can do with array and sequence properties...你可以用数组和序列属性做更多的事情......

简单映射目标编码 简单映射目标编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM