-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdual_network.py
More file actions
79 lines (64 loc) · 2.25 KB
/
dual_network.py
File metadata and controls
79 lines (64 loc) · 2.25 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
67
68
69
70
71
72
73
74
75
76
77
78
79
# ====================
# Creating the Dual Network
# ====================
# Importing packages
from tensorflow.keras.layers import Activation, Add, BatchNormalization, Conv2D, Dense, GlobalAveragePooling2D, Input
from tensorflow.keras.models import Model
from tensorflow.keras.regularizers import l2
from tensorflow.keras import backend as K
import os
# Preparing parameters
DN_FILTERS = 128 # Number of kernels in the convolutional layer (256 in the original version)
DN_RESIDUAL_NUM = 16 # Number of residual blocks (19 in the original version)
DN_INPUT_SHAPE = (3, 3, 6) # Input shape
DN_OUTPUT_SIZE = 9 + 4 * 2 # Number of actions (placement locations (3*3))
# Creating the convolutional layer
def conv(filters):
return Conv2D(filters, 3, padding='same', use_bias=False,
kernel_initializer='he_normal', kernel_regularizer=l2(0.0005))
# Creating the residual block
def residual_block():
def f(x):
sc = x
x = conv(DN_FILTERS)(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = conv(DN_FILTERS)(x)
x = BatchNormalization()(x)
x = Add()([x, sc])
x = Activation('relu')(x)
return x
return f
# Creating the dual network
def dual_network():
# Do nothing if the model is already created
if os.path.exists('./model/best.keras'):
return
# Input layer
input = Input(shape=DN_INPUT_SHAPE)
# Convolutional layer
x = conv(DN_FILTERS)(input)
x = BatchNormalization()(x)
x = Activation('relu')(x)
# Residual blocks x 16
for i in range(DN_RESIDUAL_NUM):
x = residual_block()(x)
# Pooling layer
x = GlobalAveragePooling2D()(x)
# Policy output
p = Dense(DN_OUTPUT_SIZE, kernel_regularizer=l2(0.0005),
activation='softmax', name='pi')(x)
# Value output
v = Dense(1, kernel_regularizer=l2(0.0005))(x)
v = Activation('tanh', name='v')(v)
# Creating the model
model = Model(inputs=input, outputs=[p, v])
# Saving the model
os.makedirs('./model/', exist_ok=True) # Create folder if it does not exist
model.save('./model/best.keras') # Best player's model
# Clearing the model
K.clear_session()
del model
# Running the function
if __name__ == '__main__':
dual_network()