GAN的小測試

2021-08-22 04:54:55 字數 3510 閱讀 7349

參考部落格

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

tf.set_random_seed(1)

np.random.seed(1)

# 設定超引數

batch_size = 64 # 批量大小

lr_g = 0.0001 # 生成器的學習率

lr_d = 0.0001 # 判別器的學習率

n_ideas = 5 # 認為這是生成藝術作品的幾個想法(生成器)

art_components = 15 # 在畫上畫多少個點

#列表解析式代替了for迴圈,paint_points.shape=(64,15),

#np.vstack()預設逐行疊加(axis=0)

paint_points = np.vstack([np.linspace(-1, 1, art_components) for _ in range(batch_size)])

def artist_works():

#a為64個1到2均勻分布抽取的值,shape=(64,1)

a = np.random.uniform(1, 2, size=batch_size)[:, np.newaxis]

paintings = a * np.power(paint_points, 2) + (a-1)

return paintings

with tf.variable_scope('generator'):

g_in = tf.placeholder(tf.float32, [none, n_ideas]) # 隨機的ideals(**於正態分佈)

g_l1 = tf.layers.dense(g_in, 256, tf.nn.relu)

g_l2 = tf.layers.dense(g_l1, 128, tf.nn.relu)

g_out = tf.layers.dense(g_l2, art_components) # 得到15個點

with tf.variable_scope('discriminator'):

real_art = tf.placeholder(tf.float32, [none, art_components], name='real_in') # 接受專家的畫

d_l0 = tf.layers.dense(real_art, 256, tf.nn.relu, name='l')

d_l1 = tf.layers.dense(d_l0, 128, tf.nn.relu, name='l1')

prob_artist0 = tf.layers.dense(d_l1, 1, tf.nn.sigmoid, name='out') # 代入專家的畫,判別器判斷這副畫來自於專家的概率

# 再次利用生成器生成的15個點

d_l2 = tf.layers.dense(g_out, 256, tf.nn.relu, name='l', reuse=true)

d_l3 = tf.layers.dense(d_l2, 128, tf.nn.relu, name='l1',reuse=true) # 接受業餘畫家的畫

prob_artist1 = tf.layers.dense(d_l3, 1, tf.nn.sigmoid, name='out', reuse=true) # 代入生成的畫,判別器判斷這副畫來自於專家的概率

d_loss = -tf.reduce_mean(tf.log(prob_artist0) + tf.log(1-prob_artist1))#

g_loss = tf.reduce_mean(tf.log(1-prob_artist1))

train_d = tf.train.adamoptimizer(lr_d).minimize(

d_loss, var_list=tf.get_collection(tf.graphkeys.trainable_variables, scope='discriminator'))

train_g = tf.train.adamoptimizer(lr_g).minimize(

g_loss, var_list=tf.get_collection(tf.graphkeys.trainable_variables, scope='generator'))

sess = tf.session()

sess.run(tf.global_variables_initializer())

plt.ion() # 連續畫圖

for step in range(4000):

artist_paintings = artist_works() # 專家的畫

g_ideas = np.random.randn(batch_size, n_ideas)

g_paintings, pa0, pa1, dl = sess.run([g_out, prob_artist0, prob_artist1,d_loss, train_d, train_g], )[:4] # 訓練和獲取結果

if step % 50 == 0: # 每50步訓練畫一次圖

GAN學習系列2 GAN的起源

本文大約 5000 字,閱讀大約需要 10 分鐘 這是 gan 學習系列的第二篇文章,這篇文章將開始介紹 gan 的起源之作,鼻祖,也就是 ian goodfellow 在 2014 年發表在 iclr 的 generative adversarial networks 當然由於數學功底有限,所以會...

gan網路損失函式 GAN的損失函式

理解生成對抗網路的關鍵在於理解gan的損失函式 js散度 gan實際是通過對先驗分布施加乙個運算g,來擬合乙個新的分布 如果從傳統的判別式網路的思路出發,只要選定合適的loss,就可以使生成分布和真實分布之間的距離盡可能逼近 kl散度經常用來衡量分布之間距離 但kl散度是不對稱的。不對稱意味著,對於...

GAN裡面的乙個小坑

log sigmoid f x log 1 exp f x softplus f x log 1 sigmoid f x log 1 exp f x softplus f x thus,softplus f x softplus f x represents the same objective a...