from keras import backend as K
from keras.models import load_model
models = load_model('models.hdf5')
image=r'image.png'
images=cv2.imread(r'image.png')
image_arr = process_image(image, (224, 224, 3))
image_arr = np.expand_dims(image_arr, axis=0)
layer_1 = K.function([base_model.get_input_at(0)], [base_model.get_layer('layer_name').output])
f1 = layer_1([image_arr])[0]
其中,K.function有两种不同的写法:
1. 获取名为layer_name的层的输出
layer_1 = K.function([base_model.get_input_at(0)], [base_model.get_layer('layer_name').output])
#指定输出层的名称
2. 获取第n层的输出
layer_1 = K.function([model.get_input_at(0)], [model.layers[5].output])
#指定输出层的序号(层号从0开始)
另外,需要注意的是,书写不规范会导致报错:
报错:TypeError: inputs to a TensorFlow backend function should be a list or tuple
将该句:
f1 = layer_1(image_arr)[0]
修改为:
f1 = layer_1([image_arr])[0]