简体   繁体   中英

How to get weights from keras model?

I'm trying to build a 2 layered neural network for MNIST dataset and I want to get weights from my model.

I found a similar question her on SO and I tried this,

model.get_weights()

But It returned 11 values when I check the len(model.get_weights()) Isn't it suppose to return 3 weights? I have even disabled bias.

model = Sequential()
model.add(Flatten(input_shape = (28, 28)))
model.add(Dense(512, activation='relu', kernel_initializer='he_normal', use_bias=False,))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dense(128, activation='relu', kernel_initializer='he_normal', use_bias=False,))
model.add(BatchNormalization())
model.add(Dropout(0.1))
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', use_bias=False,))

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

result = model.fit(x_train, y_train, validation_split=0.25, epochs=10, 
                   batch_size=128, verbose=1)

To get the weights of a particular layer , you could retrieve this layer by using its name and call get_weights on it (as shubham-panchal said in its comment ).

For example:

model.get_layer('dense').get_weights()

or

model.get_layer('dense_2').get_weights()

You could go though the layers of your model and retrieve its name and weights:

{layer.name: layer.get_weights() for layer in model.layers}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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