GAN-cls是一種GAN網絡增強技術——具有匹配感知的判別器。在中,使用了ACGAN的方式進行指導模擬數據與生成數據的對應關系。在GAN-cls中該效果會以更簡單的方式來實現,即增強判別器的功能,令其不僅能判斷圖片的真偽,還能判斷匹配真偽。
一、GAN-cls的具體實現
GAN-cls具體做法是,在原有GAN網絡上,將判別器的輸入變為圖片與對應標簽的連接數據。這樣判別器的輸入特征中就會有生成圖像的特征與對應標簽的特征。然后用這樣的判別器分別對真實標簽與真實圖片、假標簽與真實圖片、真實標簽與假圖片進行判斷,預期結果為真、假、假網絡增強器有用嗎,在訓練過程中沿這個方向收斂即可。對于生成器不需要作出改變。
二、實例92:使用GNA-cls技術實現生成標簽匹配的模擬數據 實例描述
使用GAN-cls技術對判別器進行改造網絡增強器有用嗎,并通過輸入錯誤的樣本標簽讓判別器學習樣本與標簽的匹配,從而優化生成器,是生成器最終生成與標簽一樣的樣本,實現與ACGAN同等的效果。
1.修改判別器
將判別器的輸入改成x與y,新增加的y代表輸入的標簽;在內部處理中,先通過全連接網絡將y變成與圖片一樣維度的映射,并調整為圖片相同的形狀,使用將二者連接到一起統一處理。后續的處理過程是一樣的,兩個卷積后再連接連接兩個全連接,最后輸出disc。
def discriminator(x,y): #x是正圖片,y是標簽
reuse = len([t for t in tf.global_variables() if t.name.startswith('discriminator')]) > 0
with tf.variable_scope('discriminator', reuse=reuse):
# 通過一個全連接層將y標簽轉換成與x一樣的維度
y = slim.fully_connected(y, num_outputs=n_input, activation_fn = leaky_relu)
y = tf.reshape(y, shape=[-1, 28, 28, 1])
x = tf.reshape(x, shape=[-1, 28, 28, 1])
x= tf.concat(axis=3, values=[x,y])
# 兩個卷積層+兩個全連接層
x = slim.conv2d(x, num_outputs = 64, kernel_size=[4,4], stride=2, activation_fn=leaky_relu)
x = slim.conv2d(x, num_outputs=128, kernel_size=[4,4], stride=2, activation_fn=leaky_relu)

x = slim.flatten(x)
shared_tensor = slim.fully_connected(x, num_outputs=1024, activation_fn = leaky_relu)
disc = slim.fully_connected(shared_tensor, num_outputs=1, activation_fn=tf.nn.sigmoid)
disc = tf.squeeze(disc, -1)
return disc
2.添加錯誤而標簽輸入符,構建網絡結構
添加錯誤標簽misy,同時在判別器中分別將真實樣本與真實標簽、生成的圖片gen與真實標簽、真實樣本與錯誤標簽組成輸入傳入到判別器中。
這里將3中輸入的x與y分別按照維度連接為判別器的輸入。生成結果后再使用split函數將其裁為3個結果、和,分別代表真實樣本與真實標簽、生成的圖像gen與真實標簽、真實樣本與錯誤標簽所對應的判別值。
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.int32, [None]) #正確的標簽
misy = tf.placeholder(tf.int32, [None]) #錯誤的標簽
z_rand = tf.random_normal((batch_size, rand_dim))#38列
z = tf.concat(axis=1, values=[tf.one_hot(y, depth = classes_dim), z_rand])#50列
gen = generator(z)

genout= tf.squeeze(gen, -1)
# 判別器
xin=tf.concat([x, tf.reshape(gen, shape=[-1,784]),x],0)
yin=tf.concat([tf.one_hot(y, depth = classes_dim),tf.one_hot(y, depth = classes_dim),tf.one_hot(misy, depth = classes_dim)],0)
disc_all = discriminator(xin,yin)
disc_real,disc_fake,disc_mis =tf.split(disc_all,3)
loss_d = tf.reduce_sum(tf.square(disc_real-1) + ( tf.square(disc_fake)+tf.square(disc_mis))/2 )/2
loss_g = tf.reduce_sum(tf.square(disc_fake-1))/2
在計算判別器的loss時,同時使用LSGAN方式,并且將錯誤部分的loss變成與的和,然后除以2。因為對于生成器生成的樣本與錯誤的標簽輸入,判別器都應該判別錯誤。
3.使用sion創建開始訓練
定義,使用sion創建,來管理檢查點文件,在中構建錯誤標簽數據,訓練模型。
gen_global_step = tf.Variable(0, trainable=False)

global_step = tf.train.get_or_create_global_step()#使用MonitoredTrainingSession,必須有
train_disc = tf.train.AdamOptimizer(0.0001).minimize(loss_d , var_list = d_vars, global_step = global_step)
train_gen = tf.train.AdamOptimizer(0.001).minimize(loss_g , var_list = g_vars, global_step = gen_global_step)
training_epochs = 3
display_step = 1
with tf.train.MonitoredTrainingSession(checkpoint_dir='log/checkpointsnew',save_checkpoint_secs =60) as sess:
total_batch = int(mnist.train.num_examples/batch_size)
print("global_step.eval(session=sess)",global_step.eval(session=sess),int(global_step.eval(session=sess)/total_batch))
for epoch in range( int(global_step.eval(session=sess)/total_batch),training_epochs):
avg_cost = 0.

# 遍歷全部數據集
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)#取數據
_, mis_batch_ys = mnist.train.next_batch(batch_size)#取數據
feeds = {x: batch_xs, y: batch_ys,misy:mis_batch_ys}
# Fit training using batch data
l_disc, _, l_d_step = sess.run([loss_d, train_disc, global_step],feeds)
l_gen, _, l_g_step = sess.run([loss_g, train_gen, gen_global_step],feeds)
# 顯示訓練中的詳細信息
if epoch % display_step == 0:
print("Epoch:", 'd' % (epoch + 1), "cost=", "{:.9f} ".format(l_disc),l_gen)
print("完成!")
# 測試

_, mis_batch_ys = mnist.train.next_batch(batch_size)
print ("result:", loss_d.eval({x: mnist.test.images[:batch_size],y:mnist.test.labels[:batch_size],misy:mis_batch_ys},session = sess)
, loss_g.eval({x: mnist.test.images[:batch_size],y:mnist.test.labels[:batch_size],misy:mis_batch_ys},session = sess))
# 根據圖片模擬生成圖片
show_num = 10
gensimple,inputx,inputy = sess.run(
[genout,x,y], feed_dict={x: mnist.test.images[:batch_size],y: mnist.test.labels[:batch_size]})
f, a = plt.subplots(2, 10, figsize=(10, 2))
for i in range(show_num):
a[0][i].imshow(np.reshape(inputx[i], (28, 28)))
a[1][i].imshow(np.reshape(gensimple[i], (28, 28)))
plt.draw()
plt.show()