我正在尝试为我的一项任务获取resnet50
模型的所有卷积层的权重和偏差。我了解到我们可以使用函数layer.get_weights()
来获得权重和偏差。这将返回一个列表,其中包含存储在layer.get_weights()[0]中的图层的两个元素的权重,并且偏差存储在layer.get_weights()[1]中。这是我使用的代码。
import tensorflow as to
import source
from source import models
from source.utils.image import read_image_bgr, preprocess_image, resize_image
from source.utils.visualization import draw_box, draw_caption
from source.utils.colors import label_color
from source.models import retinanet
import warnings
warnings.filterwarnings("ignore")
from tensorflow import ConfigProto
import numpy as np
import os
import argparse
import keras
from keras.layers import Input,Conv2D,MaxPooling2D,UpSampling2D, Activation, Dropout
from keras.models import Model
ap = argparse.ArgumentParser()
ap.add_argument("-weight", "--weight_file", type=str,default="trained_model.h5",help="Path to the weights file")
ap.add_argument("-backbone", "--backbone", type=str, default="resnet50",help="Backbone model name")
args = vars(ap.parse_args())
#fetching a tensorflow session
def get_session():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return tf.Session(config=config)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.keras.backend.set_session(tf.Session(config=config))
keras.backend.tensorflow_backend.set_session(get_session())
model = str(args.get("weight_file", False))
backbone = str(args.get("backbone", False))
model = models.load_model(str(model), backbone_name=str(backbone))
#model is the resnet50 model
for layer in model.layers:
print('layer name', layer.name)
we = layer.get_weights()
print('len(we)',len(we))
但是在我的情况下,某些情况下的长度为1,而其他情况下的长度为4,这与预期的有所不同。在这一点上我真的很困惑。如果有人有任何想法和建议,将非常有帮助。
谢谢。
答案 0 :(得分:1)
get_weights()
函数返回图层的可训练参数和不可训练参数。 BatchNormalization层具有4个参数,这些参数说明了4个长度的输出(因为Resnet块具有batchnorm)。据我所知,由于批处理规范,ResNet模型未在卷积层中使用偏差项,这可以解释长度为1的输出。