improve cnn : Epoch 100/100
124/124 ━━━━━━━━━━━━━━━━━━━━ 1s 6ms/step - accuracy: 0.8963 - loss: 0.3435 - val_accuracy: 0.8532 - val_loss: 0.8805 : # Import necessary libraries
import tensorflow as tf
import os
import numpy as np
import glob
from PIL import Image
import matplotlib.pyplot as plt
def getFENtileLabel(fen,letter,number):
"""Given a fen string and a rank (number) and file (letter), return label vector"""
l2i = lambda l: ord(l)-ord('A') # letter to index
number = 8-number # FEN has order backwards
piece_letter = fen[number*8+number + l2i(letter)]
label = np.zeros(13, dtype=np.uint8)
label['1KQRBNPkqrbnp'.find(piece_letter)] = 1 # note the 1 instead of ' ' due to FEN notation
We ignore shorter FENs with numbers > 1 because we generate the FENs ourselves
return label
We'll define the 12 pieces and 1 spacewith single characters
KQRBNPkqrbnp
def getLabelForSquare(letter,number):
"""Given letter and number (say 'B3'), return one-hot label vector
(12 pieces + 1 space == no piece, so 13-long vector)"""
l2i = lambda l: ord(l)-ord('A') # letter to index
piece2Label = lambda piece: ' KQRBNPkqrbnp'.find(piece)
def loadLabels(image_filepaths):
"""Load label vectors from list of image filepaths"""
Each filepath contains which square we're looking at,
since we're in starter position, we know which
square has which piece, 12 distinct pieces
(6 white and 6 black) and 1 as empty = 13 labels
training_data = np.zeros([image_filepaths.size, 13], dtype=np.float64)
for i, image_filepath in enumerate(image_filepaths):
training_data[i,:] = getLabelForSquare(image_filepath[-6],int(image_filepath[-5]))
return training_data
def loadImages(image_filepaths):
Each tile is a 32x32 grayscale image, add extra axis for working with MNIST Data format
training_data = np.zeros([image_filepaths.size, 32, 32, 1], dtype=np.uint8)
for i, image_filepath in enumerate(image_filepaths):
if i % 100 == 0:
print("On #%d/%d : %s" % (i,image_filepaths.size, image_filepath))
img = Image.open(image_filepath)
training_data[i,:,:,0] = np.asarray(img, dtype=np.uint8)
return training_data
Set NumPy print options for better readability
np.set_printoptions(precision=2, suppress=True)
Load and prepare the data
Adjust the path according to your data location
data_path = "tiles//.png" # Update this path as needed
all_paths = np.array(glob.glob(data_path)) # Ensure labels are set correctly
Verify that the data path contains files
if len(all_paths) == 0:
print(f"No image files found in the path: {data_path}")
exit(1)
Shuffle the paths
np.random.shuffle(all_paths)
Split the data into training and testing sets (90/10 ratio)
ratio = 0.9 # Training/testing ratio
divider = int(len(all_paths) * ratio)
train_paths = all_paths[:divider]
test_paths = all_paths[divider:]
Load training dataset
print(f"Loading {train_paths.size} Training tiles")
train_images, train_labels = loadFENtiles(train_paths) # Ensure this function works correctly
do_training = True # Set to True to train the model
epochs = 25 # Adjust the number of epochs as needed
batch_size = 100 # Batch size for training
if do_training:
# Train the model
print(f"Training for {epochs} epochs...")
model.fit(train_images, train_labels, epochs=epochs, batch_size=batch_size,
validation_data=(test_images, test_labels), verbose=1)
print("Finished training.")
code
# Ensure 'saved_models' directory exists
if not os.path.exists('saved_models'):
os.makedirs('saved_models')
# Save the trained model
model.save('saved_models/model_{}.h5'.format(epochs))
print(f"Model saved in file: saved_models/model_{epochs}.h5")
else:
# Load the pre-trained model
model_name = 'saved_models/model_{}.h5'.format(epochs)
print(f"Loading model '{model_name}'")
if os.path.exists(model_name):
model = tf.keras.models.load_model(model_name)
print("Model loaded.")
else:
print(f"Model file '{model_name}' not found.")
exit(1)
Evaluate the model on the testing dataset
test_loss, test_accuracy = model.evaluate(test_images, test_labels, verbose=0)
print(f"Accuracy on test set: {test_accuracy * 100:.2f}%\n")
Improving your Convolutional Neural Network (CNN) for classifying chessboard tiles involves several strategies, including enhancing the model architecture, optimizing training processes, implementing data augmentation, and fine-tuning hyperparameters. Below, I provide a comprehensive guide to upgrade your current CNN setup, along with an improved version of your code incorporating these enhancements.
1. Analyze Current Model Performance
From your training log:
Training Accuracy: ~89.63%
Validation Accuracy: ~85.32%
Training Loss: 0.3435
Validation Loss: 0.8805
The gap between training and validation accuracy indicates potential overfitting. To mitigate this, consider the following strategies:
Data Augmentation: Increase the diversity of your training data to help the model generalize better.
Model Architecture Enhancements: Incorporate additional layers, batch normalization, and regularization techniques.
Hyperparameter Tuning: Optimize learning rates, batch sizes, and dropout rates.
Use Transfer Learning: Leverage pretrained models for better feature extraction (though more beneficial for larger datasets and more complex tasks).
2. Implementing Improvements
a. Data Augmentation
Data augmentation artificially increases the diversity of your dataset by applying random transformations, helping the model generalize better.
python
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Define data augmentation parameters
datagen = ImageDataGenerator(
rotation_range=15, # Random rotations
width_shift_range=0.1, # Horizontal shifts
height_shift_range=0.1, # Vertical shifts
zoom_range=0.1, # Zoom
horizontal_flip=True, # Horizontal flips
fill_mode='nearest' # Fill mode for new pixels
)
b. Enhancing the Model Architecture
Incorporate additional convolutional layers, batch normalization, and adjust dropout rates to improve learning and reduce overfitting.
Convolutional Layers: Increased the number and depth of convolutional layers to capture more complex features.
Batch Normalization: Added after convolutional layers to stabilize and accelerate training.
Dropout Layers: Adjusted dropout rates to better prevent overfitting.
Regularization: Consider adding kernel regularizers to convolutional layers if overfitting persists.
c. Optimizing Training Process
Adjust the learning rate, utilize a learning rate scheduler, and consider early stopping to prevent overfitting.
python
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping
# Compile the model with a lower learning rate
optimizer = Adam(learning_rate=1e-4)
model.compile(optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy'])
# Define callbacks
lr_reduction = ReduceLROnPlateau(monitor='val_loss',
patience=3,
factor=0.5,
min_lr=1e-6,
verbose=1)
early_stop = EarlyStopping(monitor='val_loss',
patience=10,
restore_best_weights=True,
verbose=1)
d. Integrating Data Augmentation and Callbacks into Training
Modify the training process to include data augmentation and callbacks.
python
if do_training:
# Fit the model using data augmentation
print(f"Training for {epochs} epochs with data augmentation...")
history = model.fit(
datagen.flow(train_images, train_labels, batch_size=batch_size),
epochs=epochs,
validation_data=(test_images, test_labels),
steps_per_epoch=len(train_images) // batch_size,
callbacks=[lr_reduction, early_stop],
verbose=1
)
print("Finished training.")
# Save the trained model
if not os.path.exists('saved_models'):
os.makedirs('saved_models')
model.save('saved_models/model_improved.h5')
print(f"Model saved in file: saved_models/model_improved.h5")
e. Preprocessing Enhancements
Normalize image data to help the model converge faster and perform better.
Ensure that your label encoding correctly represents all classes. It seems there's a minor indexing issue in your getFENtileLabel function. Here's a refined version:
python
def getFENtileLabel(fen, letter, number):
"""Given a FEN string and a rank (number) and file (letter), return label vector."""
l2i = lambda l: ord(l.upper()) - ord('A') # Ensures uppercase for indexing
number = 8 - number # Adjust FEN rank
piece_letter = fen[number * 8 + l2i(letter)]
label = np.zeros(13, dtype=np.uint8)
index = ' KQRBNPkqrbnp'.find(piece_letter)
if index == -1:
index = 0 # Default to empty if not found
label[index] = 1
return label
3. Full Improved Code
Below is the complete improved version of your CNN with the aforementioned enhancements:
python
4. Additional Recommendations
a. Data Quality and Quantity
Ensure that your dataset is large and diverse enough to represent all possible board states. If the dataset is limited, consider generating synthetic data or augmenting it further.
b. Class Imbalance Handling
If certain classes (pieces) are underrepresented, implement strategies to handle class imbalance:
Class Weights: Assign higher weights to underrepresented classes during training.
Balanced Sampling: Ensure that each batch has a balanced number of samples from each class.
python
from sklearn.utils import class_weight
# Calculate class weights
class_weights = class_weight.compute_class_weight(
class_weight='balanced',
classes=np.unique(true_labels),
y=true_labels
)
class_weights = dict(enumerate(class_weights))
While the improved CNN architecture provided is robust, experimenting with different architectures like ResNet, DenseNet, or MobileNet (with transfer learning) can yield better performance, especially if you scale up image sizes and datasets.
d. Monitor Training with TensorBoard
Integrate TensorBoard to visualize training metrics and gain deeper insights into the model's performance.
python
from tensorflow.keras.callbacks import TensorBoard
import datetime
# Define TensorBoard callback
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)
# Include in callbacks
callbacks = [lr_reduction, early_stop, tensorboard_callback]
# Launch TensorBoard
# In your terminal, run: tensorboard --logdir=logs/fit
e. Fine-Tune Hyperparameters
Use hyperparameter tuning libraries like Keras Tuner or Optuna to systematically explore and find the optimal set of hyperparameters for your model.
5. Expected Outcomes
By incorporating these enhancements, you should observe:
Improved Validation Accuracy: Likely increasing closer to or surpassing training accuracy.
Reduced Overfitting: Enhanced generalization to unseen data.
Faster Convergence: Through normalized data and optimized learning rates.
Better Insights: Via visualization tools like TensorBoard.
Conclusion
Improving your CNN involves a combination of architectural enhancements, better training practices, and more robust data handling. The provided code modifications and recommendations should serve as a solid foundation for achieving higher accuracy and better generalization in your chessboard tile classification task. Remember to iteratively experiment and validate each change to understand its impact on your model's performance.