gpt4 book ai didi

python - 具有多个输入层的 Keras fit_generator

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:07 27 4
gpt4 key购买 nike

我正在尝试为具有 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)

最佳答案

您需要做的就是如下修改 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)

关于python - 具有多个输入层的 Keras fit_generator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55886074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com