如何在Python中使用Keras函数式API进行交叉验证

我想对一个具有多个输入的Keras模型进行交叉验证。因此,我尝试了KerasClassifier。这对于只有一个输入的普通顺序模型来说运行良好。然而,当使用函数式API并扩展到两个输入时,sklearn的cross_val_predict似乎无法按预期工作。

def create_model():    input_text = Input(shape=(1,), dtype=tf.string)    embedding = Lambda(UniversalEmbedding, output_shape=(512, ))(input_text)    dense = Dense(256, activation='relu')(embedding)        input_title = Input(shape=(1,), dtype=tf.string)    embedding_title = Lambda(UniversalEmbedding, output_shape=(512, ))(input_title)    dense_title = Dense(256, activation='relu')(embedding_title)        out = Concatenate()([dense, dense_title])    pred = Dense(2, activation='softmax')(out)    model = Model(inputs=[input_text, input_title], outputs=pred)    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])    return model

失败的交叉验证代码

keras_classifier = KerasClassifier(build_fn=create_model, epochs=10, batch_size=10, verbose=1)cv = StratifiedKFold(n_splits=10, random_state=0)results = cross_val_predict(keras_classifier, [X1, X2], y, cv=cv, method = "predict_proba")

后来,我发现KerasClassifier仅支持顺序模型:https://keras.io/scikit-learn-api/。换句话说,它不支持具有多个输入的函数式API。

因此,我想知道是否有其他方法可以对使用Keras函数式API的模型进行交叉验证。更具体地说,我希望获得每个数据实例的预测概率(当它在交叉验证中的测试切片时) – 这正是cross_val_predict所做的。

如果需要,我很乐意提供更多细节。

编辑:我当前的问题是如何将多个输入输入到StratifiedKFold.split()。我在代码中放了????????????。只是在想是否可以将其作为[input1, input2, input3, input4, input5]提供

假设,我有5个输入作为input1input2input3input4input5,我如何在StratifiedKFold.split()中使用这些输入

k_fold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0)for train_index, test_index in k_fold.split(????????????, labels):    print("iteration", i, ":")    print("train indices:", train_index)    #input1    print("train data:", input1[train_index])    #input2    print("train data:", input2[train_index])    #input3    print("train data:", input3[train_index])    #input4    print("train data:", input1[train_index])    #input5    print("train data:", input1[train_index])    print("test indices:", test_index)    print("test data:", X[test_index])

回答:

有趣的是,sklearn仅支持Sequential,但看你的模型,我认为你可以有一个单一的输入,因为它们共享嵌入等:

def create_model():    model = Sequential()    model.add(Lambda(UniversalEmbedding, output_shape=(2, 512), input_shape=(2,)))    # (2, 512)    model.add(Flatten()) # (2*512)    model.add(Dense(2*256, activation='relu')) # (2*256)    model.add(Dense(2, activation='softmax'))    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])    return model

换句话说,你有两个相同领域的输入,以相同的方式嵌入,所以你可以使用大小为2的单一输入。然后,为了模拟两个密集层,你可以展平并使用一个大小是两倍的单一Dense层 🙂 这将你带到连接层,从那里开始模型是相同的。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注