TF2를 사용한 간단한 GAN 네트워크 데모
18725 단어 tensorflowkeraspythongan
내 게시물의 이 예에서 REAL 아티스트는 자신의 스타일로 멋진 "그림"을 그릴 수 있습니다. 이 그림은 아래 그림의 회색 영역 안에 있고 파란색 및 빨간색 포물선과 평행한 포물선입니다.
그런 다음 생성자와 판별자가 정의된 GAN 네트워크를 소개합니다. Generator 모델은 가능한 한 아티스트의 작품을 시뮬레이션하려고 합니다. 이 생성기 모델의 구조는 다음과 같습니다.
반대로 Discriminator 모델은 생성된 그림과 REAL 그림을 구별하기 위해 최선을 다해야 합니다. 그 구조는 아래와 같습니다.
이제 코딩을 시작하겠습니다.
먼저 의존성. 하나는 tensorflow 2, numpy 및 matplotlib가 설치되어 있어야 합니다.
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "2"
import tensorflow as tf2
import tensorflow.keras as keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
import tensorflow.keras.backend as K
import numpy as np
import matplotlib.pyplot as plt
print("TF version: ", tf2.__version__)
몇 가지 중요한 하이퍼 매개변수.
# Hyper Parameters
BATCH_SIZE = 32
LR_G = 0.0001 # learning rate for generator
LR_D = 0.0001 # learning rate for discriminator
N_IDEAS = 5 # think of this as number of ideas for generating an art work (Generator)
ART_COMPONENTS = 15 # it could be total point G can draw in the canvas
PAINT_POINTS = np.vstack([np.linspace(-1, 1, ART_COMPONENTS) for _ in range(BATCH_SIZE)])
이 함수는 실제 아티스트의 그림 작품을 반환합니다.
# return painting of the famous artist (real target)
def artist_works():
a = np.random.uniform(1, 2, size=BATCH_SIZE)[:, np.newaxis]
paintings = a * np.power(PAINT_POINTS, 2) + (a-1)
# print("Shape of paitings: ", paintings.shape)
return paintings
이제 모델과 옵티마이저가 있습니다.
model_G = Sequential([
Dense(128, activation="relu",input_shape=(None, N_IDEAS)),
Dense(ART_COMPONENTS)
])
model_D = Sequential([
Dense(128, activation="relu", input_shape=(None, ART_COMPONENTS)),
Dense(1, activation="sigmoid"),
])
opt_D = keras.optimizers.Adam(model_D.variables, lr=LR_D)
opt_G = keras.optimizers.Adam(model_G.variables, lr=LR_G)
마지막으로 훈련 부분과 줄거리가 채워집니다.
plt.ion() # something about continuous plotting
for step in range(10000):
artist_paintings = artist_works() # real painting from artist
G_ideas = np.random.randn(BATCH_SIZE, N_IDEAS)
with tf2.GradientTape(persistent=True) as tape:
G_paintings = model_G(G_ideas) # fake painting from model G (random ideas)
prob_artist1 = model_D(G_paintings) # model D computes the prob for assessing if G_paintings are real
G_loss = K.mean(K.log(1. - prob_artist1)) # loss function of G model
prob_artist0 = model_D(artist_paintings) # D try to increase this prob for real paitings
prob_artist1 = model_D(G_paintings) # D try to reduce this prob for generated paitings
D_loss = - K.mean(K.log(prob_artist0) + K.log(1. - prob_artist1)) # loss function of G model
L_gradx = tape.gradient(G_loss, model_G.variables)
opt_G.apply_gradients(grads_and_vars=zip(L_gradx, model_G.variables))
L_gradx2 = tape.gradient(D_loss, model_D.variables)
opt_D.apply_gradients(grads_and_vars=zip(L_gradx2, model_D.variables))
if step % 50 == 0: # plotting
plt.cla()
plt.plot(PAINT_POINTS[0], G_paintings[0], c='#4AD631', lw=3, label='Generated painting',)
plt.plot(PAINT_POINTS[0], 2 * np.power(PAINT_POINTS[0], 2) + 1, c='#74BCFF', lw=3, label='upper bound')
plt.plot(PAINT_POINTS[0], 1 * np.power(PAINT_POINTS[0], 2) + 0, c='#FF9359', lw=3, label='lower bound')
plt.text(-.5, 2.3, 'D accuracy=%.2f (0.5 for D to converge)' % K.mean(prob_artist0), fontdict={'size': 13})
plt.text(-.5, 2, 'D score= %.2f (-1.38 for G to converge)' % -D_loss, fontdict={'size': 13})
plt.ylim((0, 3));plt.legend(loc='upper right', fontsize=10);plt.draw();plt.pause(0.01)
print("Current step: {}".format(step))
plt.ioff()
plt.show()
시뮬레이션 그림이 어떻게 발전하는지 확인하십시오.
우리가 볼 수 있듯이 훈련 단계가 증가함에 따라 녹색의 "생성된 그림"은 점점 더 현실적이 됩니다. 상한 및 하한 포물선과 매우 평행해지고 한계 내에 유지됩니다.
Reference
이 문제에 관하여(TF2를 사용한 간단한 GAN 네트워크 데모), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/jemaloqiu/simple-gan-network-demo-using-tf2-dg9텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)