class DCGAN():
def train(self, epochs,data, batch_size = 128, save_interval = 5):
X_train = np.expand_dims(data, axis=3
X_train = X_train/127.5 -1. #区间【-1,1】
valid = np.ones((batch_size, 1))
fake = np.zeros((batch_size, 1))
num_batches = X_train.shape[0] // batch_size
for epoch in range(epochs):
for batch in range(num_batches):
batch_start = batch * batch_size
batch_end = (batch + 1) * batch_size
imgs = X_train[batch_start:batch_end]
if len(imgs) < batch_size:
continue
noise = np.random.normal(0,1,(batch_size, self.latent_dim))#(128 ,100)
gen_imgs = self.generator.predict(noise)
d_loss_real = self.discriminator.train_on_batch(imgs, valid)
d_loss_fake = self.discriminator.train_on_batch(gen_imgs, fake)
discriminator_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
g_loss = self.combined.train_on_batch(noise, valid)
del imgs, noise, gen_imgs,d_loss_real,d_loss_fake,discriminator_loss,g_loss
这是训练代码,数据集贼小
def train(self, epochs,data, batch_size = 128, save_interval = 5):
X_train = np.expand_dims(data, axis=3
X_train = X_train/127.5 -1. #区间【-1,1】
valid = np.ones((batch_size, 1))
fake = np.zeros((batch_size, 1))
num_batches = X_train.shape[0] // batch_size
for epoch in range(epochs):
for batch in range(num_batches):
batch_start = batch * batch_size
batch_end = (batch + 1) * batch_size
imgs = X_train[batch_start:batch_end]
if len(imgs) < batch_size:
continue
noise = np.random.normal(0,1,(batch_size, self.latent_dim))#(128 ,100)
gen_imgs = self.generator.predict(noise)
d_loss_real = self.discriminator.train_on_batch(imgs, valid)
d_loss_fake = self.discriminator.train_on_batch(gen_imgs, fake)
discriminator_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
g_loss = self.combined.train_on_batch(noise, valid)
del imgs, noise, gen_imgs,d_loss_real,d_loss_fake,discriminator_loss,g_loss
这是训练代码,数据集贼小