100 KiB
100 KiB
In [1]:
%matplotlib inline
import numpy as np
import math
from scipy import signal
import matplotlib.pyplot as plt
# number of points
n = 500
# start and final times
t0 = 0.0
tn = 1.0
# Period
t = np.linspace(t0, tn, n, endpoint=False)
SqrSignal = np.zeros(n)
SqrSignal = 1.0+signal.square(2*np.pi*5*t)
plt.plot(t, SqrSignal)
plt.ylim(-0.5, 2.5)
plt.show()In [2]:
import numpy as np
import math
from scipy import signal
import matplotlib.pyplot as plt
# number of points
n = 500
# start and final times
t0 = 0.0
tn = 1.0
# Period
T =0.2
# Max value of square signal
Fmax= 2.0
# Width of signal
Width = 0.1
t = np.linspace(t0, tn, n, endpoint=False)
SqrSignal = np.zeros(n)
FourierSeriesSignal = np.zeros(n)
SqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T)
a0 = Fmax*Width/T
FourierSeriesSignal = a0
Factor = 2.0*Fmax/np.pi
for i in range(1,500):
FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T)
plt.plot(t, SqrSignal)
plt.plot(t, FourierSeriesSignal)
plt.ylim(-0.5, 2.5)
plt.show()In [3]:
# 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
# RGB images have a depth of 3
# our images are grayscale so they should have a depth of 1
inputs = inputs[:,:,:,np.newaxis]
print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
print("labels = (n_inputs) = " + str(labels.shape))
# choose some random images to display
n_inputs = len(inputs)
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()inputs = (n_inputs, pixel_width, pixel_height, depth) = (1797, 8, 8, 1) labels = (n_inputs) = (1797,)
In [4]:
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Sequential #This allows appending layers to existing models
from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer
from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)
from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)
from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function
#from tensorflow.keras import Conv2D
#from tensorflow.keras import MaxPooling2D
#from tensorflow.keras import Flatten
from sklearn.model_selection import train_test_split
# representation of labels
labels = to_categorical(labels)
# split into train and test data
# one-liner from scikit-learn library
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)In [5]:
def create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd):
model = Sequential()
model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
sgd = optimizers.SGD(lr=eta)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
return model
epochs = 100
batch_size = 100
input_shape = X_train.shape[1:4]
receptive_field = 3
n_filters = 10
n_neurons_connected = 50
n_categories = 10
eta_vals = np.logspace(-5, 1, 7)
lmbd_vals = np.logspace(-5, 1, 7)In [6]:
CNN_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):
CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd)
CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
scores = CNN.evaluate(X_test, Y_test)
CNN_keras[i][j] = CNN
print("Learning rate = ", eta)
print("Lambda = ", lmbd)
print("Test accuracy: %.3f" % scores[1])
print()2021-12-08 06:58:03.630224: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: SSE4.1 SSE4.2 AVX AVX2 FMA To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. /Users/MortenImac/anaconda3/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py:355: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead. warnings.warn(
2021-12-08 06:58:04.114437: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2)
1/12 [=>............................] - ETA: 1s - loss: 2.4411 - accuracy: 0.2500
12/12 [==============================] - 0s 853us/step - loss: 2.4410 - accuracy: 0.1944
Learning rate = 1e-05 Lambda = 1e-05 Test accuracy: 0.194
1/12 [=>............................] - ETA: 0s - loss: 4.2597 - accuracy: 0.0938
12/12 [==============================] - 0s 842us/step - loss: 3.4744 - accuracy: 0.1361
Learning rate = 1e-05 Lambda = 0.0001 Test accuracy: 0.136
1/12 [=>............................] - ETA: 1s - loss: 3.0466 - accuracy: 0.1562
12/12 [==============================] - 0s 743us/step - loss: 2.9400 - accuracy: 0.1028
Learning rate = 1e-05 Lambda = 0.001 Test accuracy: 0.103
1/12 [=>............................] - ETA: 1s - loss: 3.8064 - accuracy: 0.1250
12/12 [==============================] - 0s 912us/step - loss: 3.8175 - accuracy: 0.1056
Learning rate = 1e-05 Lambda = 0.01 Test accuracy: 0.106
1/12 [=>............................] - ETA: 1s - loss: 12.1612 - accuracy: 0.0938
12/12 [==============================] - 0s 763us/step - loss: 12.3063 - accuracy: 0.1361
Learning rate = 1e-05 Lambda = 0.1 Test accuracy: 0.136
1/12 [=>............................] - ETA: 0s - loss: 91.8768 - accuracy: 0.2812
12/12 [==============================] - 0s 922us/step - loss: 92.0923 - accuracy: 0.2972
Learning rate = 1e-05 Lambda = 1.0 Test accuracy: 0.297
1/12 [=>............................] - ETA: 0s - loss: 529.5700 - accuracy: 0.2188
12/12 [==============================] - 0s 935us/step - loss: 529.7050 - accuracy: 0.1861
Learning rate = 1e-05 Lambda = 10.0 Test accuracy: 0.186
1/12 [=>............................] - ETA: 1s - loss: 1.2495 - accuracy: 0.5312
12/12 [==============================] - 0s 750us/step - loss: 1.5138 - accuracy: 0.4694
Learning rate = 0.0001 Lambda = 1e-05 Test accuracy: 0.469
1/12 [=>............................] - ETA: 0s - loss: 1.4077 - accuracy: 0.6562
12/12 [==============================] - 0s 954us/step - loss: 1.4837 - accuracy: 0.5611
Learning rate = 0.0001 Lambda = 0.0001 Test accuracy: 0.561
1/12 [=>............................] - ETA: 0s - loss: 1.5539 - accuracy: 0.5625
12/12 [==============================] - 0s 932us/step - loss: 1.5615 - accuracy: 0.5639
Learning rate = 0.0001 Lambda = 0.001 Test accuracy: 0.564
[0;31m---------------------------------------------------------------------------[0m [0;31mKeyboardInterrupt[0m Traceback (most recent call last) [0;32m/var/folders/jy/g42mrgv128v34gnnhxwk9nrc0000gp/T/ipykernel_47647/2018906331.py[0m in [0;36m<module>[0;34m[0m [1;32m 6[0m [0mn_filters[0m[0;34m,[0m [0mn_neurons_connected[0m[0;34m,[0m [0mn_categories[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m [1;32m 7[0m eta, lmbd) [0;32m----> 8[0;31m [0mCNN[0m[0;34m.[0m[0mfit[0m[0;34m([0m[0mX_train[0m[0;34m,[0m [0mY_train[0m[0;34m,[0m [0mepochs[0m[0;34m=[0m[0mepochs[0m[0;34m,[0m [0mbatch_size[0m[0;34m=[0m[0mbatch_size[0m[0;34m,[0m [0mverbose[0m[0;34m=[0m[0;36m0[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 9[0m [0mscores[0m [0;34m=[0m [0mCNN[0m[0;34m.[0m[0mevaluate[0m[0;34m([0m[0mX_test[0m[0;34m,[0m [0mY_test[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [1;32m 10[0m [0;34m[0m[0m [0;32m~/anaconda3/lib/python3.8/site-packages/keras/engine/training.py[0m in [0;36mfit[0;34m(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)[0m [1;32m 1182[0m _r=1): [1;32m 1183[0m [0mcallbacks[0m[0;34m.[0m[0mon_train_batch_begin[0m[0;34m([0m[0mstep[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m-> 1184[0;31m [0mtmp_logs[0m [0;34m=[0m [0mself[0m[0;34m.[0m[0mtrain_function[0m[0;34m([0m[0miterator[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 1185[0m [0;32mif[0m [0mdata_handler[0m[0;34m.[0m[0mshould_sync[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 1186[0m [0mcontext[0m[0;34m.[0m[0masync_wait[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py[0m in [0;36m__call__[0;34m(self, *args, **kwds)[0m [1;32m 883[0m [0;34m[0m[0m [1;32m 884[0m [0;32mwith[0m [0mOptionalXlaContext[0m[0;34m([0m[0mself[0m[0;34m.[0m[0m_jit_compile[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m--> 885[0;31m [0mresult[0m [0;34m=[0m [0mself[0m[0;34m.[0m[0m_call[0m[0;34m([0m[0;34m*[0m[0margs[0m[0;34m,[0m [0;34m**[0m[0mkwds[0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 886[0m [0;34m[0m[0m [1;32m 887[0m [0mnew_tracing_count[0m [0;34m=[0m [0mself[0m[0;34m.[0m[0mexperimental_get_tracing_count[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/def_function.py[0m in [0;36m_call[0;34m(self, *args, **kwds)[0m [1;32m 915[0m [0;31m# In this case we have created variables on the first call, so we run the[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [1;32m 916[0m [0;31m# defunned version which is guaranteed to never create variables.[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [0;32m--> 917[0;31m [0;32mreturn[0m [0mself[0m[0;34m.[0m[0m_stateless_fn[0m[0;34m([0m[0;34m*[0m[0margs[0m[0;34m,[0m [0;34m**[0m[0mkwds[0m[0;34m)[0m [0;31m# pylint: disable=not-callable[0m[0;34m[0m[0;34m[0m[0m [0m[1;32m 918[0m [0;32melif[0m [0mself[0m[0;34m.[0m[0m_stateful_fn[0m [0;32mis[0m [0;32mnot[0m [0;32mNone[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 919[0m [0;31m# Release the lock early so that multiple threads can perform the call[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [0;32m~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py[0m in [0;36m__call__[0;34m(self, *args, **kwargs)[0m [1;32m 3037[0m (graph_function, [1;32m 3038[0m filtered_flat_args) = self._maybe_define_function(args, kwargs) [0;32m-> 3039[0;31m return graph_function._call_flat( [0m[1;32m 3040[0m filtered_flat_args, captured_inputs=graph_function.captured_inputs) # pylint: disable=protected-access [1;32m 3041[0m [0;34m[0m[0m [0;32m~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py[0m in [0;36m_call_flat[0;34m(self, args, captured_inputs, cancellation_manager)[0m [1;32m 1961[0m and executing_eagerly): [1;32m 1962[0m [0;31m# No tape is watching; skip to running the function.[0m[0;34m[0m[0;34m[0m[0;34m[0m[0m [0;32m-> 1963[0;31m return self._build_call_outputs(self._inference_function.call( [0m[1;32m 1964[0m ctx, args, cancellation_manager=cancellation_manager)) [1;32m 1965[0m forward_backward = self._select_forward_and_backward_functions( [0;32m~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/function.py[0m in [0;36mcall[0;34m(self, ctx, args, cancellation_manager)[0m [1;32m 589[0m [0;32mwith[0m [0m_InterpolateFunctionError[0m[0;34m([0m[0mself[0m[0;34m)[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 590[0m [0;32mif[0m [0mcancellation_manager[0m [0;32mis[0m [0;32mNone[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;32m--> 591[0;31m outputs = execute.execute( [0m[1;32m 592[0m [0mstr[0m[0;34m([0m[0mself[0m[0;34m.[0m[0msignature[0m[0;34m.[0m[0mname[0m[0;34m)[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m [1;32m 593[0m [0mnum_outputs[0m[0;34m=[0m[0mself[0m[0;34m.[0m[0m_num_outputs[0m[0;34m,[0m[0;34m[0m[0;34m[0m[0m [0;32m~/anaconda3/lib/python3.8/site-packages/tensorflow/python/eager/execute.py[0m in [0;36mquick_execute[0;34m(op_name, num_outputs, inputs, attrs, ctx, name)[0m [1;32m 57[0m [0;32mtry[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [1;32m 58[0m [0mctx[0m[0;34m.[0m[0mensure_initialized[0m[0;34m([0m[0;34m)[0m[0;34m[0m[0;34m[0m[0m [0;32m---> 59[0;31m tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, [0m[1;32m 60[0m inputs, attrs, num_outputs) [1;32m 61[0m [0;32mexcept[0m [0mcore[0m[0;34m.[0m[0m_NotOkStatusException[0m [0;32mas[0m [0me[0m[0;34m:[0m[0;34m[0m[0;34m[0m[0m [0;31mKeyboardInterrupt[0m:
In [7]:
# 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)):
CNN = CNN_keras[i][j]
train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
test_accuracy[i][j] = CNN.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()In [8]:
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# We import the data set
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# Normalize pixel values to be between 0 and 1 by dividing by 255.
train_images, test_images = train_images / 255.0, test_images / 255.0In [9]:
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
# The CIFAR labels happen to be arrays,
# which is why you need the extra index
plt.xlabel(class_names[train_labels[i][0]])
plt.show()In [10]:
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# Let's display the architecture of our model so far.
model.summary()In [11]:
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
Here's the complete architecture of our model.
model.summary()In [12]:
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))In [13]:
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(test_acc)
