keras GAN训练是loss不发生变化,accuracy一直为0.5

可能是激活层的激活方式与损失函数不匹配。

一般使用sigmoid,损失函数使用binary_crossentropy ;使用softmax,损失函数使用categorical_crossentropy。

作者:Yohanna
链接:https://www.zhihu.com/question/36307214/answer/364963552
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
 

  1. Binary Cross Entropy

常用于二分类问题,当然也可以用于多分类问题,通常需要在网络的最后一层添加sigmoid进行配合使用,其期望输出值(target)需要进行one hot编码,另外BCELoss还可以用于多分类问题Multi-label classification.

定义:
For brevity, let x = output, z = target. The binary cross entropy loss is
loss(x, z) = - sum_i (x[i] * log(z[i]) + (1 - x[i]) * log(1 - z[i]))

对应的代码为:

def binary_crossentropy(t,o):
    return -(t*tf.log(o+eps) + (1.0-t)*tf.log(1.0-o+eps))

2. Categorical cross-entropy

p are the predictions, t are the targets, i denotes the data point and j denotes the class.

适用于多分类问题,并使用softmax作为输出层的激活函数的情况。

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个简单的 Keras DCGAN 代码示例: ```python from keras.datasets import mnist from keras.models import Sequential, Model from keras.layers import Input, Dense, Reshape, Flatten, Dropout from keras.layers import Conv2D, Conv2DTranspose, LeakyReLU from keras.optimizers import Adam import numpy as np # 设置输入形状 img_rows = 28 img_cols = 28 channels = 1 img_shape = (img_rows, img_cols, channels) z_dim = 100 # 构建生成器模型 def build_generator(z_dim): model = Sequential() # 全连接层 model.add(Dense(128 * 7 * 7, input_dim=z_dim)) model.add(LeakyReLU(alpha=0.01)) model.add(Reshape((7, 7, 128))) # 转置卷积层 model.add(Conv2DTranspose(64, kernel_size=3, strides=2, padding='same')) model.add(LeakyReLU(alpha=0.01)) # 转置卷积层 model.add(Conv2DTranspose(1, kernel_size=3, strides=2, padding='same', activation='tanh')) return model # 构建鉴别器模型 def build_discriminator(img_shape): model = Sequential() # 卷积层 model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=img_shape, padding='same')) model.add(LeakyReLU(alpha=0.01)) # 卷积层 model.add(Conv2D(64, kernel_size=3, strides=2, input_shape=img_shape, padding='same')) model.add(LeakyReLU(alpha=0.01)) # 卷积层 model.add(Conv2D(128, kernel_size=3, strides=2, input_shape=img_shape, padding='same')) model.add(LeakyReLU(alpha=0.01)) # 扁平层 model.add(Flatten()) model.add(Dropout(0.4)) # 输出层 model.add(Dense(1, activation='sigmoid')) return model # 构建深度卷积生成对抗网络模型 def build_gan(generator, discriminator): model = Sequential() # 生成器 + 鉴别器 model.add(generator) model.add(discriminator) return model # 构建鉴别器模型 discriminator = build_discriminator(img_shape) # 编译鉴别器模型 discriminator.compile(loss='binary_crossentropy', optimizer=Adam(), metrics=['accuracy']) # 构建生成器模型 generator = build_generator(z_dim) # 保持鉴别器不可训练 discriminator.trainable = False # 构建深度卷积生成对抗网络模型 gan = build_gan(generator, discriminator) # 编译深度卷积生成对抗网络模型 gan.compile(loss='binary_crossentropy', optimizer=Adam()) # 加载 MNIST 数据集 (X_train, _), (_, _) = mnist.load_data() # 标准化输入数据 X_train = X_train / 127.5 - 1. X_train = np.expand_dims(X_train, axis=3) # 定义训练参数 batch_size = 64 epochs = 30000 sample_interval = 200 # 构建噪声向量 z = np.random.normal(0, 1, (batch_size, z_dim)) # 训练深度卷积生成对抗网络 for epoch in range(epochs): # --------------------- # 训练鉴别器 # --------------------- # 随机选择一个批次的真实图像 idx = np.random.randint(0, X_train.shape[0], batch_size) real_imgs = X_train[idx] # 生成假图像 noise = np.random.normal(0, 1, (batch_size, z_dim)) fake_imgs = generator.predict(noise) # 训练鉴别器 d_loss_real = discriminator.train_on_batch(real_imgs, np.ones((batch_size, 1))) d_loss_fake = discriminator.train_on_batch(fake_imgs, np.zeros((batch_size, 1))) d_loss = 0.5 * np.add(d_loss_real, d_loss_fake) # --------------------- # 训练生成器 # --------------------- # 生成噪声向量 noise = np.random.normal(0, 1, (batch_size, z_dim)) # 训练生成器 g_loss = gan.train_on_batch(noise, np.ones((batch_size, 1))) # 打印损失和准确率指标 print("%d [D loss: %f, acc.: %.2f%%] [G loss: %f]" % (epoch, d_loss[0], 100 * d_loss[1], g_loss)) # 保存生成的图片 if epoch % sample_interval == 0: # 生成噪声向量 noise = np.random.normal(0, 1, (1, z_dim)) # 生成假图像 gen_imgs = generator.predict(noise) # 反标准化输出图像 gen_imgs = 0.5 * gen_imgs + 0.5 # 保存生成的图像 plt.imshow(gen_imgs[0, :, :, 0], cmap='gray') plt.savefig("images/%d.png" % epoch) ``` 这个代码实现了一个简单的深度卷积生成对抗网络,用于生成 MNIST 数字图像。在训练过程中,它首先训练鉴别器,然后再训练生成器,以最小化鉴别器对假图像的判断。最后,它生成一些样本图像并将它们保存到磁盘上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值