建立一个keras模型
import keras
from keras.models import Model
from keras.layers import Input, Dense
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPool2D
from keras.layers.normalization import BatchNormalization
import numpy as np
mnist_input = Input(shape=(28, 28, 1), name='input')
conv1 = Conv2D(128, kernel_size=4, activation='relu', name='conv1')(mnist_input)
bn1 = BatchNormalization()(conv1)
pool1 = MaxPool2D(pool_size=(2, 2), name='pool1')(bn1)
conv2 = Conv2D(64, kernel_size=4, activation='relu', name='conv2')(pool1)
bn2 = BatchNormalization()(conv2)
pool2 = MaxPool2D(pool_size=(2, 2), name='pool2')(bn2)
hidden1 = Dense(64, activation='relu', name='hidden1')(pool2)
output = Dense(10, activation='softmax', name='output')(hidden1)
model = Model(inputs=mnist_input, outputs=output)
print(model.summary())
返回所有层的权重系数,并保存成numpy array
weights = np.array(model.get_weights())
print(weights[0].shape)
for i in model.get_weights():
print(i.shape)
得到具体某一层的权重系数
对于BN层,layer.get_weights()返回一个list,为[gamma, beta, mean, std]四个array, 见stackoverflow
对于卷积层和全连接层,layer.get_weights()返回一个list,为[weight, bias]两个array
for j in model.layers: # 得到所有层的名称
print(j.name)
print(model.get_layer('batch_normalization_1').get_weights()) # 根据层的名称索引到具体的层,然后得到权重系数
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:keras提取每一层的系数 - Python技术站