Keras使用K.function抽取中间层报错: TypeError: `inputs` to a TensorFlow backend function should be a list or t

# load the model
print("[INFO] loading network...")
model = load_model("fashion.model")

# load the image
image_path = "10026.jpg"
image = cv2.imread(image_path)
# pre-process the image for classification
image = cv2.resize(image, (96, 96))
image = image.astype("float") / 255.0
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
print(image, type(image))
# extract the layer feature
get_3rd_layer_output = K.function([model.layers[0].input],[model.layers[3].output])
feature = get_3rd_layer_output(image)[0]
# 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,使得它的输出是你想要的那个输出

from keras.models import Model

model = ...  # create the original model

layer_name = 'my_layer'
intermediate_layer_model = Model(input=model.input,
                                 output=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(data

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

from keras import backend as K

# with a Sequential model
get_3rd_layer_output = K.function([model.layers[0].input],
                                  [model.layers[3].output])
layer_output = get_3rd_layer_output([X])[0]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uncle_ll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值