/
train_select_cards.py
448 lines (351 loc) · 19.9 KB
/
train_select_cards.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
from QL_select_card import QNetwork as QNetworkCard
from QL_select_card import Memory
from interface_to_states import interface_to_states
from rules import Rules
import helper_functions as h
import numpy as np
import random
import copy
import tensorflow as tf
import random
import math
class train_select_cards():
def __init__(self):
self.train_episodes = 20000 # max number of episodes to learn from
self.gamma = 1 # future reward discount
# Exploration parameters
self.explore_start = 1.0 # exploration probability at start
self.explore_stop = 0.01 # minimum exploration probability 0.01
self.decay_rate = 0.0001 # exponential decay rate for exploration prob 0.00001
# Network parameters
self.hidden_size1 = 128 # number of units in each Q-network hidden layer 64
self.hidden_size2 = 64
self.hidden_size3 = 32
self.learning_rate = 0.000005 # Q-network learning rate 0.00001
# Memory parameters
self.memory_size = 1000 # memory capacity
self.batch_size = 64 # experience mini-batch size
self.pretrain_length = self.batch_size*8 # number experiences to pretrain the memory
tf.reset_default_graph()
self.QNetworkCard = QNetworkCard(name='main',
hidden_size1=self.hidden_size1,
hidden_size2=self.hidden_size2,
hidden_size3=self.hidden_size3,
learning_rate=self.learning_rate)
self.memory = Memory(max_size=self.memory_size)
self.s = interface_to_states()
self.rules = Rules()
self.reward_scale = 210 # lost solo schneider schwarz
def populate_memory(self):
# Make random actions and store experiences
j = 0
while j < math.ceil(self.pretrain_length/8):
self.s.reset_epsiode()
self.s.dealing()
for i in range(4):
possible_games = self.s.return_possible_games(i)
if len(possible_games) > 0:
selected_game = random.choice(possible_games)
if selected_game != [None, None]:
self.s.write_game_to_states(selected_game, i)
# Simulate playing
if self.s.return_state_overall()['game'] != [None, None]:
states_list = []
action_list = []
while self.s.return_state_overall()['trick_number'] < 8:
j+=1
first_player = self.s.return_state_overall()['first_player']
for i in range(4):
possible_cards = self.s.return_possbile_cards(i)
selected_card = random.choice(possible_cards)
# Save player 0's actions and states in lists
if ((first_player+i)%4) == 0:
state = self.s.return_state_select_card(player_id=0)
action = self.rules.get_index(selected_card, 'card')
states_list.append(state)
action_list.append(action)
# Write cards to states
self.s.write_card_to_states(selected_card, i)
# Update states
self.s.update_first_player_trick_nr_score()
rewards = self.s.return_reward_list()
# Scale rewards
rewards = [r/self.reward_scale for r in rewards]
# Save action, states and reward in memory
for i in range(len(states_list)):
if i < 7:
self.memory.add((states_list[i],
action_list[i],
0, #reward
states_list[i+1]))
else:
self.memory.add((states_list[i],
action_list[i],
rewards[0],
np.zeros(np.array(state).shape).tolist()))
def training(self):
saver = tf.train.Saver()
reward_list1 = []
reward_list2 = []
reward_list3 = []
reward_list4 = []
loss_list= []
total_reward1=0
total_reward2=0
total_reward3=0
total_reward4=0
total_loss=0
with tf.Session() as sess:
# Initialize variables
sess.run(tf.global_variables_initializer())
for e in range(1, self.train_episodes+1):
self.s.reset_epsiode()
self.s.dealing()
for i in range(4):
possible_games = self.s.return_possible_games(i)
if len(possible_games) > 0:
selected_game = random.choice(possible_games)
if selected_game != [None, None]:
self.s.write_game_to_states(selected_game, i)
# Simulate playing
if self.s.return_state_overall()['game'] != [None, None]:
states_list = []
action_list = []
while self.s.return_state_overall()['trick_number'] < 8:
first_player = self.s.return_state_overall()['first_player']
for i in range(4):
possible_cards = self.s.return_possbile_cards(i)
# Explore or Exploit
explore_p = self.explore_stop + \
(self.explore_start - self.explore_stop)*np.exp(-self.decay_rate*1*e)
if explore_p > np.random.rand() or \
self.s.return_state_player((first_player+i)%4)['player_id']!=0:
selected_card = random.choice(possible_cards)
if self.s.return_state_player((first_player+i)%4)['player_id']==0:
state = self.s.return_state_select_card(player_id=0)
state = np.array(state)
action = self.rules.get_index(selected_card, 'card')
states_list.append(state)
action_list.append(action)
else:
state = self.s.return_state_select_card(player_id=0)
state = np.array(state)
feed = {self.QNetworkCard.inputs_: state.reshape((1, *state.shape))}
Qs = sess.run(self.QNetworkCard.output, feed_dict=feed)
Qs = Qs[0].tolist()
possible_actions = [self.rules.get_index(p_g, 'card') for p_g in possible_cards]
Qs_subset = [i for i in Qs if Qs.index(i) in possible_actions]
action = np.argmax(Qs_subset)
action = Qs.index(max(Qs_subset))
selected_card = self.rules.cards[action]
states_list.append(state)
action_list.append(action)
# Write cards to states
self.s.write_card_to_states(selected_card, i)
# Update states
self.s.update_first_player_trick_nr_score()
rewards = self.s.return_reward_list()
# Scale rewards
rewards = [r/self.reward_scale for r in rewards]
reward1 = rewards[0]*self.reward_scale
reward2 = rewards[1]*self.reward_scale
reward3 = rewards[2]*self.reward_scale
reward4 = rewards[3]*self.reward_scale
# Save action, states and reward in memory
for i in range(len(states_list)):
if i < 7:
self.memory.add((states_list[i],
action_list[i],
0, #reward
states_list[i+1]))
else:
self.memory.add((states_list[i],
action_list[i],
rewards[0],
np.zeros(np.array(state).shape).tolist()))
# Sample mini-batch from memory
batch = self.memory.sample(self.batch_size)
states = np.array([each[0] for each in batch])
actions = np.array([each[1] for each in batch])
rewards = np.array([each[2] for each in batch])
next_states = np.array([each[3] for each in batch])
# Train network
target_Qs = sess.run(self.QNetworkCard.output,
feed_dict={self.QNetworkCard.inputs_: next_states}) #states})
targets = rewards + self.gamma * np.max(target_Qs, axis=1)
loss, _ = sess.run([self.QNetworkCard.loss, self.QNetworkCard.opt],
feed_dict={self.QNetworkCard.inputs_: states,
self.QNetworkCard.targetQs_: targets,
self.QNetworkCard.actions_: actions})
total_reward1+=reward1
total_reward2+=reward2
total_reward3+=reward3
total_reward4+=reward4
total_loss+=loss
else:
rewards = [0,0,0,0]
show_every = 500
if e%show_every==0:
print('Episode: {}'.format(e),
'Avg. total reward: {:.1f}'.format(total_reward1/show_every),
'Avg. training loss: {:.5f}'.format(total_loss/show_every))
reward_list1.append(total_reward1/show_every)
reward_list2.append(total_reward2/show_every)
reward_list3.append(total_reward3/show_every)
reward_list4.append(total_reward4/show_every)
loss_list.append(total_loss/show_every)
total_reward1=0
total_reward2=0
total_reward3=0
total_reward4=0
total_loss=0
if e%1000==0:
# Plot reward ~ epochs
h.plot_reward(reward_list1,
reward_list2,
reward_list3,
reward_list4, show_every)
# Plot loss ~ epochs
h.plot_loss(loss_list)
# Save weights of NN
saver.save(sess, "checkpoints/schafkopf.ckpt")
# Print average reward
print('Total reward: \n')
print('0: {:.1f}, \n1: {:.1f}, \n2: {:.1f}, \n3: {:.1f}'.format(sum(reward_list1),
sum(reward_list2),
sum(reward_list3),
sum(reward_list4)))
def apply_model(self):
saver = tf.train.Saver()
reward_list1 = []
reward_list2 = []
reward_list3 = []
reward_list4 = []
#loss_list= []
total_reward1=0
total_reward2=0
total_reward3=0
total_reward4=0
#total_loss=0
with tf.Session() as sess:
# Initialize variables
#sess.run(tf.global_variables_initializer())
# Restore model
saver = tf.train.import_meta_graph('C:/Users/claus/OneDrive/Documents/Schafkopf_RL/Schafkopf_RL-master/checkpoints/schafkopf.ckpt.meta')
saver.restore(sess, tf.train.latest_checkpoint('C:/Users/claus/OneDrive/Documents/Schafkopf_RL/Schafkopf_RL-master/checkpoints/'))
for e in range(1, self.train_episodes+1):
self.s.reset_epsiode()
self.s.dealing()
for i in range(4):
possible_games = self.s.return_possible_games(i)
if len(possible_games) > 0:
selected_game = random.choice(possible_games)
if selected_game != [None, None]:
self.s.write_game_to_states(selected_game, i)
# Simulate playing
if self.s.return_state_overall()['game'] != [None, None]:
states_list = []
action_list = []
while self.s.return_state_overall()['trick_number'] < 8:
first_player = self.s.return_state_overall()['first_player']
for i in range(4):
possible_cards = self.s.return_possbile_cards(i)
# Explore or Exploit
explore_p = self.explore_stop + \
(self.explore_start - self.explore_stop)*np.exp(-self.decay_rate*1*e)
if explore_p > np.random.rand() or \
self.s.return_state_player((first_player+i)%4)['player_id']!=0:
selected_card = random.choice(possible_cards)
if self.s.return_state_player((first_player+i)%4)['player_id']==0:
state = self.s.return_state_select_card(player_id=0)
state = np.array(state)
action = self.rules.get_index(selected_card, 'card')
states_list.append(state)
action_list.append(action)
else:
state = self.s.return_state_select_card(player_id=0)
state = np.array(state)
feed = {self.QNetworkCard.inputs_: state.reshape((1, *state.shape))}
Qs = sess.run(self.QNetworkCard.output, feed_dict=feed)
Qs = Qs[0].tolist()
possible_actions = [self.rules.get_index(p_g, 'card') for p_g in possible_cards]
Qs_subset = [i for i in Qs if Qs.index(i) in possible_actions]
action = np.argmax(Qs_subset)
action = Qs.index(max(Qs_subset))
selected_card = self.rules.cards[action]
states_list.append(state)
action_list.append(action)
# Write cards to states
self.s.write_card_to_states(selected_card, i)
# Update states
self.s.update_first_player_trick_nr_score()
rewards = self.s.return_reward_list()
# Scale rewards
rewards = [r/self.reward_scale for r in rewards]
reward1 = rewards[0]*self.reward_scale
reward2 = rewards[1]*self.reward_scale
reward3 = rewards[2]*self.reward_scale
reward4 = rewards[3]*self.reward_scale
# Save action, states and reward in memory
for i in range(len(states_list)):
if i < 7:
self.memory.add((states_list[i],
action_list[i],
0, #reward
states_list[i+1]))
else:
self.memory.add((states_list[i],
action_list[i],
rewards[0],
np.zeros(np.array(state).shape).tolist()))
# Sample mini-batch from memory
#batch = self.memory.sample(self.batch_size)
#states = np.array([each[0] for each in batch])
#actions = np.array([each[1] for each in batch])
#rewards = np.array([each[2] for each in batch])
#next_states = np.array([each[3] for each in batch])
# Train network
#target_Qs = sess.run(self.QNetworkCard.output,
# feed_dict={self.QNetworkCard.inputs_: next_states}) #states})
#targets = rewards + self.gamma * np.max(target_Qs, axis=1)
#loss, _ = sess.run([self.QNetworkCard.loss, self.QNetworkCard.opt],
# feed_dict={self.QNetworkCard.inputs_: states,
# self.QNetworkCard.targetQs_: targets,
# self.QNetworkCard.actions_: actions})
total_reward1+=reward1
total_reward2+=reward2
total_reward3+=reward3
total_reward4+=reward4
#total_loss+=loss
else:
rewards = [0,0,0,0]
show_every = 500
if e%show_every==0:
print('Episode: {}'.format(e),
'Avg. total reward: {:.1f}'.format(total_reward1/show_every))
reward_list1.append(total_reward1/show_every)
reward_list2.append(total_reward2/show_every)
reward_list3.append(total_reward3/show_every)
reward_list4.append(total_reward4/show_every)
#loss_list.append(total_loss/show_every)
total_reward1=0
total_reward2=0
total_reward3=0
total_reward4=0
#total_loss=0
if e%1000==0:
# Plot reward ~ epochs
h.plot_reward(reward_list1,
reward_list2,
reward_list3,
reward_list4, show_every)
# Plot loss ~ epochs
#h.plot_loss(loss_list)
# Save weights of NN
#saver.save(sess, "checkpoints/schafkopf.ckpt")
# Print average reward
print('Total reward: \n')
print('0: {:.1f}, \n1: {:.1f}, \n2: {:.1f}, \n3: {:.1f}'.format(sum(reward_list1),
sum(reward_list2),
sum(reward_list3),
sum(reward_list4)))