如何在Keras中为自动编码器改编训练数据

时间:2019-09-21 23:09:34

标签: python tensorflow machine-learning keras deep-learning

我在Keras中使用了自动编码器。我希望改组训练数据x_train,以便自动编码器将数据重构为来自同一类的不同样本。这可能吗?

model_train = autoencoder.fit(x_train, x_train,
          batch_size=32,
          epochs=1000,
          shuffle=True,
          callbacks=[checkpoint, early_stopping],
          validation_data=(x_test, x_test))

我认为shuffle=True正在改组x_train并根据 same 对计算损失,而这不是我想要的。

1 个答案:

答案 0 :(得分:1)

这是可能的,但是Keras不会为您做到这一点,因为它将数据和标签混在一起。假设您有标签,我发现此功能对于您的目的非常有用:

import numpy as np

def create_pairs(data, labels):
    # Exclude batch dimension
    pairs = np.empty(0, 2, *data.shape[1:])

    for label in np.unique(labels):
        idxs = np.where(labels == label)[0]
        # Indexes must be even in order to create pairs
        idxs = idxs if len(idxs) % 2 == 0 else idxs[:-1]
        np.random.shuffle(idxs)

        samples = data[idxs].reshape((-1, 2, *data.shape[1:]))
        pairs = np.vstack((pairs, samples))
    return pairs[:, 0], pairs[:, 1]

现在,数据被重新整理并分成几对,您可以训练模型了:

x_train, y_train = create_pairs(data, labels)
history = model.fit(
    x_train, y_train,
    batch_size=32,
    epochs=1000,
    shuffle=True,
    callbacks=[checkpoint, early_stopping],
    validation_split=0.2)