鱼C论坛

 找回密码
 立即注册
查看: 1112|回复: 2

Keras搭建LSTM:调用fit()时明明传入了两个array却报错称只传了一个?

[复制链接]
发表于 2020-8-7 18:16:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 猪仔很忙 于 2020-8-8 20:36 编辑

求助。如代码所示,模型有两个输入,在fit时validation_data分别传入了val_data、val_labels,shape与两个模型的输入相同,分别为(834,10,7)、(834,1):
def get_loss(y_true, y_pred):
    pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
    pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
    return -K.mean(0.75 * K.pow(1. - pt_1, 0) * K.log(pt_1)) - K.mean((1 - 0.75) * K.pow(pt_0, 0) * K.log(1. - pt_0))


def get_adversary(args):
    y_true = args[0]
    y_pred = args[1]
    v_final = args[2]
    loss = get_loss(y_true, y_pred)
    perturb = tf.gradients(loss, [v_final])[0]
    v_final_adv = tf.add(v_final, perturb)
    return v_final_adv


def my_loss(args):
    y_true = args[0]
    pred = args[1]
    adv_pred = args[2]
    loss1 = get_loss(y_true, pred)
    loss2 = get_loss(y_true, adv_pred)
    return loss1 + 0.1 * loss2


def _build_model(time_step, feature_dim, modelName):
    trace_input = Input(shape=(time_step, feature_dim), name='trace')
    label_input = Input(shape=(1,), name='label')

    if modelName == 'FEMT_LSTM':
        v_final = RNN_SEPARATE_2(time_step, feature_dim)(trace_input)
    else:
        v_final = RNN(time_step, feature_dim)(trace_input)

    pred = Dense(1, activation='sigmoid')(v_final)
    v_final_adv = Lambda(get_adversary, output_shape=(256,))([label_input, pred, v_final])
    adv_pred = Dense(1, activation='sigmoid')(v_final_adv)

    loss = Lambda(my_loss, name='loss')([label_input, pred, adv_pred])
    model = Model(inputs=[trace_input, label_input], outputs=[loss])

    loss_layer = model.get_layer('loss').output
    model.add_loss(loss_layer)

    model.compile(optimizer=optimizers.Adam(lr=0.001, clipvalue=15))
    return model


def build_train(data, machineID, modelName):
    train_data, train_labels, val_data, val_labels, test_data, test_labels = data

    num_samples = train_data.shape[0]
    time_step = train_data.shape[1]
    feature_dim = train_data.shape[2]

    model = _build_model(time_step, feature_dim, modelName)

    print('Train...')
    model_save_path = './lib/model_cp_adv_rnn_{}'.format(machineID)

    call_backs = [Call_back_0(valid_data=[val_data, val_labels, test_data, test_labels],  # test_data, test_labels
                              model_save_path=model_save_path),
                  ReduceLROnPlateau(monitor='val_loss', factor=0.8, patience=4, mode='min'),  # 4
                  ModelCheckpoint(filepath=model_save_path, monitor='val_loss', save_best_only=True,
                                  save_weights_only=True, mode='min')]

    model.fit({'trace': train_data, 'label': train_labels},
              batch_size=64,
              epochs=30,  # 30 60
              callbacks=call_backs,
              validation_data=(val_data, val_labels))
却出现报错:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "D:\JetBrains\PyCharm 2020.1.2\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "D:\JetBrains\PyCharm 2020.1.2\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "D:/PycharmProjects/turningpoint-master/main.py", line 67, in <module>
    modelName=modelName)
  File "D:\PycharmProjects\turningpoint-master\baseline_main_rnn.py", line 37, in train_rnn_turning_point
    clf = rnn_turning_point.build_train(data, machineID, modelName)
  File "D:\PycharmProjects\turningpoint-master\model\rnn_turning_point.py", line 86, in build_train
    validation_data=[val_data, val_labels])
  File "D:\Anaconda3\envs\edogawaAi\lib\site-packages\keras\engine\training.py", line 972, in fit
    batch_size=batch_size)
  File "D:\Anaconda3\envs\edogawaAi\lib\site-packages\keras\engine\training.py", line 751, in _standardize_user_data
    exception_prefix='input')
  File "D:\Anaconda3\envs\edogawaAi\lib\site-packages\keras\engine\training_utils.py", line 102, in standardize_input_data
    str(len(data)) + ' arrays: ' + str(data)[:200] + '...')
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 2 array(s), but instead got the following list of 1 arrays: [array([[[0.23777019, 0.30065992, 0.37679494, ..., 0.32888769,
         0.69490097, 0.37461882],
        [0.39814235, 0.25375877, 0.20461036, ..., 0.18472258,
         0.62059676, 0.65594323],
       ...
明明传入了两个输入集,却报错称少了一个,无法理解,希望有人能指点迷津。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-8-7 19:56:47 | 显示全部楼层
没看懂你的问题
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-7 20:07:04 | 显示全部楼层
71行validation_data那儿需要两个array,报错显示我少传入了一个,但是我明明已经传了两个,分别是val_data, val_labels
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-1-19 14:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表