정성훈
    파이썬과 케라스로 배우는 강화학습이 5장) 텐서플로 2.0과 케라스
MNIST_tf2.png [8 KB]   MNIST_tf2.ipynb [6 KB]  




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Dense
 
class Model(tf.keras.Model):
  def __init__(self):
    super(Model, self).__init__()
    self.input_layer = Dense(256, activation='relu', input_shape=(784,))
    self.hidden_layer = Dense(128, activation='relu')
    self.output_layer = Dense(10, activation='softmax')
 
  def call(self, x):
    x = self.input_layer(x)
    x = self.hidden_layer(x)
    output = self.output_layer(x)
    return output
 
if __name__ == "__main__":
  # 모델, 오류함수, 옵티마이저 생성
  model = Model()
  cross_entropy = tf.keras.losses.CategoricalCrossentropy(from_logits=False)
  optimizer = Adam(1e-4)
 
  # 데이터 불러오기
  mnist = tf.keras.datasets.fashion_mnist
  (x_train, y_train), (x_test, y_test) = mnist.load_data()
  # 0~255 범위의 픽셀값을 0~1로 노멀라이즈
  x_train, x_test = x_train / 255.0, x_test / 255.0
 
# 미니배치 사이즈 설정
batch_size = 32
num_train_data = x_train.shape[0]
num_test_data = x_test.shape[0]
 
num_epoch = 10
for e in range(num_epoch):
  # 1 에포크 동안 훈련 진행
  for i in range(num_train_data // batch_size):
    # 미니 배치 하나만큼 데이터 가져오기
    x_batch = x_train[i * batch_size:(i + 1) * batch_size]
    y_batch = y_train[i * batch_size:(i + 1) * batch_size]
    # (batch_size, 28, 28) -> (batch_size, 28, 28, 1)로 shape 변경
    x_batch = x_batch.reshape(-1, 28*28)
    # 정답을 one-hot encoding으로 변경
    y_batch = tf.one_hot(y_batch, 10)
 
    # 계산 과정을 기록하기 위한 tape scope 선언
    model_params = model.trainable_variables
    with tf.GradientTape() as tape:
      # 모델을 통한 예측
      predicts = model(x_batch)
      # 오류함수 계산
      losses = cross_entropy(predicts, y_batch)
    # tape를 통한 그레이디언트 계산
    grads = tape.gradient(losses, model_params)
    # 계산한 그레이디언트를 통해 모델을 업데이트
    optimizer.apply_gradients(zip(grads, model_params))
 
x_test = x_test.reshape(-1, 28*28)
predicts = model(x_test)
corrects = tf.equal(tf.argmax(predicts, 1), y_test)
accuracy = tf.reduce_mean(tf.cast(corrects, tf.float32), axis=-1)
print("accuracy=%f"%accuracy)
 
 
 
cs

  등록일 : 2021-11-05 [23:32] 조회 : 629 다운 : 632   
 
△ 이전글바닥부터 배우는 강화 학습 코드 (github)
▽ 다음글파이썬과 케라스로 배우는 강화학습이 5장) 텐서플로 2.0과 케라스
강화학습 실습
번호 ⓒ 제 목 이름
강화학습 - 기초 개념부터 최신 알고리즘까지 이론과 실습을 통해 응용으로...
바닥부터 배우는 강화 학습 코드 (github)
강화학습/심층강화학습 특강 (github)
파이썬과 케라스로 배우는 강화학습 (github)
31 l강화학습 - 기초 개념부터 최신 알고리즘까지 이론과 실습을 통해 응용으로 가는 길 (오일석) 정성훈
30 └❶ 12장) 흉내 학습 (Imitation Learning) 정성훈
29    └❷ 프로그램 12-1) 바닐라 BC로 Hopper 과업 학습 정성훈
28 └❶ 10장) 신뢰 영역 (Trust Region) 방법 정성훈
27    └❷ 프로그램 10-1) PPO-clip을 이용한 Hopper 과업 학습 정성훈
26 l파이썬과 케라스로 배우는 강화학습 (github) 정성훈
25 └❶ 7장) 아타리 브레이크 아웃 (A3C) 정성훈
24 └❶ 7장) 아타리 브레이크 아웃 (DQN) 정성훈
23 l강화학습/심층강화학습 특강 (github) 정성훈
22 └❶ 13장) 스네이크 게임 마스터 되기 정성훈
21 └❶ 10장) 자율주행차를 위한 AI 정성훈
20 l바닥부터 배우는 강화 학습 코드 (github) 정성훈
19 └❶ 파이썬과 케라스로 배우는 강화학습이 5장) 텐서플로 2.0과 케라스 정성훈
18    └❷ 파이썬과 케라스로 배우는 강화학습이 5장) 텐서플로 2.0과 케라스 정성훈
17 └❶ l9장) ActorCritic (ch9_ActorCritic.py) 정성훈

[1][2][3]