【问题标题】:How to replace the input layer of a pre-trained tensorflow model with our own input layer...?如何用我们自己的输入层替换预训练的张量流模型的输入层......?
【发布时间】:2021-12-28 11:08:46
【问题描述】:

我有一个输入形状为 shape=(None,4096, 12) 的预训练模型。我想将这个训练有素的模型与我自己的输入层一起使用,该输入层具有 shape=(None, 1250, 5)。我已经尝试过发布here 的解决方案。但我有错误

enter ValueError                                Traceback (most recent call last)
/tmp/ipykernel_34/2421370102.py in <module>
2 weights = [layer.get_weights() for layer in mod.layers[1:]]
3 for layer, weight in zip(new_model.layers[1:], weights):
----> 4     layer.set_weights(weight)
/opt/conda/lib/python3.7/site-packages/keras/engine/base_layer.py in 
set_weights(self, weights)
1799           raise ValueError(
1800               'Layer weight shape %s not compatible with 
provided weight '
-> 1801               'shape %s' % (ref_shape, weight_shape))
1802         weight_value_tuples.append((param, weight))
1803         weight_index += 1

ValueError: Layer weight shape (16, 5, 64) not compatible with 
provided weight shape (16, 12, 64)

【问题讨论】:

    标签: python tensorflow keras conv1d


    【解决方案1】:

    我不知道您在链接到的帖子中到底尝试了什么,因为那里有几个选项,但您始终可以做的一件事是将新输入层重新塑造成适当的形状,因为第一个模型是固定的,除非您决定操纵它们:

    第一个模型:

    import tensorflow as tf
    
    inputs = tf.keras.layers.Input(shape=(4096, 12))
    x = tf.keras.layers.LSTM(32)(inputs)
    outputs = tf.keras.layers.Dense(1, 'sigmoid') (x)
    model = tf.keras.Model(inputs, outputs)
    model.compile('adam', 'binary_crossentropy')
    
    x = tf.random.normal((5, 4096, 12))
    y = tf.random.uniform((5, 1), maxval=2, dtype=tf.int32)
    model.fit(x, y, epochs=2, batch_size=2)
    

    删除第一层:

    model.layers.pop(0)
    

    第二个模型:

    new_inputs = tf.keras.layers.Input(shape=(1250, 5))
    x = tf.keras.layers.Dense(4096 * 12)(tf.keras.layers.Flatten()(new_inputs))
    x = tf.keras.layers.Reshape((4096, 12))(x)
    new_outputs = model(x)
    new_model = tf.keras.Model(new_inputs, new_outputs)
    
    new_model.compile('adam', 'binary_crossentropy')
    
    x = tf.random.normal((5, 1250, 5))
    y = tf.random.uniform((5, 1), maxval=2, dtype=tf.int32)
    new_model.fit(x, y, epochs=2, batch_size=2)
    

    【讨论】:

    • 感谢您的回复,但我猜 model.layers.pop(0) 不起作用。
    • 您尝试过我发布的示例吗?它有效。
    猜你喜欢
    • 2018-12-12
    • 2021-08-04
    • 2018-12-21
    • 2020-05-29
    • 2021-11-03
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    相关资源
    最近更新 更多