我试图用TensorFlow和Keras在Python中进行图像识别。请看我的代码,在下面的链接,我提供了,因为我面临的另一个问题,同样的代码,现在是固定的。
getting error while predicting a test image - cannot reshape array of size
我按照post Keras, How to get the output of each layer?获得每个层的输出,并使用下面的代码
from keras import backend as K
inp = model.input # input placeholder
outputs = [layer.output for layer in model.layers[:12]] # all layer outputs except first (input) layer
functor = K.function([inp, K.learning_phase()], outputs ) # evaluation function
# Testing
test = numpy.random.random(input_shape)[np.newaxis,...]
layer_outs = functor([test, 1.])
print (layer_outs)然而,我得到了以下错误:
ValueError: Input tensors to a Functional must come from `tf.keras.Input`. Received: 0 (missing previous layer metadata).有人能帮我得到图像的每一层的输出吗?我正在对它进行预测,这是一个新的图像,而不是网络训练的一部分?
发布于 2022-04-19 05:31:55
如果您可以按以下方式定义您的模型,那么您将不会得到上述特定错误:
model = Sequential([
tf.keras.Input(shape=(X_train.shape[1:])),
Conv2D(32, (3, 3), padding='same', activation='relu'),
Conv2D(32, (3, 3), activation='relu', padding='same'),
Dropout(0.2),
BatchNormalization(),
Conv2D(64, (3, 3), padding='same', name='test1', activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.2),
BatchNormalization(),
Conv2D(64, (3, 3), padding='same', name='test2', activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Dropout(0.2),
BatchNormalization(),
Conv2D(128, (3, 3), padding='same', name='test3',activation='relu'),
Dropout(0.2),
BatchNormalization(),
Flatten(),
Dropout(0.2),
Dense(256, kernel_constraint=maxnorm(3),activation='relu'),
Dropout(0.2),
BatchNormalization(),
Dense(128, kernel_constraint=maxnorm(3),activation='relu'),
Dropout(0.2),
BatchNormalization(),
Dense(class_num,activation='softmax')
])现在,要从模型中获取每个定义层的输出值,请检查如下:
from tensorflow.keras import backend as K
for index, layer in enumerate(model.layers):
func = K.function([model.get_layer(index=0).input], layer.output)
layerOutput = func([X_test])
print(layerOutput.shape) # to check each layer output, remove .shape输出:
(10000, 28, 28, 32)
(10000, 28, 28, 32)
(10000, 28, 28, 32)
(10000, 28, 28, 32)
(10000, 28, 28, 64)
(10000, 14, 14, 64)
(10000, 14, 14, 64)
(10000, 14, 14, 64)
(10000, 14, 14, 64)
(10000, 7, 7, 64)
(10000, 7, 7, 64)
(10000, 7, 7, 64)
(10000, 7, 7, 128)
(10000, 7, 7, 128)
(10000, 7, 7, 128)
(10000, 6272)
(10000, 6272)
(10000, 256)
(10000, 256)
(10000, 256)
(10000, 128)
(10000, 128)
(10000, 128)
(10000, 10)要提取一个特定层的输出值,可以使用以下代码:
feature_extractor = keras.Model(
inputs=model.inputs,
outputs=model.get_layer(name="test1").output)
features = feature_extractor(X_test)
features.shape
features输出:
TensorShape([10000, 28, 28, 64])
<tf.Tensor: shape=(10000, 28, 28, 64), dtype=float32, numpy=
array([[[[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00],
[0.00000000e+00, 0.00000000e+00, 0.00000000e+00, ..
.
.
.https://stackoverflow.com/questions/67538470
复制相似问题