Kou*_*oul 11 keras keras-layer keras-2
在一些特征提取实验中,我注意到“model.pop()”功能没有按预期工作。对于像 vgg16 这样的预训练模型,在使用 'model.pop()' 后,model.summary() 显示该层已被删除(预期有 4096 个特征),但是在将图像通过新模型时,结果相同特征数量(1000)作为原始模型。无论移除多少层,包括一个完全空的模型,它都会生成相同的输出。寻求您对可能出现的问题的指导。
#Passing an image through the full vgg16 model
model = VGG16(weights = 'imagenet', include_top = True, input_shape = (224,224,3))
img = image.load_img( 'cat.jpg', target_size=(224,224) )
img = image.img_to_array( img )
img = np.expand_dims( img, axis=0 )
img = preprocess_input( img )
features = model.predict( img )
features = features.flatten()
print(len(features)) #Expected 1000 features corresponding to 1000 imagenet classes
Run Code Online (Sandbox Code Playgroud)
1000
model.layers.pop()
img = image.load_img( 'cat.jpg', target_size=(224,224) )
img = image.img_to_array( img )
img = np.expand_dims( img, axis=0 )
img = preprocess_input( img )
features2 = model.predict( img )
features2 = features2.flatten()
print(len(features2)) #Expected 4096 features, but still getting 1000. Why?
#No matter how many layers are removed, the output is still 1000
Run Code Online (Sandbox Code Playgroud)
1000
谢谢!
在此处查看完整代码:https : //github.com/keras-team/keras/files/1592641/bug-feature-extraction.pdf
解决@Koul 的回答。
我相信您不需要使用该pop
方法。而只是将输出层之前的层作为Model
方法的输出参数的参数传递:
from keras.models import Model
model2 = Model(model.input, model.layers[-2].output)
model2.summary()
Run Code Online (Sandbox Code Playgroud)
在这里找到答案: https: //github.com/keras-team/keras/issues/2371#issuecomment-308604552
from keras.models import Model
model.layers.pop()
model2 = Model(model.input, model.layers[-1].output)
model2.summary()
Run Code Online (Sandbox Code Playgroud)
model2 行为正确。
归档时间: |
|
查看次数: |
8646 次 |
最近记录: |