-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent_structure.py
2491 lines (2003 loc) · 105 KB
/
agent_structure.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import os
import random
import copy
import math
from collections import deque
import torch
from torch import nn, optim
import torch.nn.functional as F
import time
import env
import nashpy as nash
from env import MCTS, MCTSParallel, SPG
from functions import board_normalization, \
get_model_config, set_optimizer, \
get_distinct_actions, is_full_after_my_turn, \
softmax_policy, get_valid_actions, get_next_board, \
get_current_time, get_encoded_state
from ReplayBuffer import RandomReplayBuffer
# models.py 분리 후 이동, 정상 작동하면 지울 듯
# import torch.nn.init as init
# import torch.nn.functional as F
from models import DQNModel, HeuristicModel, RandomModel, MinimaxModel, \
AlphaZeroResNet
import json
import matplotlib.pyplot as plt
from sys import exit
# editable hyperparameters
# let iter=10000, then
# learning rate 0.01~0.00001
# batch_size 2^5~2^10
# hidden layer 2^6~2^9
# memory_len 100~100000
# target_update 1~10000
# models = {
# 1:CFLinear,
# 2:CFCNN,
# 3:HeuristicModel,
# 4:RandomModel,
# 5:AlphaZeroResNet,
# 6:ResNetforDQN,
# 7:CNNforMinimax,
# }
# with open('config.json', 'r') as f:
# config = json.load(f)
def set_op_agent(agent_name):
if agent_name == "Heuristic":
return HeuristicAgent()
elif agent_name == "Random":
return ConnectFourRandomAgent()
elif agent_name == "Minimax":
return MinimaxAgent()
elif agent_name == "self":
return "self"
else:
print("invalid op_agent model name")
exit()
def evaluate_model(agent, record, n_battles=[10,10,10]):
op_agents = [ConnectFourRandomAgent(), HeuristicAgent(), MinimaxAgent()]
w,l,d = env.compare_model(agent, op_agents[0], n_battle=n_battles[0])
record[0].append(w+d)
w,l,d = env.compare_model(agent, op_agents[1], n_battle=n_battles[1])
record[1].append(w+d)
w,l,d = env.compare_model(agent, op_agents[2], n_battle=n_battles[2])
record[2].append(w+d)
class ConnectFourDQNAgent(nn.Module):
def __init__(self, state_size=6*7, action_size=7, config_file_name=None, **kwargs):
super(ConnectFourDQNAgent,self).__init__()
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
config = get_model_config(config_file_name)
# print(kwargs)
for key, value in kwargs.items():
# print("key, value")
# print(key, value)
config[key] = value
self.use_conv=config['use_conv']
self.use_resnet=config['use_resnet']
self.use_minimax=config['use_minimax']
self.use_nash=config['use_nash']
self.next_state_is_op_state = config['next_state_is_op_state']
if self.use_minimax and self.next_state_is_op_state:
print("invalid model structure")
exit()
self.policy_net = DQNModel(use_conv=self.use_conv,
use_resnet=self.use_resnet,
use_minimax=self.use_minimax
).model
# 실제 업데이트되는 network
# target network
self.target_net = copy.deepcopy(self.policy_net)
# deepcopy하면 파라미터 load를 안해도 되는거 아닌가? 일단 두자
self.target_net.load_state_dict(self.policy_net.state_dict())
self.target_net.eval()
self.lr = config['lr']
# optimizer는 기본적으로 adam을 사용하겠지만 추후 다른 것으로 실험할 수도 있음
self.optimizer = set_optimizer(
config['optimizer'],
self.policy_net.parameters(),
lr=self.lr
)
self.selfplay = config['selfplay']
self.add_pool_freq = config['add_pool_freq'] # no need if no selfplay
self.memory_len = config['memory_len']
self.batch_size = config['batch_size']
# DQN에 사용될 replay memory(buffer)
self.memory = RandomReplayBuffer(
buffer_size=self.memory_len,
batch_size=self.batch_size,
use_conv=self.use_conv,
use_minimax=self.use_minimax
)
self.gamma = config['gamma'] # discount factor
self.state_size = state_size
self.action_size = action_size
self.target_update = config['target_update'] # target net update 주기(여기선 step)
self.steps = 0
self.epi = config['epi']
self.softmax_const = config['softmax_const'] + np.finfo(np.float32).min
self.max_temp = config['max_temp']
self.min_temp = config['min_temp']
self.temp_decay = (self.min_temp/self.max_temp)**(1/(self.epi*self.softmax_const))
self.temp = self.max_temp
self.eps = config['eps'] # DQN에서 사용될 epsilon
self.noise_while_train = config['noise_while_train']
self.double_dqn = config['double_dqn']
self.batch_size = config['batch_size'] # size of mini-batch
self.repeat_reward = config['repeat_reward'] # repeat reward
self.losses = [] # loss들을 담는 list
# record of win rate of random, heuristic, minimax agent
self.record = [[], [], []]
# def get_nash_action(self, q_value,valid_actions, distinct_actions):
# # if len(valid_actions) == 1:
# # return (valid_actions[0],valid_actions[0])
# A = q_value.cpu().detach().numpy().reshape(7,7)
# A = A[valid_actions][:,valid_actions]
# # print(A,B)
# game = nash.Game(A)
# try:
# print(valid_actions)
# print(distinct_actions)
# print(A)
# action_prob1, action_prob2 = game.lemke_howson(initial_dropped_label=0)
# if len(action_prob1) != len(valid_actions) or len(action_prob2) != len(valid_actions): # GAME IS DEGENERATE
# equilibria = game.support_enumeration()
# action_prob1, action_prob2 = next(equilibria)
# except:
# equilibria = game.support_enumeration()
# action_prob1, action_prob2 = next(equilibria)
# # print(valid_actions)
# # print(action_prob1)
# # print(action_prob2)
# # print()
# a = np.random.choice (valid_actions, p=action_prob1)
# b = np.random.choice (valid_actions, p=action_prob2)
# # print("probA:",prob[0])
# # print("probB:",prob[1])
# if not (a in distinct_actions and a==b):
# return (a,b)
# else:
# return (None, None)
# https://code.activestate.com/recipes/496825-game-theory-payoff-matrix-solver/
# 내쉬 균형 찾는 코드 참고
def get_nash_prob_and_value(self,payoff_matrix, vas, das, iterations=50):
if isinstance(payoff_matrix, torch.Tensor):
payoff_matrix = payoff_matrix.clone().detach().cpu().numpy().reshape(7,7)
elif isinstance(payoff_matrix, np.ndarray):
payoff_matrix = payoff_matrix.reshape(7,7)
payoff_matrix = payoff_matrix[vas][:,vas]
'''Return the oddments (mixed strategy ratios) for a given payoff matrix'''
transpose_payoff = np.transpose(payoff_matrix)
row_cum_payoff = np.zeros(len(payoff_matrix))
col_cum_payoff = np.zeros(len(transpose_payoff))
col_count = np.zeros(len(transpose_payoff))
row_count = np.zeros(len(payoff_matrix))
active = 0
for i in range(iterations):
row_count[active] += 1
col_cum_payoff += payoff_matrix[active]
active = np.argmin(col_cum_payoff)
col_count[active] += 1
row_cum_payoff += transpose_payoff[active]
active = np.argmax(row_cum_payoff)
value_of_game = (max(row_cum_payoff) + min(col_cum_payoff)) / 2.0 / iterations
row_prob = row_count / iterations
col_prob = col_count / iterations
return row_prob, col_prob, value_of_game
def get_nash_action(self, q_value,valid_actions, distinct_actions):
# if len(valid_actions) == 1:
# return (valid_actions[0],valid_actions[0])
# print(A,B)
action_prob1, action_prob2, value = self.get_nash_prob_and_value(q_value, valid_actions, distinct_actions)
# print(valid_actions)
# print(action_prob1)
# print(action_prob2)
# print()
a = np.random.choice (valid_actions, p=action_prob1)
b = np.random.choice (valid_actions, p=action_prob2)
# print("probA:",prob[0])
# print("probB:",prob[1])
if not (a in distinct_actions and a==b):
return (a,b)
else:
return (None, None)
# softmax를 포함한 minimax action sampling
def get_minimax_action(self, q_value,valid_actions, distinct_actions, temp=0):
if is_full_after_my_turn(valid_actions, distinct_actions):
return (valid_actions[0], np.random.choice(valid_actions))
if self.use_nash:
a,b = self.get_nash_action(q_value,valid_actions, distinct_actions)
if (a,b) != (None, None):
return a,b
q_dict = {}
# print(valid_actions)
# print(distinct_actions)
for a in valid_actions:
q_dict[a] = []
for b in valid_actions:
if a in distinct_actions and a==b: continue
idx = 7*a + b
# print(a,b)
# print(q_value[idx])
# print(q_dict[a][1])
q_dict[a].append((b, -q_value[idx]))
op_action, value = softmax_policy(torch.tensor(q_dict[a]), temp=temp)
# if torch.isnan(value):
# print(a,b)
# print(q_value.reshape(7,7))
# print(q_dict)
q_dict[a] = (op_action, -1 * value)
qs_my_turn = [[key, value[1]] for key, value in q_dict.items()]
action, value = softmax_policy(torch.tensor(qs_my_turn), temp=temp)
# if torch.isnan(value):
# print(a,b)
# print(q_value.reshape(7,7))
# print(q_dict)
return (action, q_dict[action][0])
def select_action(self, state, env, player=1):
valid_actions = env.valid_actions
if self.use_minimax:
distinct_actions = get_distinct_actions(env)
if is_full_after_my_turn(valid_actions, distinct_actions):
return (valid_actions[0], np.random.choice(valid_actions))
if np.max([np.random.uniform(), self.softmax_const]) < self.eps:
while True:
a,b = np.random.choice(valid_actions), np.random.choice(valid_actions)
if a==b and a in distinct_actions:continue
else: break
return (a,b)
else:
if np.max([np.random.uniform(), self.softmax_const]) < self.eps:
return np.random.choice(valid_actions)
with torch.no_grad():
state_ = torch.FloatTensor(state).to(self.device)
# CNN일 때만 차원을 바꿔줌
if self.use_conv:
# input channel=3 test
# state_ = state_.reshape(6,7)
# state_ = state_.unsqueeze(0).unsqueeze(0) # (6,7) -> (1,1,6,7)
state_ = state_.unsqueeze(0)
else: state_ = state_.flatten()
q_value = self.policy_net(state_)
# print(env.board)
# print(((q_value.reshape(7,7)*100).int()/100.).v)
if True in torch.isnan(q_value):
print( q_value)
print(state, state.shape)
print(state_, state_.shape)
print(env.board)
print(self.policy_net)
exit()
# temp=0 은 greedy action을 의미하므로
temp = 0 if self.softmax_const < self.eps else self.temp
if self.use_minimax:
# print("state:",state)
# print("valid_actions:",valid_actions)
# print("q_value:",q_value)
a,b = self.get_minimax_action(
q_value.squeeze(0),
valid_actions,
distinct_actions,
temp=temp
)
# for debugging
# print(q_value.reshape(7,7))
# print(valid_actions)
# print(distinct_actions)
# print(temp)
# print(a,b)
return (a, b)
else:
# print("state:",state)
# print("valid_actions:",valid_actions)
# print("q_value:",q_value)
valid_q_values = q_value.squeeze()[torch.tensor(valid_actions)].to(self.device)
valid_index_q_values = torch.stack([torch.tensor(valid_actions).to(self.device), valid_q_values], dim=0)
valid_index_q_values = torch.transpose(valid_index_q_values,0,1)
action, value = softmax_policy(valid_index_q_values,temp=temp)
return action
# return valid_actions[torch.argmax(valid_q_values)]
# # replay buffer에 경험 추가
# def append_memory(self, state, action, reward, next_state, done):
# if self.policy_net.model_type == 'Linear':
# self.memory.append((state.flatten(), action, reward, next_state.flatten(), done))
# else:
# self.memory.append((state.reshape(6,7), action, reward, next_state.reshape(6,7), done))
def collect_data(self, env, op_model):
players = {1:self, 2:op_model}
while self.memory.get_length() < self.memory.start_size:
print("num collected:",self.memory.get_length())
# if self.memory.get_length() > 20:
# s = torch.round(self.memory.buffer[-2][0]).reshape(6,7)
# a = self.memory.buffer[-2][1]
# b = self.memory.buffer[-2][2]
# r = self.memory.buffer[-2][3]
# s_prime = torch.round(self.memory.buffer[-2][4]).reshape(6,7)
# m = self.memory.buffer[-2][5]
# d = self.memory.buffer[-2][6]
# print(s,a,b,r,s_prime,m,d)
# print()
# s = torch.round(self.memory.buffer[-1][0]).reshape(6,7)
# a = self.memory.buffer[-1][1]
# b = self.memory.buffer[-1][2]
# r = self.memory.buffer[-1][3]
# s_prime = torch.round(self.memory.buffer[-1][4]).reshape(6,7)
# m = self.memory.buffer[-1][5]
# d = self.memory.buffer[-1][6]
# print(s,a,b,r,s_prime,m,d)
# print()
env.reset()
state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=players[env.player].use_conv)
if self.use_conv:
# input channel=3 test
state = torch.tensor(get_encoded_state(state_))
else:
state = torch.from_numpy(state_).float()
done = False
past_state, past_action, past_reward, past_done = state, None, None, done
while not done:
# 원래는 player, op_player 였지만, 직관적인 이해를 위해 수정
turn = env.player
op_turn = 2//turn
action = players[turn].select_action(state, env, player=turn)
if players[turn].use_minimax:
op_action_prediction = action[1]
action = action[0]
observation, reward, done = env.step(action)
if self.use_minimax and self.use_nash:
mask = torch.zeros(7)
VA = get_valid_actions(observation)
DA = get_distinct_actions(env)
mask[VA] = 1
mask[DA] = 2
elif self.use_minimax:
mask = torch.ones(7,7)
VA = get_valid_actions(observation)
DA = get_distinct_actions(env)
for a in range(7):
if not a in VA:
mask[a,:] = 0
mask[:,a] = 0
for da in DA:
mask[da,da] = 0
# for debugging
# print(observation)
# print(VA)
# print(DA)
# print(mask)
# print()
else:
mask = torch.zeros(7)
VA = get_valid_actions(observation)
for va in VA:
mask[va] = 1
op_state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=players[turn].use_conv)
# input channel=3 test
if self.use_conv:
op_state = torch.tensor(get_encoded_state(op_state_))
else: op_state = torch.from_numpy(op_state_).float()
if past_action is not None: # 맨 처음이 아닐 때
# 경기가 끝났을 때(중요한 경험)
if done:
repeat = 1
# 중요한 경험일 때는 더 많이 memory에 추가해준다(optional)
if reward > 0: repeat = self.repeat_reward
for _ in range(repeat):
# 돌을 놓자마자 끝났으므로, next_state가 반전됨, 따라서 -1을 곱해준다
if turn==1:
if self.use_minimax:
self.memory.add(state, action, op_action_prediction, reward, op_state*-1,mask,done)
elif self.next_state_is_op_state:
self.memory.add(state, action, reward, op_state,mask,done)
else:
self.memory.add(state,action, reward, op_state*-1, mask,done)
if turn==2:
if self.use_minimax:
self.memory.add(past_state, past_action, action, -reward, op_state, mask,done)
elif self.next_state_is_op_state:
self.memory.add(past_state, past_action,-reward, state,mask, past_done)
else:
self.memory.add(past_state, past_action, -reward, op_state, mask,done)
# 경기가 끝나지 않았다면
elif turn==2: # 내 경험만 수집한다
if self.use_minimax:
self.memory.add(past_state, past_action, action, past_reward, op_state, mask,past_done)
elif self.next_state_is_op_state:
self.memory.add(past_state, past_action, past_reward, state,mask,past_done)
else:
self.memory.add(past_state, past_action, past_reward, op_state, mask,past_done)
# info들 업데이트 해줌
past_state = state
past_action = action
past_reward = reward
past_done = done
state = op_state
# 게임이 끝났다면 나가기
if done: break
def minimax_train(self,epi,env):
env.reset()
print(self.eps, epi)
self.collect_data(env, self)
if self.selfplay:
players = {1: self}
new_model = copy.deepcopy(self)
new_model.policy_net.eval()
new_model.target_net.eval()
new_model.eps = 0.1
pool = deque([new_model], maxlen=1000)
# models 딕셔너리는 전역 변수로 사용하므로, players로 변경
else: players = {1: self, 2: self}
for i in range(epi):
if self.selfplay:
random.shuffle(pool)
players[2] = random.choice(pool)
if i!=0 and i%200==0:
env.print_board(clear_board=False)
print("epi:",i, ", agent's step:",self.steps)
# 얼마나 학습이 진행되었는지 확인하기 위해, 모델 성능 측정
evaluate_model(self, record=self.record)
print(self.record[0][-1],self.record[1][-1], self.record[2][-1])
# print("agent의 승률이 {}%".format(int(100*record[0]/sum(record))))
print("loss:",sum(self.losses[-101:-1])/100.)
if self.eps > self.softmax_const: print("epsilon:",self.eps)
else: print("temp:",self.temp)
# simulate_model() 을 실행시키면 직접 행동 관찰 가능
# simulate_model(self, op_model)
env.reset()
if env.player == 2:
action = random.randint(0,6)
env.step(action)
state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=self.use_conv)
if self.use_conv:
# input channel=3 test
state = torch.tensor(get_encoded_state(state_))
else: state = torch.from_numpy(state_).float()
done = False
while not done:
# 원래는 player, op_player 였지만, 직관적인 이해를 위해 수정
turn = env.player
if turn != 1:
print("this cannot be happen in minimax")
exit()
action, op_action = players[turn].select_action(state, env, player=turn)
observation, reward, done = env.step(action)
if self.use_nash:
mask = torch.zeros(7)
VA = get_valid_actions(observation)
DA = get_distinct_actions(env)
mask[VA] = 1
mask[DA] = 2
else:
mask = torch.ones(7,7)
VA = get_valid_actions(observation)
DA = get_distinct_actions(env)
for a in range(7):
if not a in VA:
mask[a,:] = 0
mask[:,a] = 0
for da in DA:
mask[da,da] = 0
# for debugging
# print(observation)
# print(VA)
# print(DA)
# print(mask)
# print()
op_state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=self.use_conv)
if self.use_conv:
# input channel=3 test
op_state = torch.tensor(get_encoded_state(op_state_))
else: op_state = torch.from_numpy(op_state_).float()
# 경기가 끝났을 때(중요한 경험)
if done:
# 중요한 경험일 때는 더 많이 memory에 추가해준다(optional)
if reward > 0: repeat = self.repeat_reward
for _ in range(repeat):
# 돌을 놓자마자 끝났으므로, next_state가 반전됨, 따라서 -1을 곱해준다
self.memory.add(state, action, op_action, reward, op_state*-1,mask,done)
# print("s:\n",torch.round(state).reshape(6,7).int())
# print("a:\n", action)
# print("b:\n", op_action)
# print("r:\n", reward)
# print("s_prime\n", torch.round(op_state*-1).reshape(6,7).int())
# print("m:\n", mask.reshape(7,7).int())
# print("d:\n", done)
break
# 아직 안끝났으면,
if self.selfplay:
op_real_action, _ = players[2].select_action(op_state, env, player=2//turn)
op_observation, op_reward, op_done = env.step(op_real_action)
else:
op_observation, op_reward, op_done = env.step(op_action)
done = done or op_done
if self.use_nash:
mask = torch.zeros(7)
VA = get_valid_actions(observation)
DA = get_distinct_actions(env)
mask[VA] = 1
mask[DA] = 2
else:
mask = torch.ones(7,7)
VA = get_valid_actions(op_observation)
DA = get_distinct_actions(env)
for a in range(7):
if not a in VA:
mask[a,:] = 0
mask[:,a] = 0
for da in DA:
mask[da,da] = 0
next_state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=players[turn].use_conv)
if self.use_conv:
# input channel=3 test
next_state = torch.tensor(get_encoded_state(next_state_))
else: next_state = torch.from_numpy(next_state_).float()
self.memory.add(state, action, op_action, reward-op_reward, next_state, mask,done)
# if reward-op_reward < 0:
# print("s:\n",torch.round(state).reshape(6,7).int())
# print("a:\n", action)
# print("b:\n", op_action)
# print("r:\n", reward-op_reward)
# print("s_prime\n", torch.round(next_state).reshape(6,7).int())
# print("m:\n", mask.reshape(7,7).int())
# print("d:\n", done)
# info들 업데이트 해줌
state = next_state.clone()
# replay buffer 를 이용하여 mini-batch 학습
if self.use_minimax and self.use_nash:
self.replay_nash()
else:
self.replay()
if self.selfplay and self.steps and not self.steps%self.add_pool_freq:
print("added in pool")
new_model = copy.deepcopy(self)
new_model.policy_net.eval()
new_model.target_net.eval()
new_model.memory.clear()
new_model.eps = 0.1
new_model.softmax_const = 0
new_model.temp = 0
pool.append(new_model)
# if Qagent.memory and abs(Qagent.memory[-1][2])!=1:
# print("state:\n",torch.round(Qagent.memory[-1][0]).int())
# print("action:",Qagent.memory[-1][1])
# print("reward:",Qagent.memory[-1][2])
# print("next_state\n",torch.round(Qagent.memory[-1][3]).int())
if self.eps > 0.1: self.eps -= (1/epi)
if self.eps < self.softmax_const:
self.temp *= self.temp_decay
def train(self,epi,env:env.ConnectFourEnv,op_model):
if self.use_minimax:
self.minimax_train(epi,env)
return
env.reset()
# self.eps += self.memory.get_maxlen()//10/epi
# epi += self.memory.get_maxlen()//10
print(self.eps, epi)
if self.selfplay:
players = {1: self}
new_model = copy.deepcopy(self)
new_model.policy_net.eval()
new_model.target_net.eval()
new_model.eps = 0.1
pool = deque([new_model], maxlen=200)
# models 딕셔너리는 전역 변수로 사용하므로, players로 변경
else: players = {1: self, 2: op_model}
self.collect_data(env, self if self.selfplay else op_model)
for i in range(epi):
if self.selfplay:
# random.shuffle(pool)
players[2] = random.choice(pool)
# 100번마다 loss, eps 등의 정보 표시
if i!=0 and i%200==0:
#env.print_board(clear_board=False)
print("epi:",i, ", agent's step:",self.steps)
# 얼마나 학습이 진행되었는지 확인하기 위해, 모델 성능 측정
evaluate_model(self, record=self.record)
print(self.record[0][-1],self.record[1][-1], self.record[2][-1])
# print("agent의 승률이 {}%".format(int(100*record[0]/sum(record))))
print("loss:",sum(self.losses[-101:-1])/100.)
if self.eps > self.softmax_const: print("epsilon:",self.eps)
else: print("temp:",self.temp)
# simulate_model() 을 실행시키면 직접 행동 관찰 가능
# simulate_model(self, op_model)
env.reset()
state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=players[env.player].use_conv)
if self.use_conv:
# input channel=3 test
state = torch.tensor(get_encoded_state(state_))
else: state = torch.from_numpy(state_).float()
done = False
past_state, past_action, past_reward, past_done = state, None, None, done
while not done:
# 원래는 player, op_player 였지만, 직관적인 이해를 위해 수정
turn = env.player
op_turn = 2//turn
action = players[turn].select_action(state, env, player=turn)
if players[turn].use_minimax:
op_action_prediction = action[1]
action = action[0]
observation, reward, done = env.step(action)
if self.use_minimax:
mask = torch.ones(7,7)
VA = get_valid_actions(observation)
DA = get_distinct_actions(env)
for a in range(7):
if not a in VA:
mask[a,:] = 0
mask[:,a] = 0
for da in DA:
mask[da,da] = 0
# for debugging
# print(observation)
# print(VA)
# print(DA)
# print(mask)
# print()
else:
mask = torch.zeros(7)
VA = get_valid_actions(observation)
for va in VA:
mask[va] = 1
op_state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=players[turn].use_conv)
#
if self.use_conv:
# input channel=3 test
op_state = torch.tensor(get_encoded_state(op_state_))
else: op_state = torch.from_numpy(op_state_).float()
if past_action is not None: # 맨 처음이 아닐 때
# 경기가 끝났을 때(중요한 경험)
if done:
repeat = 1
# 중요한 경험일 때는 더 많이 memory에 추가해준다(optional)
if reward > 0: repeat = self.repeat_reward
for _ in range(repeat):
# 돌을 놓자마자 끝났으므로, next_state가 반전됨, 따라서 -1을 곱해준다
if turn==1:
if self.use_minimax:
self.memory.add(state, action, op_action_prediction, reward, op_state*-1,mask,done)
elif self.next_state_is_op_state:
self.memory.add(state, action, reward, op_state,mask,done)
else:
self.memory.add(state,action, reward, op_state*-1, mask,done)
# print for debugging
# print("for player")
# print("state:\n",torch.round(state).reshape(6,7).int())
# print("action:",action)
# print("reward:",reward)
# print("next_state:\n",torch.round(op_state*-1).reshape(6,7).int())
# print("mask:\n",torch.round(mask))
# print()
# 내가 이겼으므로 상대는 음의 보상을 받음
#Qmodels[op_player].append_memory(past_state, past_action, -reward, op_state, done)
if turn==2:
if self.use_minimax:
self.memory.add(past_state, past_action, action, -reward, op_state, mask,done)
elif self.next_state_is_op_state:
self.memory.add(past_state, past_action,-reward, state,mask, past_done)
else:
self.memory.add(past_state, past_action, -reward, op_state, mask,done)
# print for debugging
# print("for opponent")
# print("state:\n",torch.round(past_state).reshape(6,7).int())
# print("action:",past_action)
# print("op_action:",action)
# print("reward:",-reward)
# print("next_state\n",torch.round(state).reshape(6,7).int())
# print("next_state\n",torch.round(op_state).reshape(6,7).int())
# print("mask\n",mask)
# print()
# 경기가 끝나지 않았다면
elif turn==2: # 내 경험만 수집한다
if self.use_minimax:
self.memory.add(past_state, past_action, action, past_reward, op_state, mask,past_done)
elif self.next_state_is_op_state:
self.memory.add(past_state, past_action, past_reward, state,mask,past_done)
else:
self.memory.add(past_state, past_action, past_reward, op_state, mask,past_done)
# print for debugging
# print("for opponent")
# print("state:\n",torch.round(past_state).reshape(6,7).int())
# print("action:",past_action)
# print("reward:",past_reward)
# print("next_state\n",torch.round(state*-1).reshape(6,7).int())
# print("mask\n",mask)
# print()
# op_action = Qmodels[player].select_action(op_state,valid_actions=CFenv.valid_actions, player=player)
# op_observation, op_reward, op_done = CFenv.step(op_action)
# next_state_ = board_normalization(op_observation.flatten()) + np.random.randn(1, Qagent.state_size)/100.0
# next_state = torch.from_numpy(next_state_).float()
# # 2p가 돌을 놓자마자 끝남
# if op_done:
# Qmodels[player].append_memory(op_state,op_action, op_reward, next_state, op_done)
# Qmodels[op_player].append_memory(state,action, -op_reward, next_state, op_done)
# else:
# exp = (state, action, reward, next_state, done)
# Qmodels[player].append_memory(*exp)
# info들 업데이트 해줌
past_state = state
past_action = action
past_reward = reward
past_done = done
state = op_state
# replay buffer 를 이용하여 mini-batch 학습
self.replay()
if self.selfplay and self.steps and not self.steps%self.add_pool_freq:
print("added in pool")
new_model = copy.deepcopy(self)
new_model.policy_net.eval()
new_model.target_net.eval()
new_model.eps = 0.1
new_model.memory.clear()
new_model.softmax_const = 0
new_model.temp = 0
pool.append(new_model)
# if Qagent.memory and abs(Qagent.memory[-1][2])!=1:
# print("state:\n",torch.round(Qagent.memory[-1][0]).int())
# print("action:",Qagent.memory[-1][1])
# print("reward:",Qagent.memory[-1][2])
# print("next_state\n",torch.round(Qagent.memory[-1][3]).int())
# 게임이 끝났다면 나가기
if done: break
# print("eps:",Qagent.eps)
# epsilon-greedy
# min epsilon을 가지기 전까지 episode마다 조금씩 낮춰준다(1 -> 0.1)
if self.eps > 0.1: self.eps -= (1/epi)
if self.eps < self.softmax_const:
self.temp *= self.temp_decay
# def train_selfplay(self, epi, env, pool, add_pool):
# env.reset()
# # models 딕셔너리는 전역 변수로 사용하므로, players로 변경
# players = {1: self}
# for i in range(epi):
# players[2] = random.choice(pool)
# # 100번마다 loss, eps 등의 정보 표시
# if i!=0 and i%100==0:
# env.print_board(clear_board=False)
# print("epi:",i, ", agent's step:",self.steps)
# # 얼마나 학습이 진행되었는지 확인하기 위해, 모델 성능 측정
# record = compare_model(self, players[2], n_battle=100)
# print(record)
# print("agent의 승률이 {}%".format(int(100*record[0]/sum(record))))
# print("loss:",sum(self.losses[-101:-1])/100.)
# print("epsilon:",self.eps)
# # simulate_model() 을 실행시키면 직접 행동 관찰 가능
# # simulate_model(self, op_model)
# env.reset()
# state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=players[env.player].use_conv)
# state = torch.from_numpy(state_).float()
# done = False
# past_state, past_action, past_reward, past_done = state, None, None, done
# while not done:
# # 원래는 player, op_player 였지만, 직관적인 이해를 위해 수정
# turn = env.player
# op_turn = 2//turn
# action = players[turn].select_action(state, env, player=turn)
# if self.use_minimax:
# op_action_prediction = action[1]
# action = action[0]
# observation, reward, done = env.step(action)
# op_state_ = board_normalization(noise=self.noise_while_train, env=env, use_conv=players[turn].use_conv)
# op_state = torch.from_numpy(op_state_).float()
# if past_action is not None: # 맨 처음이 아닐 때
# # 경기가 끝났을 때(중요한 경험)
# if done:
# repeat = 1
# # 중요한 경험일 때는 더 많이 memory에 추가해준다(optional)
# if reward > 0: repeat = self.repeat_reward
# for j in range(repeat):
# # 돌을 놓자마자 끝났으므로, next_state가 반전됨, 따라서 -1을 곱해준다
# if turn==1:
# if self.use_minimax:
# self.append_memory(state,action,op_action_prediction, reward, op_state*-1, done)
# else:
# self.append_memory(state,action, reward, op_state*-1, done)
# # print for debugging
# # print("for player")
# # print("state:\n",torch.round(state).reshape(6,7).int())
# # print("action:",action)
# # print("reward:",reward)
# # print("next_state\n",torch.round(op_state*-1).reshape(6,7).int())
# # print()
# # 내가 이겼으므로 상대는 음의 보상을 받음
# #Qmodels[op_player].append_memory(past_state, past_action, -reward, op_state, done)
# if turn==2:
# if self.use_minimax:
# self.append_memory(past_state, past_action, action, -reward, op_state, done)
# else:
# self.append_memory(past_state, past_action, -reward, op_state, done)
# # print for debugging
# # print("for opponent")
# # print("state:\n",torch.round(past_state).reshape(6,7).int())
# # print("action:",past_action)
# # print("reward:",-reward)
# # print("next_state\n",torch.round(op_state).reshape(6,7).int())
# # print()
# # 경기가 끝나지 않았다면
# elif turn==2: # 내 경험만 수집한다
# if self.use_minimax:
# self.append_memory(past_state, past_action, action, past_reward, op_state, past_done)
# else:
# self.append_memory(past_state, past_action, past_reward, op_state, past_done)
# # print for debugging
# # print("for opponent")
# # print("state:\n",torch.round(past_state).reshape(6,7).int())