From bfe38a8a2df7b934d479b65770c7b430354cb734 Mon Sep 17 00:00:00 2001 From: Alexander Munch-Hansen Date: Wed, 10 Apr 2019 22:37:46 +0200 Subject: [PATCH] Model builder --- tmp/tensor.py | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 tmp/tensor.py diff --git a/tmp/tensor.py b/tmp/tensor.py new file mode 100644 index 00000000..432fbe38 --- /dev/null +++ b/tmp/tensor.py @@ -0,0 +1,77 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +import tensorflow as tf +import tensorflow_datasets as tfds +from tensorflow.python.keras import datasets, layers, models +import glob +import numpy as np +import cv2 + +#(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data() + +#print(train_images[0]) + +#exit() +training_img = [] +training_labels = [] + +test_img = [] +test_labels_ = [] + + +for _ in range(10): + for filename in glob.glob(f"../training_images/rook/*_square/*.png")[:-50]: + training_img.append(cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2GRAY)) + training_labels.append(1) + + +for _ in range(10): + for filename in glob.glob(f"../training_images/knight/*_square/*.png")[:-50]: + training_img.append(cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2GRAY)) + training_labels.append(0) + +for _ in range(5): + for filename in glob.glob(f"../training_images/rook/*_square/*.png")[-50:]: + test_img.append(cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2GRAY)) + test_labels_.append(1) + +for _ in range(5): + for filename in glob.glob(f"../training_images/knight/*_square/*.png")[-50:]: + test_img.append(cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2GRAY)) + test_labels_.append(0) + + +width, height = training_img[0].shape + +training_img = np.array(training_img).reshape((len(training_img), width, height, 1)) +test_img = np.array(test_img).reshape((len(test_img),width, height, 1)) + +# Normalize pixel values to be between 0 and 1 +train_images, test_images = training_img / 255.0, test_img / 255.0 + +model = models.Sequential() +model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(width, height, 1))) +model.add(layers.MaxPooling2D((2, 2))) +model.add(layers.Conv2D(64, (3, 3), activation='relu')) +model.add(layers.MaxPooling2D((2, 2))) +model.add(layers.Conv2D(64, (3, 3), activation='relu')) + +model.add(layers.Flatten()) +model.add(layers.Dense(64, activation='relu')) +model.add(layers.Dense(2, activation='softmax')) + +model.summary() + +model.compile(optimizer='adam', + loss='sparse_categorical_crossentropy', + metrics=['accuracy']) + +model.fit(train_images, training_labels, epochs=5) + +test_loss, test_acc = model.evaluate(test_images, test_labels_) + +print(test_acc) + +# Save entire model to a HDF5 file +model.save('test_chess_model.h5') +