-
Notifications
You must be signed in to change notification settings - Fork 0
/
NN.py
297 lines (242 loc) · 10.7 KB
/
NN.py
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import os
import random
from collections import deque
from pathlib import Path
from typing import List, Tuple
import numpy as np
import torch
import torch.nn as nn
from gymnasium import Env
from tetris_gym import Action
from tetris_project.controller import Controller
WEIGHT_OUT_PATH = os.path.join(os.path.dirname(__file__), "out.pth")
def lines_cleared(score):
if score >= 800:
return 4
elif score >= 500:
return 3
elif score >= 300:
return 2
elif score >= 100:
return 1
else:
return 0
class BufferItem:
def __init__(self, now_observe, reward, next_observe, done, clear_lines):
self.now_observe = now_observe
self.reward = reward
self.next_observe = next_observe
self.done = done
self.clear_lines = clear_lines
class ExperienceBuffer:
def __init__(self, buffer_size=10000):
self.buffer = deque(maxlen=buffer_size)
self.data_line_cnt = [0, 0, 0, 0, 0]
def add(self, experience: BufferItem):
if len(self.buffer) >= self.buffer.maxlen:
pop_item = self.buffer.popleft()
self.data_line_cnt[pop_item.clear_lines] -= 1
self.buffer.append(experience)
self.data_line_cnt[experience.clear_lines] += 1
def sample(
self, size: int
) -> List[Tuple[np.ndarray, int, float, np.ndarray, bool]]:
idx = np.random.choice(len(self.buffer), size, replace=False)
return [self.buffer[i] for i in idx]
def len(self) -> int:
return len(self.buffer)
class NN(nn.Module):
def __init__(self, input_size: int, output_size: int) -> None:
super(NN, self).__init__()
self.fc1 = nn.Linear(input_size, 64)
self.fc2 = nn.Linear(64, 256)
self.fc3 = nn.Linear(256, 128)
self.fc4 = nn.Linear(128, 64)
self.fc5 = nn.Linear(64, output_size)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = torch.relu(self.fc3(x))
x = torch.relu(self.fc4(x))
x = self.fc5(x)
return x
def save(self) -> None:
torch.save(self.state_dict(), WEIGHT_OUT_PATH)
def load(self, path: str) -> None:
path = os.path.join(os.path.dirname(__file__), path)
if Path(path).is_file():
self.load_state_dict(torch.load(path))
class NNTrainerController(Controller):
def __init__(
self,
actions: set[Action],
model: nn.Module,
discount=0.99,
epsilon=1.00,
epsilon_min=0.05,
epsilon_decay=0.995,
device="cpu",
) -> None:
super().__init__(actions)
self.model = model
self.discount = discount # 割引率
self.epsilon = epsilon # ε-greedy法 の ε
self.epsilon_min = epsilon_min # ε-greedy法 の ε の最小値
self.epsilon_decay = epsilon_decay # ε-greedy法 の ε の減衰率
# Experience Replay Buffer (上下 2 つ)
self.lower_experience_buffer = ExperienceBuffer()
self.upper_experience_buffer = ExperienceBuffer()
self.device = device
def get_action(self, env: Env) -> Action:
possible_states = self.get_possible_actions(env)
if random.random() < self.epsilon: # ε-greedy法
return random.choice(possible_states)[0]
else: # 最適行動
# 1. 3 Line 以上消せる遷移があったら問答無用でそれを選択
# 2. 直近で置いたミノが (height-6) / 2 + 6 より上なら、Line を消す遷移で最も期待値が高いものを選択
# ※ 2 で Line を消す遷移がなかった場合は他の遷移を選択
states = [state for _, state, _ in possible_states]
states_tensor = torch.tensor(np.array(states)).float().to(self.device)
rating = self.model(states_tensor)
line_clear_action = []
for idx, (action, state, clear_lines) in enumerate(possible_states):
if clear_lines >= 3:
return action
if clear_lines >= 1:
line_clear_action.append(tuple([rating[idx].item(), action]))
if (
len(line_clear_action) > 0
and env.unwrapped.tetris.board.height // 2
> env.unwrapped.tetris.pre_mino_state.origin[0]
):
line_clear_action.sort(reverse=True)
_, action = line_clear_action[0]
return action
action = possible_states[rating.argmax().item()][0]
return action
def train(self, env: Env, episodes=1):
# 統計情報
rewards = []
steps = 0
for _ in range(episodes):
state, _ = env.reset()
done = False
total_reward = 0
total_lines = 0
while not done:
action = self.get_action(env) # 行動を選択 (ε-greedy法)
next_state, reward, done, _, info = env.step(action) # 行動を実行
clear_lines = lines_cleared(reward)
if clear_lines >= 1: # Line Clear 時
print(f"★★★★★★★★★★ {clear_lines} Line Clear! ★★★★★★★★★★")
total_lines += clear_lines
# 設置高によって報酬に倍率をかける (画面下部がより高い倍率)
h_rate = (
1.0
- (env.unwrapped.tetris.pre_mino_state.origin[0] + 1)
/ env.unwrapped.tetris.board.height
)
rate1 = -h_rate * 3.0 / 2.0 + 1.0
rate2 = -h_rate * 2.0 / 3.0 + 2.0 / 3.0
if h_rate <= 0.40:
reward *= rate1
else:
reward *= rate2
buffer_item = BufferItem(state, reward, next_state, done, clear_lines)
if info["is_lower"]:
self.lower_experience_buffer.add(buffer_item)
else:
self.upper_experience_buffer.add(buffer_item)
state = next_state
total_reward += reward
steps += 1
if total_lines >= 30: # 30 Line 以上消したら break
break
rewards.append(total_reward)
self.learn()
return [steps, rewards]
def learn(self, batch_size=128, epochs=8):
# 上下合わせて batch_size 個のデータを取得
if (
self.lower_experience_buffer.len() < batch_size // 2
or self.upper_experience_buffer.len() < batch_size - batch_size // 2
):
print("lower experience buffer size: ", self.lower_experience_buffer.len())
print(
"upper experience buffer size: ",
self.upper_experience_buffer.len(),
"\n",
)
return
# 訓練データ
lower_batch = self.lower_experience_buffer.sample(batch_size // 2)
upper_batch = self.upper_experience_buffer.sample(batch_size - batch_size // 2)
all_batch = lower_batch + upper_batch
# 現在と次の状態の Q(s, a) を纏めてバッチ処理して効率化
states = np.array([sample.now_observe for sample in all_batch])
next_states = np.array([sample.next_observe for sample in all_batch])
cancat_states_tensor = (
torch.tensor(np.concatenate([states, next_states])).float().to(self.device)
)
all_targets = self.model(cancat_states_tensor)
targets = all_targets[:batch_size]
next_targets = all_targets[batch_size:]
# batch 内で最も高い報酬の期待値 Q(s, a) と即時報酬 r を表示
# idx: 最も高い報酬の期待値のインデックス
idx = np.argmax([sample.reward for sample in all_batch])
print(f"Immediate max reward in batch: {all_batch[idx].reward:.3f}")
print(f"Action max value for the first sample in batch: {targets[idx].item():.3f}")
# Q(s, a) の更新
for i, sample in enumerate(all_batch):
targets[i] = sample.reward
if not sample.done:
targets[i] += self.discount * next_targets[i]
targets_tensor = torch.tensor(targets).float().to(self.device)
# 学習
optimizer = torch.optim.Adam(self.model.parameters(), lr=0.001)
criterion = nn.MSELoss()
for _ in range(epochs):
optimizer.zero_grad()
states_tensor = torch.tensor(states).float().to(self.device)
outputs = self.model(states_tensor)
loss = criterion(outputs, targets_tensor)
loss.backward()
optimizer.step()
# 学習後に再度 batch 内で最も高い報酬の期待値 Q(s, a) を表示 (確認用)
targets = self.model(torch.tensor(states).float().to(self.device))
print(
f"Action max value for the first sample in batch after learning: {targets[idx].item():.3f}"
)
# Buffer 内部のデータ内訳
print("Data line count (lower): ", self.lower_experience_buffer.data_line_cnt)
print("Data line count (upper): ", self.upper_experience_buffer.data_line_cnt)
print("\n")
# 学習させる度に ε を減衰
self.epsilon = max(self.epsilon * self.epsilon_decay, self.epsilon_min)
class NNPlayerController(Controller):
def __init__(self, actions: set[Action], model) -> None:
super().__init__(actions)
self.model = model
def get_action(self, env: Env) -> Action:
possible_states = self.get_possible_actions(env)
# 1. 3 Line 以上消せる遷移があったら問答無用でそれを選択
# 2. 直近で置いたミノが (height-6) / 2 + 6 より上なら、Line を消す遷移で最も期待値が高いものを選択
# ※ 2 で Line を消す遷移がなかった場合は他の遷移を選択
states = [state for _, state, _ in possible_states]
rating = self.model(torch.tensor(np.array(states)).float())
line_clear_action = []
for idx, (action, state, clear_lines) in enumerate(possible_states):
if clear_lines >= 3:
return action
if clear_lines >= 1:
line_clear_action.append(tuple([rating[idx].item(), action]))
if (
len(line_clear_action) > 0
and env.unwrapped.tetris.board.height // 2
> env.unwrapped.tetris.pre_mino_state.origin[0]
):
line_clear_action.sort(reverse=True)
_, action = line_clear_action[0]
return action
action = possible_states[rating.argmax().item()][0]
return action