X 层的输入 0 与该层不兼容:预期形状 = X,找到的形状 = Y

Input 0 of layer X is incompatible with the layer: expected shape= X, found shape= Y

我正在尝试按照 this 教程查看图像模型的所有中间激活的每个通道。

我写了这个:

import glob
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import imageio as im
from keras import models
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Dropout
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ModelCheckpoint

images = []
for img_path in glob.glob('/content/pic1*.JPEG'):
    image1 = mpimg.imread(img_path)
    open_file = image1 / 255
    resize = cv2.resize(open_file,(150,150))
    images.append(open_file)
  
plt.figure(figsize=(20,10))
columns = 5
for i, image in enumerate(images):
    plt.subplot(len(images) / columns + 1, columns, i + 1)
    plt.imshow(image)


print(model.summary())

layer_outputs = [layer.output for layer in model.layers[:]]
activation_model = models.Model(inputs=model.input, outputs=layer_outputs)
activations = activation_model.predict(images[0]) 


  [1]: https://towardsdatascience.com/visualizing-intermediate-activation-in-convolutional-neural-networks-with-keras-260b36d60d0

我收到错误:

   ValueError: Input 0 of layer "model_12" is incompatible with the layer: expected shape=(None, 150, 150, 3), found shape=(32, 448, 3)

我知道这是说我输入的形状有误,但是 cv2.resize(open_file, (150,150)) 行不是要改变它吗?

您在调整大小之前附加图像。

for img_path in glob.glob('/content/pic1*.JPEG'):
    image1 = mpimg.imread(img_path)
    open_file = image1 / 255
    resize = cv2.resize(open_file,(150,150))
    # images.append(open_file)  # WRONG
    images.append(resize)

此外,我认为您模型的输入形状是 4 维的。

# activations = activation_model.predict(images[0])  # not sure this works
activations = activation_model.predict(np.expand_dims(images[0]), axis=0)

有关详细信息,请查看您提到的教程的 'Predicting the class of unseen images' 部分。