【问题标题】:How can I solve "expected axis -1 of input shape to have value 1 but received input with shape [None, 256, 256, 3]'" error?如何解决“输入形状的预期轴 -1 的值为 1,但接收到的输入形状为 [None, 256, 256, 3]'”错误?
【发布时间】:2020-10-29 14:05:42
【问题描述】:

我正在尝试使用 keras 模型。我训练了模型并想从网络摄像头中使用它。但是,据我了解,我在训练模型时使用的输入与从相机接收到的输入不匹配。我该如何解决这个问题?

这里是火车代码:

from keras.preprocessing.image import ImageDataGenerator
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Dropout
from keras.layers import Dense
from keras.layers import Flatten

from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.models import Sequential, load_model
import tensorflow as tf
import numpy as np
import os

# plot pretty figures
import matplotlib
import matplotlib.pyplot as plt

plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

nbatch=32

train_datagen = ImageDataGenerator ( rescale=1./255,
                                     rotation_range=12.,
                                     width_shift_range=0.2,
                                     height_shift_range=0.2,
                                     zoom_range=0.15,
                                     horizontal_flip=True)

test_datagen = ImageDataGenerator (rescale=1./255)

train_gen = train_datagen.flow_from_directory(
    'images/train/',
    target_size=(256,256),
    color_mode='grayscale',
    batch_size=nbatch,
    classes=['NONE','ONE','TWO','THREE','FOUR','FIVE'],
    class_mode='categorical'
)

test_gen = test_datagen.flow_from_directory(
    'images/test/',
    target_size=(256,256),
    color_mode='grayscale',
    batch_size=nbatch,
    classes=['NONE','ONE','TWO','THREE','FOUR','FIVE'],
    class_mode='categorical'
)

for X, y in train_gen:
    print(X.shape, y.shape)

    plt.figure(figsize=(16,16))
    for i in range(25):
        plt.subplot(5,5,i+1)
        plt.axis('off')
        plt.title('Label: {}'.format(np.argmax(y[i])))
        img= np.uint8(255*X[i,:,:,0])
        plt.imshow(img,cmap='gray')
    break

plt.show()

model = Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(256,256,1)))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(128,(3,3),activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(256,(3,3),activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(150, activation='relu'))
model.add(Dropout(0.25))
model.add(Dense(6,activation='softmax'))

model.summary()

model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])

callback_list=[EarlyStopping(monitor='val_loss',patience=10),
               ModelCheckpoint(filepath='model_6cat_2.h6',monitor='val_loss',save_best_only=True),]

os.environ["CUDA_VISIBLE_DEVİCES"] = "0"
with tf.device('/GPU:0'):
    history = model.fit_generator(
        train_gen,
        steps_per_epoch=64,
        epochs=200,
        validation_data=test_gen,
        validation_steps=28,
        callbacks=callback_list
    )

plt.figure(figsize=(16,6))
plt.subplot(1,2,1)
nepochs=len(history.history['loss'])
plt.plot(range(nepochs),history.history['loss'], 'g-', label='train')
plt.plot(range(nepochs),history.history['val_loss'], 'c-', label='test')
plt.legend(prop={'size':20})
plt.ylabel('loss')
plt.xlabel('number of epochs')
plt.subplot(1,2,2)
plt.plot(range(nepochs),history.history['acc'], 'g-', label='train')
plt.plot(range(nepochs),history.history['val_acc'], 'c-', label='test')
plt.legend(prop={'size':20})
plt.ylabel('accuracy')
plt.xlabel('number of epochs')


X_test, y_test= [], []
for ibatch, (X,y) in enumerate(test_gen):
    X_test.append(X)
    y_test.append(y)
    ibatch+=1
    if (ibatch==5*28):break

X_test = np.concatenate(X_test)
y_test = np.concatenate(y_test)
y_test = np.int32([np.argmax(r) for  r in y_test])


y_pred = np.int32([np.argmax(r) for  r in model.predict(X_test)])
match=(y_test == y_pred)
print(("Testing Accuracy = {}").format(np.sum(match)*100/match.shape[0]))

这里是预测代码:

model = load_model("C://Users//90544//OneDrive//Masaüstü//Yusuf// 
ödevler//kerasGiris//model_6cat_2.h6", compile = True)

  cap = cv2.VideoCapture(0)
  while 1:
    ret, frame = cap.read()
    if ret:
        frame = cv2.flip(frame, 1)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        frame = cv2.resize(frame, (256, 256))
        frameNp = image.img_to_array(frame)
        frameNp = np.expand_dims(frameNp, axis=0)

        predictions = model.predict(frameNp)
        print(predictions)

        cv2.imshow("frame", frameNp)

        k = cv2.waitKey(1) & 0xff
        if k == 27: break  # ESC pressed

    cap.release()
    cv2.destroyAllWindows()

ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 1 but received input with shape [None, 256, 256, 3]

我尝试更改从相机获取的图像的形状,但无法确定尺寸。

【问题讨论】:

    标签: python keras deep-learning neural-network


    【解决方案1】:

    你可以从这行告诉模型的输入形状:

    model.add(Conv2D(32,(3,3),activation='relu',input_shape=(256,256,1)))
    

    这条线表示模型根据 input_shape 参数获取形状为 (256, 256, 1) 的图像,因此模型期望获取该尺寸的图像。

    您的错误消息意味着您使用了形状为 (256, 256, 3) 的图像,并且预期为 1 而不是 3,因此您需要将通道值设为 1,如灰度图像而不是 3,即 BGR .

    在预测代码的while循环的第一行之后添加这一行:

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    

    此行将图像的通道从 BGR 更改为灰度,以匹配模型的输入大小通道和模型请求的输入形状。

    【讨论】:

    • 一个窗口打开但在 1 秒后关闭。我得到了这个错误。我也照你说的更新了代码。
    • 如果该用户解决了您最初的问题,您需要接受他的回答并针对您面临的下一个问题提出另一个问题
    • @NicolasGervais 我很确定我解决了他的 input_shape 问题,无论如何我尝试了第二个错误,谢谢提及。
    • 感谢您的帮助,正如您所说,我修复了第一个错误。我正在尝试修复第二个错误。
    • @codcod55 恕我直言,您应该使用新的错误消息发布一个不同的问题,我为您的第一条错误消息(输入形状错误)发布了一个答案并处理了它,请接受这个回答,因为它解决了你的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2020-08-04
    • 2023-03-19
    • 2021-12-17
    • 2021-08-23
    • 2021-08-05
    • 2021-09-03
    • 1970-01-01
    相关资源
    最近更新 更多