K.function用法


    
    
  1. # load the model
  2. print( "[INFO] loading network...")
  3. model = load_model( "fashion.model")
  4. # load the image
  5. image_path = "10026.jpg"
  6. image = cv2.imread(image_path)
  7. # pre-process the image for classification
  8. image = cv2.resize(image, ( 96, 96))
  9. image = image.astype( "float") / 255.0
  10. image = img_to_array(image)
  11. image = np.expand_dims(image, axis= 0)
  12. print(image, type(image))
  13. # extract the layer feature
  14. get_3rd_layer_output = K.function([model.layers[ 0].input],[model.layers[ 3].output])
  15. feature = get_3rd_layer_output(image)[ 0]
  16. # prob = model.predict(image)[0]

报错:TypeError: `inputs` to a TensorFlow backend function should be a list or tuple

原因在于,在使用get_3rd_layer时没有用[ ]将image框起来,变成一个list。

将该句

feature = get_3rd_layer_output(image)[0]
  
  

修改为:

feature = get_3rd_layer_output([image])[0]
  
  

问题解决

参考:https://stackoverflow.com/questions/42045092/does-k-function-method-of-keras-with-tensorflow-backend-work-with-network-layers

一种简单的方法是创建一个新的Model,使得它的输出是你想要的那个输出


  
  
  1. from keras.models import Model
  2. model = ... # create the original model
  3. layer_name = 'my_layer'
  4. intermediate_layer_model = Model(input=model.input,
  5. output=model.get_layer(layer_name).output)
  6. intermediate_output = intermediate_layer_model.predict(data

此外,我们也可以建立一个Keras的函数来达到这一目的:


  
  
  1. from keras import backend as K
  2. # with a Sequential model
  3. get_3rd_layer_output = K.function([model.layers[ 0].input],
  4. [model.layers[ 3].output])
  5. layer_output = get_3rd_layer_output([X])[ 0]

  
  
  1. # load the model
  2. print( "[INFO] loading network...")
  3. model = load_model( "fashion.model")
  4. # load the image
  5. image_path = "10026.jpg"
  6. image = cv2.imread(image_path)
  7. # pre-process the image for classification
  8. image = cv2.resize(image, ( 96, 96))
  9. image = image.astype( "float") / 255.0
  10. image = img_to_array(image)
  11. image = np.expand_dims(image, axis= 0)
  12. print(image, type(image))
  13. # extract the layer feature
  14. get_3rd_layer_output = K.function([model.layers[ 0].input],[model.layers[ 3].output])
  15. feature = get_3rd_layer_output(image)[ 0]
  16. # prob = model.predict(image)[0]

猜你喜欢

转载自blog.csdn.net/Robin_Ge/article/details/84934645