【问题标题】:Keras fit_generator with multiple input layers具有多个输入层的 Keras fit_generator
【发布时间】:2019-09-17 01:23:05
【问题描述】:

我正在尝试为具有 3 个输入和一个处理文本数据的单个输出的模型实现自定义数据生成器,如下所示:

# dummy model
input_1 = Input(shape=(None,))
input_2 = Input(shape=(None,))
input_3 = Input(shape=(None,))     
combined = Concatenate(axis=-1)([input_1, input_2, input_3])
...
dense_1 = Dense(10, activation='relu')(combined)
output_1 = Dense(1, activation='sigmoid')(dense_1)

model = Model([input_1, input_2, input_3], output_1)
print(model.summary())

#Compile and fit_generator
model.compile(optimizer='adam', loss='binary_crossentropy')

train_data_gen = Generator([x1_train, x2_train, x3_train], y_train, batch_size)
test_data_gen = Generator([x1_test, x2_test, x3_test], y_test, batch_size)

model.fit_generator(generator=train_data_gen, validation_data = test_data_gen, epochs=epochs, verbose=1)

我找到here的数据生成器代码,不知如何修改以接受多个输入张量。

class Generator(Sequence):
    # Class is a dataset wrapper for better training performance
    def __init__(self, x_set, y_set, batch_size=256):
        self.x, self.y = x_set, y_set
        self.batch_size = batch_size
        self.indices = np.arange(self.x.shape[0])

    def __len__(self):
        return math.floor(self.x.shape[0] / self.batch_size)

    def __getitem__(self, idx):
        inds = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]
        batch_x = self.x[inds]
        batch_y = self.y[inds]
        return batch_x, batch_y

    def on_epoch_end(self):
        np.random.shuffle(self.indices)

【问题讨论】:

标签: python keras deep-learning generator


【解决方案1】:

你需要做的就是修改Generator类如下。

class Generator(Sequence):
    # Class is a dataset wrapper for better training performance
    def __init__(self, x_set, y_set, batch_size=256):
        self.x, self.y = x_set, y_set
        self.batch_size = batch_size
        self.indices = np.arange(self.x[0].shape[0])

    def __len__(self):
        return math.floor(self.x[0].shape[0] / self.batch_size)

    def __getitem__(self, idx):
        inds = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]
        batch_x = [self.x[0][inds],self.x[1][inds],self.x[2][inds]]
        batch_y = self.y[inds]
        return batch_x, batch_y

    def on_epoch_end(self):
        np.random.shuffle(self.indices)

【讨论】:

    猜你喜欢
    • 2019-08-28
    • 2019-03-28
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多