Skip to content

Commit b52f8a9

Browse files
committed
Re-add the final version.
1 parent c51504a commit b52f8a9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Diff for: tictacnet.py

+53
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,57 @@ def move_accuracy(y_test, y_pred):
1010
"""A predicted move is correct if the largest output is 1 in the test vector."""
1111
return np.mean(y_test[y_pred == np.max(y_pred, axis=1, keepdims=True)])
1212

13+
1314
np.random.seed(1234)
15+
16+
df = pd.read_csv("tictactoe-data.csv")
17+
print("Scores:", Counter(df["score"]))
18+
19+
# Input is all the board features (2x9 squares) plus the turn.
20+
X = df.iloc[:, list(range(18)) + [-2]]
21+
22+
# Target variables are the possible move squares.
23+
moves = df.iloc[:, list(range(18, 27))]
24+
# To predict score instead, use this as the target:
25+
# score = pd.get_dummies(df['score'])
26+
27+
X_train, X_test, y_train, y_test = train_test_split(X, moves, test_size=0.2)
28+
29+
print("Train/test shapes:", X_train.shape, X_test.shape, y_train.shape, y_test.shape)
30+
31+
model = tf.keras.Sequential()
32+
model.add(tf.keras.layers.Dense(128, activation="relu", input_dim=X.shape[1]))
33+
model.add(tf.keras.layers.Dropout(0.3))
34+
model.add(tf.keras.layers.Dense(64, activation="relu"))
35+
model.add(tf.keras.layers.Dropout(0.3))
36+
model.add(tf.keras.layers.Dense(32, activation="relu"))
37+
model.add(tf.keras.layers.Dropout(0.3))
38+
model.add(tf.keras.layers.Dense(moves.shape[1], activation="softmax"))
39+
40+
# For a multi-class classification problem
41+
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
42+
43+
print(model.summary())
44+
45+
# This is not needed, but lets you view a lot of useful information using
46+
# > tensorboard --logdir logs
47+
# at your terminal prompt.
48+
tensorboard_callback = tf.keras.callbacks.TensorBoard(
49+
log_dir="./logs",
50+
histogram_freq=1,
51+
batch_size=100,
52+
write_graph=True,
53+
write_grads=True,
54+
write_images=True,
55+
)
56+
model.fit(
57+
X_train,
58+
y_train,
59+
epochs=100,
60+
batch_size=16,
61+
validation_data=[X_test, y_test],
62+
callbacks=[tensorboard_callback],
63+
)
64+
65+
print("accuracy:", model.evaluate(X_test, y_test))
66+
print("Custom accuracy:", move_accuracy(y_test.values, model.predict(X_test)))

0 commit comments

Comments
 (0)