turn this jyputer notebook into python 3 script : # Init and helper functions
import tensorflow as tf
import numpy as np
import PIL
import urllib, cStringIO
import glob
from IPython.core.display import Markdown
from IPython.display import Image, display
import helper_functions as hf
import tensorflow_chessbot
np.set_printoptions(precision=2, suppress=True)
Let's load the tiles in for the training and test dataset, and then split them in a 90/10 ratio
All tiles with pieces in random organizations
all_paths = np.array(glob.glob("tiles/train_tiles_C//.png")) # TODO : (set labels correctly)
Shuffle order of paths so when we split the train/test sets the order of files doesn't affect it
np.random.shuffle(all_paths)
ratio = 0.9 # training / testing ratio
divider = int(len(all_paths) * ratio)
train_paths = all_paths[:divider]
test_paths = all_paths[divider:]
Training dataset
Generated by programmatic screenshots of lichess.org/editor/
print "Loading %d Training tiles" % train_paths.size
train_images, train_labels = hf.loadFENtiles(train_paths) # Load from generated set
Test dataset, taken from screenshots of the starting position
print "Loading %d Training tiles" % test_paths.size
test_images, test_labels = hf.loadFENtiles(test_paths) # Load from generated set
train_dataset = hf.DataSet(train_images, train_labels, dtype=tf.float32)
test_dataset = hf.DataSet(test_images, test_labels, dtype=tf.float32)
Loading 8294 Training tiles
. . . . . . . . . Done
Loading 922 Training tiles
. Done
Looks good. Now that we've loaded the data, let's build up a deep CNN classifier based off of this beginner tutorial on tensorflow.
Start Interactive session for rest of notebook (else we'd want to close session)
sess = tf.InteractiveSession()
Training vs loading existing model
do_training = False
Number of steps
N = 10000
if do_training:
#Initialize session
sess.run(tf.initialize_all_variables())
# Training
print "Training for %d steps..." % N
for i in range(N):
# Get next batch for training
batch_xs, batch_ys = train_dataset.next_batch(100)
# Print out progress to screen
if ((i+1) % 100) == 0:
train_accuracy = accuracy.eval(feed_dict={
x:batch_xs, y_: batch_ys, keep_prob: 1.0})
print "\n\t%d/%d, training accuracy %g" % (i+1, N, train_accuracy),
elif ((i+1) % 10) == 0:
print '.',
# Train model with batch
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})
print "Finished training."
# Save model checkpoint
save_path = saver.save(sess, "saved_models/model_%d.ckpt" % N)
print "Model saved in file: ", save_path
else:
# Restore model from checkpoint
model_name = "saved_models/model_%d.ckpt" % N
print "Loading model '%s'" % model_name
saver.restore(sess, model_name)
print "Model restored."
if mistake_indices.size > 0:
print "%d mistakes:" % mistake_indices.size
for idx in np.random.choice(mistake_indices, 5, replace=False):
a,b = test_dataset.labels[idx], guessed[idx]
print "---"
print "\t#%d | Actual: '%s', Guessed: '%s'" % (idx, hf.label2Name(a),hf.labelIndex2Name(b))
print "Actual:",a
print " Guess:",guess_prob[idx,:]
hf.display_array(np.reshape(test_dataset.images[idx,:],[32,32]))
else:
print "%d mistakes" % mistake_indices.size
0 mistakes
It looks like it's been learning that pieces have black borders, and since this pieceSet didn't, and it was a small part of the training set, it just fails and thinks we're looking at blank squares, more training data! From the label probabilities, it did a reasonable job of thinking the pieces were white, and their second best guesses tended to be close to the right answer, the blank spaces just won out.
Also, lets look at several random selections, including successes.
Certainly! Below is the converted Python 3 script based on your provided Jupyter Notebook. This script includes necessary modifications to ensure compatibility with Python 3, such as updating print statements, replacing deprecated modules, and adjusting TensorFlow functions. Additionally, it removes Jupyter-specific display functions and replaces them with alternatives suitable for a standalone script.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TensorFlow Chessbot CNN Training Script
This script trains a Convolutional Neural Network (CNN) to classify chess pieces
from image tiles. It can either train a new model or load an existing one for evaluation.
Dependencies:
- TensorFlow 1.x
- NumPy
- Pillow
- glob
- helper_functions (custom module)
- tensorflow_chessbot (custom module)
Usage:
python3 train_chessbot_cnn.py
Ensure that the necessary training and testing data are available in the specified directories.
"""
import tensorflow as tf
import numpy as np
import PIL
import urllib
import io
import glob
from helper_functions import loadFENtiles, DataSet, label2Name, labelIndex2Name, display_array
import tensorflow_chessbot
import random
# Set NumPy print options
np.set_printoptions(precision=2, suppress=True)
def main():
# Load the tiles for the training and test dataset, then split them in a 90/10 ratio
# All tiles with pieces in random organizations
all_paths = np.array(glob.glob("tiles/train_tiles_C/*/*.png")) # TODO: Set labels correctly
# Shuffle order of paths so when we split the train/test sets the order of files doesn't affect it
np.random.shuffle(all_paths)
ratio = 0.9 # training / testing ratio
divider = int(len(all_paths) * ratio)
train_paths = all_paths[:divider]
test_paths = all_paths[divider:]
# Training dataset
# Generated by programmatic screenshots of lichess.org/editor/<FEN-string>
print(f"Loading {train_paths.size} Training tiles")
train_images, train_labels = loadFENtiles(train_paths) # Load from generated set
# Test dataset, taken from screenshots of the starting position
print(f"Loading {test_paths.size} Test tiles")
test_images, test_labels = loadFENtiles(test_paths) # Load from generated set
train_dataset = DataSet(train_images, train_labels, dtype=tf.float32)
test_dataset = DataSet(test_images, test_labels, dtype=tf.float32)
# Build the CNN classifier
print("Setting up CNN...")
def weight_variable(shape, name=""):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial, name=name)
def bias_variable(shape, name=""):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial, name=name)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x, name=""):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME', name=name)
x = tf.placeholder(tf.float32, [None, 32 * 32], name='Input')
# First layer: 32 features
W_conv1 = weight_variable([5, 5, 1, 32], name='W1')
b_conv1 = bias_variable([32], name='B1')
x_image = tf.reshape(x, [-1, 32, 32, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1, name='Conv1')
h_pool1 = max_pool_2x2(h_conv1, name='Pool1')
# Second convolutional layer: 64 features
W_conv2 = weight_variable([5, 5, 32, 64], name='W2')
b_conv2 = bias_variable([64], name='B2')
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2, name='Conv2')
h_pool2 = max_pool_2x2(h_conv2, name='Pool2')
# Densely connected layer: 1024 neurons, image size now 8x8
W_fc1 = weight_variable([8 * 8 * 64, 1024], name='W3')
b_fc1 = bias_variable([1024], name='B3')
h_pool2_flat = tf.reshape(h_pool2, [-1, 8 * 8 * 64], name='Pool3')
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1, name='MatMult3')
# Dropout
keep_prob = tf.placeholder(tf.float32, name='KeepProb')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob, name='Drop4')
# Readout layer: softmax, 13 features
W_fc2 = weight_variable([1024, 13], name='W5')
b_fc2 = bias_variable([13], name='B5')
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name='Ypredict')
# Ground truth labels
y_ = tf.placeholder(tf.float32, [None, 13], name='Ytruth')
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv), name='CrossEntropy')
# Train step
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1), name='CorrectPrediction')
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='Accuracy')
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Training vs loading existing model
do_training = False # Set to True to train a new model
# Number of steps
N = 10000
with tf.Session() as sess:
if do_training:
# Initialize variables
sess.run(tf.global_variables_initializer())
# Training
print(f"Training for {N} steps...")
for i in range(N):
# Get next batch for training
batch_xs, batch_ys = train_dataset.next_batch(100)
# Print out progress to screen
if (i + 1) % 100 == 0:
train_accuracy = sess.run(accuracy, feed_dict={
x: batch_xs, y_: batch_ys, keep_prob: 1.0})
print(f"\n\t{i+1}/{N}, training accuracy {train_accuracy}", end='')
elif (i + 1) % 10 == 0:
print('.', end='', flush=True)
# Train model with batch
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})
print("\nFinished training.")
# Save model checkpoint
save_path = saver.save(sess, f"saved_models/model_{N}.ckpt")
print(f"Model saved in file: {save_path}")
else:
# Restore model from checkpoint
model_name = f"saved_models/model_{N}.ckpt"
print(f"Loading model '{model_name}'")
saver.restore(sess, model_name)
print("Model restored.")
# Testing
test_accuracy = sess.run(accuracy, feed_dict={
x: test_dataset.images,
y_: test_dataset.labels,
keep_prob: 1.0
})
print(f"Accuracy: {test_accuracy}\n")
# Analyze mistakes
print("Analyzing mistakes...")
mistakes = tf.where(tf.logical_not(correct_prediction))
mistake_indices = sess.run(mistakes, feed_dict={
x: test_dataset.images,
y_: test_dataset.labels,
keep_prob: 1.0
}).flatten()
guess_prob, guessed = sess.run([y_conv, tf.argmax(y_conv, 1)], feed_dict={
x: test_dataset.images,
keep_prob: 1.0
})
if mistake_indices.size > 0:
print(f"{mistake_indices.size} mistakes:")
selected_indices = np.random.choice(mistake_indices, min(5, mistake_indices.size), replace=False)
for idx in selected_indices:
actual_label = test_dataset.labels[idx]
guessed_label = guessed[idx]
actual_name = label2Name(actual_label)
guessed_name = labelIndex2Name(guessed_label)
print("---")
print(f"\t#{idx} | Actual: '{actual_name}', Guessed: '{guessed_name}'")
print(f"Actual: {actual_label}")
print(f"Guess: {guess_prob[idx, :]}")
# Display the image using PIL
img_array = test_dataset.images[idx, :].reshape(32, 32)
display_array(img_array)
else:
print("0 mistakes")
# Display several random selections, including successes
print("\nDisplaying several random selections (including successes):")
sample_indices = np.random.choice(test_dataset.num_examples, 5, replace=False)
for idx in sample_indices:
actual_label = test_dataset.labels[idx]
guessed_label = guessed[idx]
actual_name = label2Name(actual_label)
guessed_name = labelIndex2Name(guessed_label)
print(f"#{idx} | Actual: '{actual_name}', Guessed: '{guessed_name}'")
# Display the image using PIL
img_array = test_dataset.images[idx, :].reshape(32, 32)
display_array(img_array)
if __name__ == "__main__":
main()
Key Modifications and Considerations:
Print Statements:
Updated all print statements to use Python 3 syntax with parentheses.
Removed cStringIO:
Replaced import cStringIO with import io, as cStringIO is not available in Python 3.
TensorFlow Compatibility:
The script uses TensorFlow 1.x style (e.g., tf.Session(), tf.placeholder). Ensure that TensorFlow 1.x is installed. If you have TensorFlow 2.x, you might need to install TensorFlow 1.x or adjust the code for compatibility using tf.compat.v1.
Replaced tf.initialize_all_variables() with tf.global_variables_initializer().
Display Functions:
Removed Jupyter-specific display functions such as IPython.display.Image and display. Instead, the script uses a custom display_array function from helper_functions. Ensure that this function is appropriately defined to display images in a non-Jupyter environment, possibly using matplotlib or saving images to disk.
Handling Custom Modules:
The script assumes that helper_functions and tensorflow_chessbot are available in the Python path. Ensure these modules are present and compatible with Python 3.
Random Selection and Display:
Used np.random.choice with replace=False safely to handle cases where there are fewer mistakes than the number of samples you want to display.
Main Function and Guard:
Encapsulated the script logic within a main() function and added the if __name__ == "__main__": guard to allow the script to be imported without executing the training process.
Shebang and Encoding:
Added a shebang (#!/usr/bin/env python3) and encoding declaration for better portability and clarity.
Comments and Documentation:
Included a docstring at the beginning of the script to explain its purpose, dependencies, and usage.
Additional Recommendations:
Virtual Environment:
Use a Python virtual environment to manage dependencies and ensure compatibility.
TensorFlow Version:
If possible, consider upgrading to TensorFlow 2.x for improved performance and easier syntax. This will, however, require significant code changes, especially replacing tf.Session(), tf.placeholder, and other deprecated functionalities.
Visualization:
For image display in a script, consider using matplotlib to visualize images inline or save them to disk for later review.
Configuration Management:
Use configuration files or command-line arguments to manage parameters like training steps, batch size, learning rate, etc.
Ensure that all dependencies are installed and properly configured before running the script. You can install the required packages using pip:
pip install tensorflow==1.15 numpy pillow
Replace 1.15 with the appropriate TensorFlow 1.x version you intend to use. If you need to switch to TensorFlow 2.x, additional code adjustments will be necessary.
For a production-ready script, consider adding error handling, argument parsing (using argparse), logging instead of print statements, and configuration through external files or command-line arguments.