使用验证\u split,我在训练它时遇到了一个错误:传递到具有错误大小的模型的数组列表

2024-09-30 22:27:37 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图用keras训练一个模型时,我犯了以下错误。你知道吗

ValueError:检查模型输入时出错:传递给模型的Numpy数组列表的大小不是模型预期的大小。期望看到5个数组,但得到了以下1个数组的列表:

这是输入的形状:

 x_train shape: (231, 244, 1) | y_train shape: (231, 2)
 x_test shape : (432, 244, 1) | y_test shape : (432, 2)
 x_train_1: (231, 61, 1)
 x_train_2: (231, 61, 1)
 x_train_3: (231, 61, 1)
 x_train_4: (231, 61, 1)

这是我的模型:

def input_part(x_train):
    input_shape = x_train[0,:,:].shape
    model_input = Input(shape=input_shape)
    return model_input


def conv_pool(model_input: Tensor) -> training.Model:
    # 3 covs + 1 ave_pool + 3 covs + 1 ave_pool + flatten
    global_x = Dense(128, activation='relu')(x)
    return global_x


def cnn_p1(model_input: Tensor) -> training.Model:
    # 3 covs + 1 ave_pool + 3 covs + 1 ave_pool + flatten
    cnnpart_1 = Dense(128, activation='relu')(x)
    return cnnpart_1


def cnn_p2(model_input: Tensor) -> training.Model:
    # 3 covs + 1 ave_pool + 3 covs + 1 ave_pool + flatten
    cnnpart_2 = Dense(128, activation='relu')(x)
    return cnnpart_2


def cnn_p3(model_input: Tensor) -> training.Model:
    # 3 covs + 1 ave_pool + 3 covs + 1 ave_pool + flatten
    cnnpart_3 = Dense(128, activation='relu')(x)
    return cnnpart_3


def cnn_p4(model_input: Tensor) -> training.Model:
    # 3 covs + 1 ave_pool + 3 covs + 1 ave_pool + flatten
    cnnpart_4 = Dense(128, activation='relu')(x)
    return cnnpart_4


def ensemble(x_train):
    x_train_1, x_train_2, x_train_3, x_train_4 = np.split(x_train, 4, axis=1)

    model_input = input_part(x_train)
    model_input_1 = input_part(x_train_1)
    model_input_2 = input_part(x_train_2)
    model_input_3 = input_part(x_train_3)
    model_input_4 = input_part(x_train_4)


    conv_pool_model = conv_pool(model_input)
    cnn_p1_model = cnn_p1(model_input_1)
    cnn_p2_model = cnn_p1(model_input_2)
    cnn_p3_model = cnn_p1(model_input_3)
    cnn_p4_model = cnn_p1(model_input_4)

    conca = Concatenate(axis=0)([conv_pool_model, cnn_p1_model, cnn_p2_model, cnn_p3_model, cnn_p4_model])
    x = Dropout(0.5)(conca)
    x = Dense(2, activation='softmax')(x)
    model = Model(inputs = [model_input, model_input_1, model_input_2, model_input_3, model_input_4], outputs=x, name='conv_pool_cnn')
    return model

用于培训

def compile_and_train(model:training.Model, num_epochs: int, x_train, y_train) -> Tuple[History, str]:
    sgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=0, save_weights_only=True,
                             save_best_only=True, mode='auto', period=1)
    tensor_board = TensorBoard(log_dir='global2/', histogram_freq=0, batch_size=10)
    history = model.fit(x=x_train, y=y_train, batch_size=10, epochs=num_epochs, verbose=1,
                    callbacks=[checkpoint, tensor_board],
                    validation_split=0.2, shuffle=True)
    weight_files = glob.glob(os.path.join(os.getcwd(), 'global/*'))
    weight_file = max(weight_files, key=os.path.getctime)
    return history, weight_file

上面有错误的地方是:

history = model.fit(x=x_train, y=y_train, batch_size=10, epochs=num_epochs, verbose=1,
                    callbacks=[checkpoint, tensor_board],
                    validation_split=0.2, shuffle=True)

我得到这个错误:

Traceback (most recent call last):

File "D:/Users/11825/source/repos/mutil cnn/ensembling_CNN.py", line 191, in <module>
history, cnn_weight_file = compile_and_train(cnn_pool_model, NUM_EPOCHS, x_train, y_train)  

File "D:/Users/11825/source/repos/mutil cnn/ensembling_CNN.py", line 156, in compile_and_train
validation_split=0.2, shuffle=True)

ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 5 array(s), but instead got the following list of 1 arrays: 

Tags: inputmodelreturndeftrainingtraincnnpool
2条回答

当您在模型中使用多个输入时,您需要将您的输入作为一个列表提供,其中包含数据的不同部分。您可以像这样在compile_and_train中更改代码,只需在model.fit之前添加一行即可。你知道吗

new_x_train = [x_train[i,:,:] for i in 5]
history = model.fit(x=new_x_train, y=y_train, batch_size=10, epochs=num_epochs, 
                verbose=1,
                callbacks=[checkpoint, tensor_board],
                validation_split=0.2, shuffle=True)

因为您在模型中定义了4个输入。您需要在fit方法中提供一个包含4个输入的列表。方法可能是

model.fit(x=[x_train_1, x_train_2, x_train_3, x_train_4], ...)

相关问题 更多 >