K.function用法
阿新 • • 發佈:2018-12-10
-
# 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]
問題解決
一種簡單的方法是建立一個新的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]
-
# 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]