【问题标题】:Keras Error with fit_generator: Error when checking target: expected softmax_1 to have shape (2,) but got array with shape (1,)带有 fit_generator 的 Keras 错误:检查目标时出错:预期 softmax_1 的形状为 (2,),但得到的数组的形状为 (1,)
【发布时间】:2020-06-29 21:45:41
【问题描述】:

我是使用 keras 的新手。我的数据集很大,所以我正在修改我的代码以批量工作。我的发电机在这里:

def batch_generator(csv_file,chunk_size,
                    steps, var_list):
    idx=1
    while True:
        yield load_data(csv_file,idx-1,chunk_size,var_list)## Yields data
        if idx<steps:
            idx+=1
        else:
            idx=1

def load_data(csv_file,idx,
              chunk_size, var_list):
    global col_names
    if idx == 0:
        df = pd.read_csv(
                  csv_file,
                  nrows=chunk_size)
        col_names = df.columns
    else:
    df = pd.read_csv(
                  csv_file, skiprows=idx*chunk_size,
                  nrows=chunk_size,
                  header=None,names = col_names)
    x = df[var_list]
    y = df['targets_LJ']
    return (np.array(x), to_categorical(y))

还有我代码的机器学习部分:

    #create iterator over dataframe
    train_gen = batch_generator(filepath_train, chunk_size, steps, list_of_vars)
    val_gen = batch_generator(filepath_val, chunk_size, steps_val, list_of_vars)

    # now make the network
    from keras.layers import Input, Dense, Softmax
    from keras.models import Model

    #layers are functions that construct the deep learning model
    #tensors define the data flow through the model
    input_tensor = Input(shape = (len(list_of_vars),))
    node1_layer = Dense(2)
    node1_tensor = node1_layer(input_tensor)
    output_layer = Softmax()
    output_tensor = output_layer(node1_tensor)

    #build model
    model = Model(input_tensor, output_tensor)
    model.compile(optimizer='rmsprop',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    #create early stopping for if the nn is not improving
    from keras.callbacks import EarlyStopping
    early_stop = EarlyStopping(monitor='val_loss', patience=2)

    #fit model
    history = model.fit_generator(generator=train_gen,
        validation_data=val_gen,
        steps_per_epoch=steps, epochs=args.epochs, validation_steps=steps_val, callbacks=[early_stop])

我收到了一个在我从 fit 切换到 fit_generator 之前没有收到的错误:

Traceback (most recent call last):
  File "./train_nn.py", line 162, in <module>
    run()
  File "./train_nn.py", line 145, in run
    steps_per_epoch=steps, epochs=args.epochs, validation_steps=steps_val, callbacks=[early_stop])
  File "/opt/ohpc/pub/packages/anaconda3/lib/python3.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "/opt/ohpc/pub/packages/anaconda3/lib/python3.7/site-packages/keras/engine/training.py", line 1418, in fit_generator
    initial_epoch=initial_epoch)
  File "/opt/ohpc/pub/packages/anaconda3/lib/python3.7/site-packages/keras/engine/training_generator.py", line 217, in fit_generator
    class_weight=class_weight)
  File "/opt/ohpc/pub/packages/anaconda3/lib/python3.7/site-packages/keras/engine/training.py", line 1211, in train_on_batch
    class_weight=class_weight)
  File "/opt/ohpc/pub/packages/anaconda3/lib/python3.7/site-packages/keras/engine/training.py", line 789, in _standardize_user_data
    exception_prefix='target')
  File "/opt/ohpc/pub/packages/anaconda3/lib/python3.7/site-packages/keras/engine/training_utils.py", line 138, in standardize_input_data
    str(data_shape))
ValueError: Error when checking target: expected softmax_1 to have shape (2,) but got array with shape (1,)

我不知道这有什么问题。我正在使用'categorical_crossentropy',但我的目标是明确的,据我所知,这些应该一起工作。

谢谢, 莎拉

【问题讨论】:

    标签: python keras generator softmax


    【解决方案1】:

    您的模型具有输出形状 (2,),因为您的最后一层有 2 个单位。
    既然你用的是"softmax",我猜你是在做二进制分类,对吧?

    但是您的数据具有(1,) 的形状,这意味着您没有两个类!!!你只有一门课。在通常的二元分类中,你得到的数据是零(一类)和一(另一类)

    如果是这种情况,您的最后一层必须仅包含 1 个单元。你最后一次激活应该是'sigmoid',你的损失应该是'binary_crossentropy'。这样您就无需更改数据。

    【讨论】:

    • 谢谢这个工作,一旦我理解它,当我摆脱了 to_categorical(y) 在我的 batch_generator 。但我不明白为什么在我拥有to_categorical(y) 之前它不起作用。因为当我手动检查 y 的形状为 (chunk_size,2) 时,to categorical 函数似乎按预期工作,但 Keras 将其视为具有 (1,) 的形状?我也不明白为什么Softmax() 层必须是第一个。
    • 好吧,错误信息很清楚,你有一个Dense(2) + softmax(模型需要形状(2,)),你有(batch,1)的数据。 ---- 但不幸的是,您的模型中有很多奇怪的层,我无法正确解释。 ----- 对于多类,您使用softmax + categorical_crossentropy,对于两个类,可以使用softmax 和shape (2,)。但也可以(并且更好)使用sigmoid + binary_crossentropy
    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 2019-01-16
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多