如何在Keras中的Sequential模型中更改输入形状(How to change input shape in Sequential model in Keras)

编程入门 行业动态 更新时间:2024-10-28 22:23:28
如何在Keras中的Sequential模型中更改输入形状(How to change input shape in Sequential model in Keras)

我有一个我在Keras建立的顺序模型。 我试图弄清楚如何改变输入的形状。 在以下示例中

model = Sequential() model.add(Dense(32, input_shape=(500,))) model.add(Dense(10, activation='softmax')) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

假设我想构建一个具有不同输入形状的新模型,概念性应该如下所示:

model1 = model model1.layers[0] = Dense(32, input_shape=(250,))

有没有办法修改模型输入形状?

I have a sequential model that I built in Keras. I try to figure out how to change the shape of the input. In the following example

model = Sequential() model.add(Dense(32, input_shape=(500,))) model.add(Dense(10, activation='softmax')) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

let's say that I want to build a new model with different input shape, conceptual this should looks like this:

model1 = model model1.layers[0] = Dense(32, input_shape=(250,))

is there a way to modify the model input shape?

最满意答案

想想在那种情况下改变输入形状意味着什么。

你的第一个模特

model.add(Dense(32, input_shape=(500,)))

具有密集层,实际上是500x32矩阵。

如果您将输入更改为250个元素,则图层的矩阵和输入维度将不匹配。

但是,如果你想要实现的是重复使用你的前500个元素输入模型中最后一层经过训练的参数,你可以通过get_weights获得这些权重。 然后,您可以使用set_weights重建新模型并在新模型中设置值。

model1 = Sequential() model1.add(Dense(32, input_shape=(250,))) model1.add(Dense(10, activation='softmax')) model1.layers[1].set_weights(model1.layers[1].get_weights())

请记住,model1第一层(aka model1.layers [0])仍然是未经训练的

Think about what changing the input shape in that situation would mean.

Your first model

model.add(Dense(32, input_shape=(500,)))

Has a dense layer that really is a 500x32 matrix.

If you changed your input to 250 elements, your layers's matrix and input dimension would mismatch.

If, however, what you were trying to achieve was to reuse your last layer's trained parameters from your first 500 element input model, you could get those weights by get_weights. Then you could rebuild a new model and set values at the new model with set_weights.

model1 = Sequential() model1.add(Dense(32, input_shape=(250,))) model1.add(Dense(10, activation='softmax')) model1.layers[1].set_weights(model1.layers[1].get_weights())

Keep in mind that model1 first layer (aka model1.layers[0]) would still be untrained

更多推荐

本文发布于:2023-07-08 19:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1079979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:形状   模型   如何在   Sequential   Keras

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!