diff --git a/doc/pub/NeuralNet/html/._NeuralNet-bs000.html b/doc/pub/NeuralNet/html/._NeuralNet-bs000.html index 5b3bcff7c..da168971c 100644 --- a/doc/pub/NeuralNet/html/._NeuralNet-bs000.html +++ b/doc/pub/NeuralNet/html/._NeuralNet-bs000.html @@ -115,7 +115,15 @@ Automatically generated HTML file from DocOnce source None, '___sec47'), ('scikit-learn implementation', 2, None, '___sec48'), - ('And then with Tensorflow', 2, None, '___sec49')]} + ('Building neural networks in Tensorflow and Keras', + 2, + None, + '___sec49'), + ('Tensorflow', 2, None, '___sec50'), + ('Collect and pre-process data', 2, None, '___sec51'), + ('Using TensorFlow backend', 2, None, '___sec52'), + ('Optimizing and using gradient descent', 2, None, '___sec53'), + ('Using Keras', 2, None, '___sec54')]} end of tocinfo -->
@@ -202,7 +210,12 @@ MathJax.Hub.Config({+Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. +
+In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. + +
diff --git a/doc/pub/NeuralNet/html/._NeuralNet-bs051.html b/doc/pub/NeuralNet/html/._NeuralNet-bs051.html new file mode 100644 index 000000000..41244e26b --- /dev/null +++ b/doc/pub/NeuralNet/html/._NeuralNet-bs051.html @@ -0,0 +1,320 @@ + + + + + + + +
+ + + + +
+Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. + +
+Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. + +
+Tensorflow uses so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow graph +to represent your model, and then create a Tensorflow session to run the graph. + +
+In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. + +
+To install tensorflow on Unix/Linux systems, use pip as +
+ + +
pip3 install tensorflow
++and/or if you use anaconda, just write (or install from the graphical user interface) +
+ + +
conda install tensorflow
++
+ +
+ + +
+ + + + +
+ + +
# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# flatten the image
+# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
+n_inputs = len(inputs)
+inputs = inputs.reshape(n_inputs, -1)
+print("X = (n_inputs, n_features) = " + str(inputs.shape))
+
+
+# choose some random images to display
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+ plt.subplot(1, 5, i+1)
+ plt.axis('off')
+ plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+ plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
++ + +
from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# one-hot representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+ test_size=test_size)
++
+ +
+ + +
+ + + + +
+ + +
import tensorflow as tf
+
+class NeuralNetworkTensorflow:
+ def __init__(
+ self,
+ X_train,
+ Y_train,
+ X_test,
+ Y_test,
+ n_neurons_layer1=100,
+ n_neurons_layer2=50,
+ n_categories=2,
+ epochs=10,
+ batch_size=100,
+ eta=0.1,
+ lmbd=0.0,
+ ):
+
+ # keep track of number of steps
+ self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+
+ self.X_train = X_train
+ self.Y_train = Y_train
+ self.X_test = X_test
+ self.Y_test = Y_test
+
+ self.n_inputs = X_train.shape[0]
+ self.n_features = X_train.shape[1]
+ self.n_neurons_layer1 = n_neurons_layer1
+ self.n_neurons_layer2 = n_neurons_layer2
+ self.n_categories = n_categories
+
+ self.epochs = epochs
+ self.batch_size = batch_size
+ self.iterations = self.n_inputs // self.batch_size
+ self.eta = eta
+ self.lmbd = lmbd
+
+ # build network piece by piece
+ # name scopes (with) are used to enforce creation of new variables
+ # https://www.tensorflow.org/guide/variables
+ self.create_placeholders()
+ self.create_DNN()
+ self.create_loss()
+ self.create_optimiser()
+ self.create_accuracy()
+
+ def create_placeholders(self):
+ # placeholders are fine here, but "Datasets" are the preferred method
+ # of streaming data into a model
+ with tf.name_scope('data'):
+ self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')
+ self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+
+ def create_DNN(self):
+ with tf.name_scope('DNN'):
+ # the weights are stored to calculate regularization loss later
+
+ # Fully connected layer 1
+ self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)
+
+ # Fully connected layer 2
+ self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)
+
+ # Output layer
+ self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)
+ b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+ self.z_out = tf.matmul(a_fc2, self.W_out) + b_out
+
+ def create_loss(self):
+ with tf.name_scope('loss'):
+ softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+
+ regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)
+ regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)
+ regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+ regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)
+
+ self.loss = softmax_loss + regularizer_loss
+
+ def create_accuracy(self):
+ with tf.name_scope('accuracy'):
+ probabilities = tf.nn.softmax(self.z_out)
+ predictions = tf.argmax(probabilities, axis=1)
+ labels = tf.argmax(self.Y, axis=1)
+
+ correct_predictions = tf.equal(predictions, labels)
+ correct_predictions = tf.cast(correct_predictions, tf.float32)
+ self.accuracy = tf.reduce_mean(correct_predictions)
+
+ def create_optimiser(self):
+ with tf.name_scope('optimizer'):
+ self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+
+ def weight_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.truncated_normal(shape, stddev=0.1)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def bias_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.constant(0.1, shape=shape)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def fit(self):
+ data_indices = np.arange(self.n_inputs)
+
+ with tf.Session() as sess:
+ sess.run(tf.global_variables_initializer())
+ for i in range(self.epochs):
+ for j in range(self.iterations):
+ chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+ batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+
+ sess.run([DNN.loss, DNN.optimizer],
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ accuracy = sess.run(DNN.accuracy,
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ step = sess.run(DNN.global_step)
+
+ self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_train,
+ DNN.Y: self.Y_train})
+
+ self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_test,
+ DNN.Y: self.Y_test})
++
+ +
+ + +
+ + + + +
+ + +
epochs = 100
+batch_size = 100
+n_neurons_layer1 = 100
+n_neurons_layer2 = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
++ + +
DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+ n_neurons_layer1, n_neurons_layer2, n_categories,
+ epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)
+ DNN.fit()
+
+ DNN_tf[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % DNN.test_accuracy)
+ print()
+
++ + +
# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_tf[i][j]
+
+ train_accuracy[i][j] = DNN.train_accuracy
+ test_accuracy[i][j] = DNN.test_accuracy
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
++ + +
# optional
+# we can use log files to visualize our graph in Tensorboard
+writer = tf.summary.FileWriter('logs/')
+writer.add_graph(tf.get_default_graph())
++
+ +
+ + +
+ + + + +
+Keras is a high level neural network +that supports Tensorflow, CTNK and Theano as backends. +If you have Tensorflow installed Keras is available through the tf.keras module. +If you have Anaconda installed you may run the following command +
+ + +
conda install keras
++Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager: + +
+ + +
pip3 install keras
++or look up the instructions here. + +
+ + +
from keras.models import Sequential
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
+ model = Sequential()
+ model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_categories, activation='softmax'))
+
+ sgd = SGD(lr=eta)
+ model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+
+ return model
++ + +
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
+ eta=eta, lmbd=lmbd)
+ DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+ scores = DNN.evaluate(X_test, Y_test)
+
+ DNN_keras[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % scores[1])
+ print()
++ + +
# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_keras[i][j]
+
+ train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
+ test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
++ +
+ +
+ + ++Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. + +
+In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. +
+Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. + +
+Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. + +
+Tensorflow uses so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow graph +to represent your model, and then create a Tensorflow session to run the graph. + +
+In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. + +
+To install tensorflow on Unix/Linux systems, use pip as +
+ + +
pip3 install tensorflow
++and/or if you use anaconda, just write (or install from the graphical user interface) +
+ + +
conda install tensorflow
++ + +
# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# flatten the image
+# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
+n_inputs = len(inputs)
+inputs = inputs.reshape(n_inputs, -1)
+print("X = (n_inputs, n_features) = " + str(inputs.shape))
+
+
+# choose some random images to display
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+ plt.subplot(1, 5, i+1)
+ plt.axis('off')
+ plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+ plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
++ + +
from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# one-hot representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+ test_size=test_size)
++ + +
import tensorflow as tf
+
+class NeuralNetworkTensorflow:
+ def __init__(
+ self,
+ X_train,
+ Y_train,
+ X_test,
+ Y_test,
+ n_neurons_layer1=100,
+ n_neurons_layer2=50,
+ n_categories=2,
+ epochs=10,
+ batch_size=100,
+ eta=0.1,
+ lmbd=0.0,
+ ):
+
+ # keep track of number of steps
+ self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+
+ self.X_train = X_train
+ self.Y_train = Y_train
+ self.X_test = X_test
+ self.Y_test = Y_test
+
+ self.n_inputs = X_train.shape[0]
+ self.n_features = X_train.shape[1]
+ self.n_neurons_layer1 = n_neurons_layer1
+ self.n_neurons_layer2 = n_neurons_layer2
+ self.n_categories = n_categories
+
+ self.epochs = epochs
+ self.batch_size = batch_size
+ self.iterations = self.n_inputs // self.batch_size
+ self.eta = eta
+ self.lmbd = lmbd
+
+ # build network piece by piece
+ # name scopes (with) are used to enforce creation of new variables
+ # https://www.tensorflow.org/guide/variables
+ self.create_placeholders()
+ self.create_DNN()
+ self.create_loss()
+ self.create_optimiser()
+ self.create_accuracy()
+
+ def create_placeholders(self):
+ # placeholders are fine here, but "Datasets" are the preferred method
+ # of streaming data into a model
+ with tf.name_scope('data'):
+ self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')
+ self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+
+ def create_DNN(self):
+ with tf.name_scope('DNN'):
+ # the weights are stored to calculate regularization loss later
+
+ # Fully connected layer 1
+ self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)
+
+ # Fully connected layer 2
+ self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)
+
+ # Output layer
+ self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)
+ b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+ self.z_out = tf.matmul(a_fc2, self.W_out) + b_out
+
+ def create_loss(self):
+ with tf.name_scope('loss'):
+ softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+
+ regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)
+ regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)
+ regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+ regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)
+
+ self.loss = softmax_loss + regularizer_loss
+
+ def create_accuracy(self):
+ with tf.name_scope('accuracy'):
+ probabilities = tf.nn.softmax(self.z_out)
+ predictions = tf.argmax(probabilities, axis=1)
+ labels = tf.argmax(self.Y, axis=1)
+
+ correct_predictions = tf.equal(predictions, labels)
+ correct_predictions = tf.cast(correct_predictions, tf.float32)
+ self.accuracy = tf.reduce_mean(correct_predictions)
+
+ def create_optimiser(self):
+ with tf.name_scope('optimizer'):
+ self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+
+ def weight_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.truncated_normal(shape, stddev=0.1)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def bias_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.constant(0.1, shape=shape)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def fit(self):
+ data_indices = np.arange(self.n_inputs)
+
+ with tf.Session() as sess:
+ sess.run(tf.global_variables_initializer())
+ for i in range(self.epochs):
+ for j in range(self.iterations):
+ chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+ batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+
+ sess.run([DNN.loss, DNN.optimizer],
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ accuracy = sess.run(DNN.accuracy,
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ step = sess.run(DNN.global_step)
+
+ self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_train,
+ DNN.Y: self.Y_train})
+
+ self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_test,
+ DNN.Y: self.Y_test})
++ + +
epochs = 100
+batch_size = 100
+n_neurons_layer1 = 100
+n_neurons_layer2 = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
++ + +
DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+ n_neurons_layer1, n_neurons_layer2, n_categories,
+ epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)
+ DNN.fit()
+
+ DNN_tf[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % DNN.test_accuracy)
+ print()
+
++ + +
# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_tf[i][j]
+
+ train_accuracy[i][j] = DNN.train_accuracy
+ test_accuracy[i][j] = DNN.test_accuracy
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
++ + +
# optional
+# we can use log files to visualize our graph in Tensorboard
+writer = tf.summary.FileWriter('logs/')
+writer.add_graph(tf.get_default_graph())
++Keras is a high level neural network +that supports Tensorflow, CTNK and Theano as backends. +If you have Tensorflow installed Keras is available through the tf.keras module. +If you have Anaconda installed you may run the following command +
+ + +
conda install keras
++Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager: + +
+ + +
pip3 install keras
++or look up the instructions here. + +
+ + +
from keras.models import Sequential
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
+ model = Sequential()
+ model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_categories, activation='softmax'))
+
+ sgd = SGD(lr=eta)
+ model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+
+ return model
++ + +
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
+ eta=eta, lmbd=lmbd)
+ DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+ scores = DNN.evaluate(X_test, Y_test)
+
+ DNN_keras[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % scores[1])
+ print()
++ + +
# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_keras[i][j]
+
+ train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
+ test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
-
+Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. + +
+In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. + +
+
+
+
+Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. + +
+Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. + +
+Tensorflow uses so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow graph +to represent your model, and then create a Tensorflow session to run the graph. + +
+In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. + +
+To install tensorflow on Unix/Linux systems, use pip as +
+ + +
pip3 install tensorflow
++and/or if you use anaconda, just write (or install from the graphical user interface) +
+ + +
conda install tensorflow
+
+
+
+
+ + +
# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# flatten the image
+# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
+n_inputs = len(inputs)
+inputs = inputs.reshape(n_inputs, -1)
+print("X = (n_inputs, n_features) = " + str(inputs.shape))
+
+
+# choose some random images to display
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+ plt.subplot(1, 5, i+1)
+ plt.axis('off')
+ plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+ plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
++ + +
from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# one-hot representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+ test_size=test_size)
+
+
+
+
+ + +
import tensorflow as tf
+
+class NeuralNetworkTensorflow:
+ def __init__(
+ self,
+ X_train,
+ Y_train,
+ X_test,
+ Y_test,
+ n_neurons_layer1=100,
+ n_neurons_layer2=50,
+ n_categories=2,
+ epochs=10,
+ batch_size=100,
+ eta=0.1,
+ lmbd=0.0,
+ ):
+
+ # keep track of number of steps
+ self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+
+ self.X_train = X_train
+ self.Y_train = Y_train
+ self.X_test = X_test
+ self.Y_test = Y_test
+
+ self.n_inputs = X_train.shape[0]
+ self.n_features = X_train.shape[1]
+ self.n_neurons_layer1 = n_neurons_layer1
+ self.n_neurons_layer2 = n_neurons_layer2
+ self.n_categories = n_categories
+
+ self.epochs = epochs
+ self.batch_size = batch_size
+ self.iterations = self.n_inputs // self.batch_size
+ self.eta = eta
+ self.lmbd = lmbd
+
+ # build network piece by piece
+ # name scopes (with) are used to enforce creation of new variables
+ # https://www.tensorflow.org/guide/variables
+ self.create_placeholders()
+ self.create_DNN()
+ self.create_loss()
+ self.create_optimiser()
+ self.create_accuracy()
+
+ def create_placeholders(self):
+ # placeholders are fine here, but "Datasets" are the preferred method
+ # of streaming data into a model
+ with tf.name_scope('data'):
+ self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')
+ self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+
+ def create_DNN(self):
+ with tf.name_scope('DNN'):
+ # the weights are stored to calculate regularization loss later
+
+ # Fully connected layer 1
+ self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)
+
+ # Fully connected layer 2
+ self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)
+
+ # Output layer
+ self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)
+ b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+ self.z_out = tf.matmul(a_fc2, self.W_out) + b_out
+
+ def create_loss(self):
+ with tf.name_scope('loss'):
+ softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+
+ regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)
+ regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)
+ regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+ regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)
+
+ self.loss = softmax_loss + regularizer_loss
+
+ def create_accuracy(self):
+ with tf.name_scope('accuracy'):
+ probabilities = tf.nn.softmax(self.z_out)
+ predictions = tf.argmax(probabilities, axis=1)
+ labels = tf.argmax(self.Y, axis=1)
+
+ correct_predictions = tf.equal(predictions, labels)
+ correct_predictions = tf.cast(correct_predictions, tf.float32)
+ self.accuracy = tf.reduce_mean(correct_predictions)
+
+ def create_optimiser(self):
+ with tf.name_scope('optimizer'):
+ self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+
+ def weight_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.truncated_normal(shape, stddev=0.1)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def bias_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.constant(0.1, shape=shape)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def fit(self):
+ data_indices = np.arange(self.n_inputs)
+
+ with tf.Session() as sess:
+ sess.run(tf.global_variables_initializer())
+ for i in range(self.epochs):
+ for j in range(self.iterations):
+ chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+ batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+
+ sess.run([DNN.loss, DNN.optimizer],
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ accuracy = sess.run(DNN.accuracy,
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ step = sess.run(DNN.global_step)
+
+ self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_train,
+ DNN.Y: self.Y_train})
+
+ self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_test,
+ DNN.Y: self.Y_test})
+
+
+
+
+ + +
epochs = 100
+batch_size = 100
+n_neurons_layer1 = 100
+n_neurons_layer2 = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
++ + +
DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+ n_neurons_layer1, n_neurons_layer2, n_categories,
+ epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)
+ DNN.fit()
+
+ DNN_tf[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % DNN.test_accuracy)
+ print()
+
++ + +
# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_tf[i][j]
+
+ train_accuracy[i][j] = DNN.train_accuracy
+ test_accuracy[i][j] = DNN.test_accuracy
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
++ + +
# optional
+# we can use log files to visualize our graph in Tensorboard
+writer = tf.summary.FileWriter('logs/')
+writer.add_graph(tf.get_default_graph())
+
+
+
+
+Keras is a high level neural network +that supports Tensorflow, CTNK and Theano as backends. +If you have Tensorflow installed Keras is available through the tf.keras module. +If you have Anaconda installed you may run the following command +
+ + +
conda install keras
++Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager: + +
+ + +
pip3 install keras
++or look up the instructions here. + +
+ + +
from keras.models import Sequential
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
+ model = Sequential()
+ model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_categories, activation='softmax'))
+
+ sgd = SGD(lr=eta)
+ model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+
+ return model
++ + +
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
+ eta=eta, lmbd=lmbd)
+ DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+ scores = DNN.evaluate(X_test, Y_test)
+
+ DNN_keras[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % scores[1])
+ print()
++ + +
# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_keras[i][j]
+
+ train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
+ test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+diff --git a/doc/pub/NeuralNet/html/NeuralNet.html b/doc/pub/NeuralNet/html/NeuralNet.html index 6356f4f14..cfb13c6ce 100644 --- a/doc/pub/NeuralNet/html/NeuralNet.html +++ b/doc/pub/NeuralNet/html/NeuralNet.html @@ -140,7 +140,15 @@ div { text-align: justify; text-justify: inter-word; } None, '___sec47'), ('scikit-learn implementation', 2, None, '___sec48'), - ('And then with Tensorflow', 2, None, '___sec49')]} + ('Building neural networks in Tensorflow and Keras', + 2, + None, + '___sec49'), + ('Tensorflow', 2, None, '___sec50'), + ('Collect and pre-process data', 2, None, '___sec51'), + ('Using TensorFlow backend', 2, None, '___sec52'), + ('Optimizing and using gradient descent', 2, None, '___sec53'), + ('Using Keras', 2, None, '___sec54')]} end of tocinfo -->
@@ -2180,8 +2188,453 @@ plt.show()
-
+Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn +and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy +and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. + +
+In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite +clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or +NumPy arrays. + +
+
+
+
+Tensorflow is an open source library machine learning library +developed by the Google Brain team for internal use. It was released +under the Apache 2.0 open source license in November 9, 2015. + +
+Tensorflow is a computational framework that allows you to construct +machine learning models at different levels of abstraction, from +high-level, object-oriented APIs like Keras, down to the C++ kernels +that Tensorflow is built upon. The higher levels of abstraction are +simpler to use, but less flexible, and our choice of implementation +should reflect the problems we are trying to solve. + +
+Tensorflow uses so-called graphs to represent your computation +in terms of the dependencies between individual operations, such that you first build a Tensorflow graph +to represent your model, and then create a Tensorflow session to run the graph. + +
+In this guide we will analyze the same data as we did in our NumPy and +scikit-learn tutorial, gathered from the MNIST database of images. We +will give an introduction to the lower level Python Application +Program Interfaces (APIs), and see how we use them to build our graph. +Then we will build (effectively) the same graph in Keras, to see just +how simple solving a machine learning problem can be. + +
+To install tensorflow on Unix/Linux systems, use pip as +
+ + +
pip3 install tensorflow
++and/or if you use anaconda, just write (or install from the graphical user interface) +
+ + +
conda install tensorflow
+
+
+
+
+ + +
# import necessary packages
+import numpy as np
+import matplotlib.pyplot as plt
+from sklearn import datasets
+
+
+# ensure the same random numbers appear every time
+np.random.seed(0)
+
+# display images in notebook
+%matplotlib inline
+plt.rcParams['figure.figsize'] = (12,12)
+
+
+# download MNIST dataset
+digits = datasets.load_digits()
+
+# define inputs and labels
+inputs = digits.images
+labels = digits.target
+
+print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape))
+print("labels = (n_inputs) = " + str(labels.shape))
+
+
+# flatten the image
+# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64
+n_inputs = len(inputs)
+inputs = inputs.reshape(n_inputs, -1)
+print("X = (n_inputs, n_features) = " + str(inputs.shape))
+
+
+# choose some random images to display
+indices = np.arange(n_inputs)
+random_indices = np.random.choice(indices, size=5)
+
+for i, image in enumerate(digits.images[random_indices]):
+ plt.subplot(1, 5, i+1)
+ plt.axis('off')
+ plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
+ plt.title("Label: %d" % digits.target[random_indices[i]])
+plt.show()
++ + +
from keras.utils import to_categorical
+from sklearn.model_selection import train_test_split
+
+# one-hot representation of labels
+labels = to_categorical(labels)
+
+# split into train and test data
+train_size = 0.8
+test_size = 1 - train_size
+X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
+ test_size=test_size)
+
+
+
+
+ + +
import tensorflow as tf
+
+class NeuralNetworkTensorflow:
+ def __init__(
+ self,
+ X_train,
+ Y_train,
+ X_test,
+ Y_test,
+ n_neurons_layer1=100,
+ n_neurons_layer2=50,
+ n_categories=2,
+ epochs=10,
+ batch_size=100,
+ eta=0.1,
+ lmbd=0.0,
+ ):
+
+ # keep track of number of steps
+ self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
+
+ self.X_train = X_train
+ self.Y_train = Y_train
+ self.X_test = X_test
+ self.Y_test = Y_test
+
+ self.n_inputs = X_train.shape[0]
+ self.n_features = X_train.shape[1]
+ self.n_neurons_layer1 = n_neurons_layer1
+ self.n_neurons_layer2 = n_neurons_layer2
+ self.n_categories = n_categories
+
+ self.epochs = epochs
+ self.batch_size = batch_size
+ self.iterations = self.n_inputs // self.batch_size
+ self.eta = eta
+ self.lmbd = lmbd
+
+ # build network piece by piece
+ # name scopes (with) are used to enforce creation of new variables
+ # https://www.tensorflow.org/guide/variables
+ self.create_placeholders()
+ self.create_DNN()
+ self.create_loss()
+ self.create_optimiser()
+ self.create_accuracy()
+
+ def create_placeholders(self):
+ # placeholders are fine here, but "Datasets" are the preferred method
+ # of streaming data into a model
+ with tf.name_scope('data'):
+ self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')
+ self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
+
+ def create_DNN(self):
+ with tf.name_scope('DNN'):
+ # the weights are stored to calculate regularization loss later
+
+ # Fully connected layer 1
+ self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)
+ a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)
+
+ # Fully connected layer 2
+ self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)
+ a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)
+
+ # Output layer
+ self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)
+ b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
+ self.z_out = tf.matmul(a_fc2, self.W_out) + b_out
+
+ def create_loss(self):
+ with tf.name_scope('loss'):
+ softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
+
+ regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)
+ regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)
+ regularizer_loss_out = tf.nn.l2_loss(self.W_out)
+ regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)
+
+ self.loss = softmax_loss + regularizer_loss
+
+ def create_accuracy(self):
+ with tf.name_scope('accuracy'):
+ probabilities = tf.nn.softmax(self.z_out)
+ predictions = tf.argmax(probabilities, axis=1)
+ labels = tf.argmax(self.Y, axis=1)
+
+ correct_predictions = tf.equal(predictions, labels)
+ correct_predictions = tf.cast(correct_predictions, tf.float32)
+ self.accuracy = tf.reduce_mean(correct_predictions)
+
+ def create_optimiser(self):
+ with tf.name_scope('optimizer'):
+ self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
+
+ def weight_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.truncated_normal(shape, stddev=0.1)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def bias_variable(self, shape, name='', dtype=tf.float32):
+ initial = tf.constant(0.1, shape=shape)
+ return tf.Variable(initial, name=name, dtype=dtype)
+
+ def fit(self):
+ data_indices = np.arange(self.n_inputs)
+
+ with tf.Session() as sess:
+ sess.run(tf.global_variables_initializer())
+ for i in range(self.epochs):
+ for j in range(self.iterations):
+ chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
+ batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
+
+ sess.run([DNN.loss, DNN.optimizer],
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ accuracy = sess.run(DNN.accuracy,
+ feed_dict={DNN.X: batch_X,
+ DNN.Y: batch_Y})
+ step = sess.run(DNN.global_step)
+
+ self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_train,
+ DNN.Y: self.Y_train})
+
+ self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],
+ feed_dict={DNN.X: self.X_test,
+ DNN.Y: self.Y_test})
+
+
+
+
+ + +
epochs = 100
+batch_size = 100
+n_neurons_layer1 = 100
+n_neurons_layer2 = 50
+n_categories = 10
+
+eta_vals = np.logspace(-5, 1, 7)
+lmbd_vals = np.logspace(-5, 1, 7)
++ + +
DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
+ n_neurons_layer1, n_neurons_layer2, n_categories,
+ epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)
+ DNN.fit()
+
+ DNN_tf[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % DNN.test_accuracy)
+ print()
+
++ + +
# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_tf[i][j]
+
+ train_accuracy[i][j] = DNN.train_accuracy
+ test_accuracy[i][j] = DNN.test_accuracy
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
++ + +
# optional
+# we can use log files to visualize our graph in Tensorboard
+writer = tf.summary.FileWriter('logs/')
+writer.add_graph(tf.get_default_graph())
+
+
+
+
+Keras is a high level neural network +that supports Tensorflow, CTNK and Theano as backends. +If you have Tensorflow installed Keras is available through the tf.keras module. +If you have Anaconda installed you may run the following command +
+ + +
conda install keras
++Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager: + +
+ + +
pip3 install keras
++or look up the instructions here. + +
+ + +
from keras.models import Sequential
+from keras.layers import Dense
+from keras.regularizers import l2
+from keras.optimizers import SGD
+
+def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
+ model = Sequential()
+ model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))
+ model.add(Dense(n_categories, activation='softmax'))
+
+ sgd = SGD(lr=eta)
+ model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
+
+ return model
++ + +
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
+for i, eta in enumerate(eta_vals):
+ for j, lmbd in enumerate(lmbd_vals):
+ DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,
+ eta=eta, lmbd=lmbd)
+ DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
+ scores = DNN.evaluate(X_test, Y_test)
+
+ DNN_keras[i][j] = DNN
+
+ print("Learning rate = ", eta)
+ print("Lambda = ", lmbd)
+ print("Test accuracy: %.3f" % scores[1])
+ print()
++ + +
# optional
+# visual representation of grid search
+# uses seaborn heatmap, could probably do this in matplotlib
+import seaborn as sns
+
+sns.set()
+
+train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
+
+for i in range(len(eta_vals)):
+ for j in range(len(lmbd_vals)):
+ DNN = DNN_keras[i][j]
+
+ train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]
+ test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]
+
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Training Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+
+fig, ax = plt.subplots(figsize = (10, 10))
+sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
+ax.set_title("Test Accuracy")
+ax.set_ylabel("$\eta$")
+ax.set_xlabel("$\lambda$")
+plt.show()
+diff --git a/doc/pub/NeuralNet/ipynb/NeuralNet.ipynb b/doc/pub/NeuralNet/ipynb/NeuralNet.ipynb index c56f955ed..fd6d5ee07 100644 --- a/doc/pub/NeuralNet/ipynb/NeuralNet.ipynb +++ b/doc/pub/NeuralNet/ipynb/NeuralNet.ipynb @@ -2447,7 +2447,546 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## And then with Tensorflow" + "## Building neural networks in Tensorflow and Keras\n", + "\n", + "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", + "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", + "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", + "\n", + "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", + "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", + "NumPy arrays.\n", + "\n", + "## Tensorflow\n", + "\n", + "Tensorflow is an open source library machine learning library\n", + "developed by the Google Brain team for internal use. It was released\n", + "under the Apache 2.0 open source license in November 9, 2015.\n", + "\n", + "Tensorflow is a computational framework that allows you to construct\n", + "machine learning models at different levels of abstraction, from\n", + "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", + "that Tensorflow is built upon. The higher levels of abstraction are\n", + "simpler to use, but less flexible, and our choice of implementation\n", + "should reflect the problems we are trying to solve.\n", + "\n", + "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", + "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", + "to represent your model, and then create a Tensorflow *session* to run the graph.\n", + "\n", + "In this guide we will analyze the same data as we did in our NumPy and\n", + "scikit-learn tutorial, gathered from the MNIST database of images. We\n", + "will give an introduction to the lower level Python Application\n", + "Program Interfaces (APIs), and see how we use them to build our graph.\n", + "Then we will build (effectively) the same graph in Keras, to see just\n", + "how simple solving a machine learning problem can be.\n", + "\n", + "To install tensorflow on Unix/Linux systems, use pip as" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pip3 install tensorflow" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and/or if you use **anaconda**, just write (or install from the graphical user interface)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "conda install tensorflow" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Collect and pre-process data" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# flatten the image\n", + "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", + "n_inputs = len(inputs)\n", + "inputs = inputs.reshape(n_inputs, -1)\n", + "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from keras.utils import to_categorical\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# one-hot representation of labels\n", + "labels = to_categorical(labels)\n", + "\n", + "# split into train and test data\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using TensorFlow backend\n", + "\n", + "1. Define model and architecture\n", + "\n", + "2. Choose cost function and optimizer" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import tensorflow as tf\n", + "\n", + "class NeuralNetworkTensorflow:\n", + " def __init__(\n", + " self,\n", + " X_train,\n", + " Y_train,\n", + " X_test,\n", + " Y_test,\n", + " n_neurons_layer1=100,\n", + " n_neurons_layer2=50,\n", + " n_categories=2,\n", + " epochs=10,\n", + " batch_size=100,\n", + " eta=0.1,\n", + " lmbd=0.0,\n", + " ):\n", + " \n", + " # keep track of number of steps\n", + " self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')\n", + " \n", + " self.X_train = X_train\n", + " self.Y_train = Y_train\n", + " self.X_test = X_test\n", + " self.Y_test = Y_test\n", + " \n", + " self.n_inputs = X_train.shape[0]\n", + " self.n_features = X_train.shape[1]\n", + " self.n_neurons_layer1 = n_neurons_layer1\n", + " self.n_neurons_layer2 = n_neurons_layer2\n", + " self.n_categories = n_categories\n", + " \n", + " self.epochs = epochs\n", + " self.batch_size = batch_size\n", + " self.iterations = self.n_inputs // self.batch_size\n", + " self.eta = eta\n", + " self.lmbd = lmbd\n", + " \n", + " # build network piece by piece\n", + " # name scopes (with) are used to enforce creation of new variables\n", + " # https://www.tensorflow.org/guide/variables\n", + " self.create_placeholders()\n", + " self.create_DNN()\n", + " self.create_loss()\n", + " self.create_optimiser()\n", + " self.create_accuracy()\n", + " \n", + " def create_placeholders(self):\n", + " # placeholders are fine here, but \"Datasets\" are the preferred method\n", + " # of streaming data into a model\n", + " with tf.name_scope('data'):\n", + " self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')\n", + " self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')\n", + " \n", + " def create_DNN(self):\n", + " with tf.name_scope('DNN'):\n", + " # the weights are stored to calculate regularization loss later\n", + " \n", + " # Fully connected layer 1\n", + " self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)\n", + " b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)\n", + " a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)\n", + " \n", + " # Fully connected layer 2\n", + " self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)\n", + " b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)\n", + " a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)\n", + " \n", + " # Output layer\n", + " self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)\n", + " b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)\n", + " self.z_out = tf.matmul(a_fc2, self.W_out) + b_out\n", + " \n", + " def create_loss(self):\n", + " with tf.name_scope('loss'):\n", + " softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))\n", + " \n", + " regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)\n", + " regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)\n", + " regularizer_loss_out = tf.nn.l2_loss(self.W_out)\n", + " regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)\n", + " \n", + " self.loss = softmax_loss + regularizer_loss\n", + "\n", + " def create_accuracy(self):\n", + " with tf.name_scope('accuracy'):\n", + " probabilities = tf.nn.softmax(self.z_out)\n", + " predictions = tf.argmax(probabilities, axis=1)\n", + " labels = tf.argmax(self.Y, axis=1)\n", + " \n", + " correct_predictions = tf.equal(predictions, labels)\n", + " correct_predictions = tf.cast(correct_predictions, tf.float32)\n", + " self.accuracy = tf.reduce_mean(correct_predictions)\n", + " \n", + " def create_optimiser(self):\n", + " with tf.name_scope('optimizer'):\n", + " self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)\n", + " \n", + " def weight_variable(self, shape, name='', dtype=tf.float32):\n", + " initial = tf.truncated_normal(shape, stddev=0.1)\n", + " return tf.Variable(initial, name=name, dtype=dtype)\n", + " \n", + " def bias_variable(self, shape, name='', dtype=tf.float32):\n", + " initial = tf.constant(0.1, shape=shape)\n", + " return tf.Variable(initial, name=name, dtype=dtype)\n", + " \n", + " def fit(self):\n", + " data_indices = np.arange(self.n_inputs)\n", + "\n", + " with tf.Session() as sess:\n", + " sess.run(tf.global_variables_initializer())\n", + " for i in range(self.epochs):\n", + " for j in range(self.iterations):\n", + " chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)\n", + " batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]\n", + " \n", + " sess.run([DNN.loss, DNN.optimizer],\n", + " feed_dict={DNN.X: batch_X,\n", + " DNN.Y: batch_Y})\n", + " accuracy = sess.run(DNN.accuracy,\n", + " feed_dict={DNN.X: batch_X,\n", + " DNN.Y: batch_Y})\n", + " step = sess.run(DNN.global_step)\n", + " \n", + " self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],\n", + " feed_dict={DNN.X: self.X_train,\n", + " DNN.Y: self.Y_train})\n", + " \n", + " self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],\n", + " feed_dict={DNN.X: self.X_test,\n", + " DNN.Y: self.Y_test})" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Optimizing and using gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "epochs = 100\n", + "batch_size = 100\n", + "n_neurons_layer1 = 100\n", + "n_neurons_layer2 = 50\n", + "n_categories = 10\n", + "\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,\n", + " n_neurons_layer1, n_neurons_layer2, n_categories,\n", + " epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)\n", + " DNN.fit()\n", + " \n", + " DNN_tf[i][j] = DNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % DNN.test_accuracy)\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " DNN = DNN_tf[i][j]\n", + "\n", + " train_accuracy[i][j] = DNN.train_accuracy\n", + " test_accuracy[i][j] = DNN.test_accuracy\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# optional\n", + "# we can use log files to visualize our graph in Tensorboard\n", + "writer = tf.summary.FileWriter('logs/')\n", + "writer.add_graph(tf.get_default_graph())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Keras\n", + "\n", + "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", + "that supports Tensorflow, CTNK and Theano as backends. \n", + "If you have Tensorflow installed Keras is available through the *tf.keras* module. \n", + "If you have Anaconda installed you may run the following command" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "conda install keras" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager:" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "pip3 install keras" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or look up the [instructions here](https://keras.io/)." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from keras.models import Sequential\n", + "from keras.layers import Dense\n", + "from keras.regularizers import l2\n", + "from keras.optimizers import SGD\n", + "\n", + "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", + " model = Sequential()\n", + " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n", + " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n", + " model.add(Dense(n_categories, activation='softmax'))\n", + " \n", + " sgd = SGD(lr=eta)\n", + " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", + " \n", + " return model" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", + " eta=eta, lmbd=lmbd)\n", + " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", + " scores = DNN.evaluate(X_test, Y_test)\n", + " \n", + " DNN_keras[i][j] = DNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % scores[1])\n", + " print()" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# optional\n", + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " DNN = DNN_keras[i][j]\n", + "\n", + " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", + " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" ] } ], diff --git a/doc/pub/NeuralNet/ipynb/ipynb-NeuralNet-src.tar.gz b/doc/pub/NeuralNet/ipynb/ipynb-NeuralNet-src.tar.gz index 890c1fbf4..df4a2068c 100644 Binary files a/doc/pub/NeuralNet/ipynb/ipynb-NeuralNet-src.tar.gz and b/doc/pub/NeuralNet/ipynb/ipynb-NeuralNet-src.tar.gz differ diff --git a/doc/pub/NeuralNet/pdf/NeuralNet-minted.pdf b/doc/pub/NeuralNet/pdf/NeuralNet-minted.pdf index 730df384e..1f58cbc2a 100644 Binary files a/doc/pub/NeuralNet/pdf/NeuralNet-minted.pdf and b/doc/pub/NeuralNet/pdf/NeuralNet-minted.pdf differ diff --git a/doc/src/NeuralNet/NeuralNet.do.txt b/doc/src/NeuralNet/NeuralNet.do.txt index 11476bf3a..03bb895d7 100644 --- a/doc/src/NeuralNet/NeuralNet.do.txt +++ b/doc/src/NeuralNet/NeuralNet.do.txt @@ -1824,7 +1824,7 @@ conda install tensorflow !split ===== Collect and pre-process data ===== -bc pycod +!bc pycod # import necessary packages import numpy as np import matplotlib.pyplot as plt