在Keras中實現GAN(生成對抗網絡),需要分為兩個部分:生成器(Generator)和判別器(Discriminator)。以下是一個簡單的GAN實現示例:
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import Adam
def build_generator(input_dim, output_dim):
model = Sequential()
model.add(Dense(128, input_dim=input_dim))
model.add(Activation('relu'))
model.add(Dense(output_dim))
model.add(Activation('sigmoid'))
return model
def build_discriminator(input_dim):
model = Sequential()
model.add(Dense(128, input_dim=input_dim))
model.add(Activation('relu'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
return model
input_dim = 100 # 生成器輸入維度
output_dim = 784 # 生成器輸出維度(MNIST圖像大小)
generator = build_generator(input_dim, output_dim)
generator.compile(loss='binary_crossentropy', optimizer='adam')
input_dim = 784 # 判別器輸入維度
discriminator = build_discriminator(input_dim)
discriminator.compile(loss='binary_crossentropy', optimizer='adam')
gan = Sequential([generator, discriminator])
discriminator.trainable = False
gan.compile(loss='binary_crossentropy', optimizer='adam')
# 省略數據準備部分
for epoch in range(epochs):
noise = np.random.normal(0, 1, (batch_size, input_dim))
generated_images = generator.predict(noise)
real_labels = np.ones((batch_size, 1))
fake_labels = np.zeros((batch_size, 1))
discriminator.trainable = True
d_loss_real = discriminator.train_on_batch(real_images, real_labels)
d_loss_fake = discriminator.train_on_batch(generated_images, fake_labels)
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
noise = np.random.normal(0, 1, (batch_size, input_dim))
gan_labels = np.ones((batch_size, 1))
discriminator.trainable = False
g_loss = gan.train_on_batch(noise, gan_labels)
# 打印損失等信息
以上是一個簡單的GAN實現示例,實際應用中可能需要根據具體問題進行調整和優化。GAN的訓練比較復雜,需要仔細調整超參數和網絡結構,以獲得最佳的生成效果。