125 KiB
125 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()Metal device set to: Apple M1
/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/keras/optimizer_v2/gradient_descent.py:102: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead. super(SGD, self).__init__(name, **kwargs) 2023-11-08 15:24:42.293245: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz
[0;31m---------------------------------------------------------------------------[0m [0;31mKeyboardInterrupt[0m Traceback (most recent call last) Input [0;32mIn [6][0m, in [0;36m<cell line: 3>[0;34m()[0m [1;32m 4[0m [38;5;28;01mfor[39;00m j, lmbd [38;5;129;01min[39;00m [38;5;28menumerate[39m(lmbd_vals): [1;32m 5[0m CNN [38;5;241m=[39m create_convolutional_neural_network_keras(input_shape, receptive_field, [1;32m 6[0m n_filters, n_neurons_connected, n_categories, [1;32m 7[0m eta, lmbd) [0;32m----> 8[0m [43mCNN[49m[38;5;241;43m.[39;49m[43mfit[49m[43m([49m[43mX_train[49m[43m,[49m[43m [49m[43mY_train[49m[43m,[49m[43m [49m[43mepochs[49m[38;5;241;43m=[39;49m[43mepochs[49m[43m,[49m[43m [49m[43mbatch_size[49m[38;5;241;43m=[39;49m[43mbatch_size[49m[43m,[49m[43m [49m[43mverbose[49m[38;5;241;43m=[39;49m[38;5;241;43m0[39;49m[43m)[49m [1;32m 9[0m scores [38;5;241m=[39m CNN[38;5;241m.[39mevaluate(X_test, Y_test) [1;32m 11[0m CNN_keras[i][j] [38;5;241m=[39m CNN File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/keras/utils/traceback_utils.py:64[0m, in [0;36mfilter_traceback.<locals>.error_handler[0;34m(*args, **kwargs)[0m [1;32m 62[0m filtered_tb [38;5;241m=[39m [38;5;28;01mNone[39;00m [1;32m 63[0m [38;5;28;01mtry[39;00m: [0;32m---> 64[0m [38;5;28;01mreturn[39;00m [43mfn[49m[43m([49m[38;5;241;43m*[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 65[0m [38;5;28;01mexcept[39;00m [38;5;167;01mException[39;00m [38;5;28;01mas[39;00m e: [38;5;66;03m# pylint: disable=broad-except[39;00m [1;32m 66[0m filtered_tb [38;5;241m=[39m _process_traceback_frames(e[38;5;241m.[39m__traceback__) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/keras/engine/training.py:1384[0m, in [0;36mModel.fit[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 1377[0m [38;5;28;01mwith[39;00m tf[38;5;241m.[39mprofiler[38;5;241m.[39mexperimental[38;5;241m.[39mTrace( [1;32m 1378[0m [38;5;124m'[39m[38;5;124mtrain[39m[38;5;124m'[39m, [1;32m 1379[0m epoch_num[38;5;241m=[39mepoch, [1;32m 1380[0m step_num[38;5;241m=[39mstep, [1;32m 1381[0m batch_size[38;5;241m=[39mbatch_size, [1;32m 1382[0m _r[38;5;241m=[39m[38;5;241m1[39m): [1;32m 1383[0m callbacks[38;5;241m.[39mon_train_batch_begin(step) [0;32m-> 1384[0m tmp_logs [38;5;241m=[39m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43mtrain_function[49m[43m([49m[43miterator[49m[43m)[49m [1;32m 1385[0m [38;5;28;01mif[39;00m data_handler[38;5;241m.[39mshould_sync: [1;32m 1386[0m context[38;5;241m.[39masync_wait() File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/util/traceback_utils.py:150[0m, in [0;36mfilter_traceback.<locals>.error_handler[0;34m(*args, **kwargs)[0m [1;32m 148[0m filtered_tb [38;5;241m=[39m [38;5;28;01mNone[39;00m [1;32m 149[0m [38;5;28;01mtry[39;00m: [0;32m--> 150[0m [38;5;28;01mreturn[39;00m [43mfn[49m[43m([49m[38;5;241;43m*[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwargs[49m[43m)[49m [1;32m 151[0m [38;5;28;01mexcept[39;00m [38;5;167;01mException[39;00m [38;5;28;01mas[39;00m e: [1;32m 152[0m filtered_tb [38;5;241m=[39m _process_traceback_frames(e[38;5;241m.[39m__traceback__) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py:915[0m, in [0;36mFunction.__call__[0;34m(self, *args, **kwds)[0m [1;32m 912[0m compiler [38;5;241m=[39m [38;5;124m"[39m[38;5;124mxla[39m[38;5;124m"[39m [38;5;28;01mif[39;00m [38;5;28mself[39m[38;5;241m.[39m_jit_compile [38;5;28;01melse[39;00m [38;5;124m"[39m[38;5;124mnonXla[39m[38;5;124m"[39m [1;32m 914[0m [38;5;28;01mwith[39;00m OptionalXlaContext([38;5;28mself[39m[38;5;241m.[39m_jit_compile): [0;32m--> 915[0m result [38;5;241m=[39m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_call[49m[43m([49m[38;5;241;43m*[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwds[49m[43m)[49m [1;32m 917[0m new_tracing_count [38;5;241m=[39m [38;5;28mself[39m[38;5;241m.[39mexperimental_get_tracing_count() [1;32m 918[0m without_tracing [38;5;241m=[39m (tracing_count [38;5;241m==[39m new_tracing_count) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py:947[0m, in [0;36mFunction._call[0;34m(self, *args, **kwds)[0m [1;32m 944[0m [38;5;28mself[39m[38;5;241m.[39m_lock[38;5;241m.[39mrelease() [1;32m 945[0m [38;5;66;03m# In this case we have created variables on the first call, so we run the[39;00m [1;32m 946[0m [38;5;66;03m# defunned version which is guaranteed to never create variables.[39;00m [0;32m--> 947[0m [38;5;28;01mreturn[39;00m [38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_stateless_fn[49m[43m([49m[38;5;241;43m*[39;49m[43margs[49m[43m,[49m[43m [49m[38;5;241;43m*[39;49m[38;5;241;43m*[39;49m[43mkwds[49m[43m)[49m [38;5;66;03m# pylint: disable=not-callable[39;00m [1;32m 948[0m [38;5;28;01melif[39;00m [38;5;28mself[39m[38;5;241m.[39m_stateful_fn [38;5;129;01mis[39;00m [38;5;129;01mnot[39;00m [38;5;28;01mNone[39;00m: [1;32m 949[0m [38;5;66;03m# Release the lock early so that multiple threads can perform the call[39;00m [1;32m 950[0m [38;5;66;03m# in parallel.[39;00m [1;32m 951[0m [38;5;28mself[39m[38;5;241m.[39m_lock[38;5;241m.[39mrelease() File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/function.py:2956[0m, in [0;36mFunction.__call__[0;34m(self, *args, **kwargs)[0m [1;32m 2953[0m [38;5;28;01mwith[39;00m [38;5;28mself[39m[38;5;241m.[39m_lock: [1;32m 2954[0m (graph_function, [1;32m 2955[0m filtered_flat_args) [38;5;241m=[39m [38;5;28mself[39m[38;5;241m.[39m_maybe_define_function(args, kwargs) [0;32m-> 2956[0m [38;5;28;01mreturn[39;00m [43mgraph_function[49m[38;5;241;43m.[39;49m[43m_call_flat[49m[43m([49m [1;32m 2957[0m [43m [49m[43mfiltered_flat_args[49m[43m,[49m[43m [49m[43mcaptured_inputs[49m[38;5;241;43m=[39;49m[43mgraph_function[49m[38;5;241;43m.[39;49m[43mcaptured_inputs[49m[43m)[49m File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/function.py:1853[0m, in [0;36mConcreteFunction._call_flat[0;34m(self, args, captured_inputs, cancellation_manager)[0m [1;32m 1849[0m possible_gradient_type [38;5;241m=[39m gradients_util[38;5;241m.[39mPossibleTapeGradientTypes(args) [1;32m 1850[0m [38;5;28;01mif[39;00m (possible_gradient_type [38;5;241m==[39m gradients_util[38;5;241m.[39mPOSSIBLE_GRADIENT_TYPES_NONE [1;32m 1851[0m [38;5;129;01mand[39;00m executing_eagerly): [1;32m 1852[0m [38;5;66;03m# No tape is watching; skip to running the function.[39;00m [0;32m-> 1853[0m [38;5;28;01mreturn[39;00m [38;5;28mself[39m[38;5;241m.[39m_build_call_outputs([38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_inference_function[49m[38;5;241;43m.[39;49m[43mcall[49m[43m([49m [1;32m 1854[0m [43m [49m[43mctx[49m[43m,[49m[43m [49m[43margs[49m[43m,[49m[43m [49m[43mcancellation_manager[49m[38;5;241;43m=[39;49m[43mcancellation_manager[49m[43m)[49m) [1;32m 1855[0m forward_backward [38;5;241m=[39m [38;5;28mself[39m[38;5;241m.[39m_select_forward_and_backward_functions( [1;32m 1856[0m args, [1;32m 1857[0m possible_gradient_type, [1;32m 1858[0m executing_eagerly) [1;32m 1859[0m forward_function, args_with_tangents [38;5;241m=[39m forward_backward[38;5;241m.[39mforward() File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/function.py:499[0m, in [0;36m_EagerDefinedFunction.call[0;34m(self, ctx, args, cancellation_manager)[0m [1;32m 497[0m [38;5;28;01mwith[39;00m _InterpolateFunctionError([38;5;28mself[39m): [1;32m 498[0m [38;5;28;01mif[39;00m cancellation_manager [38;5;129;01mis[39;00m [38;5;28;01mNone[39;00m: [0;32m--> 499[0m outputs [38;5;241m=[39m [43mexecute[49m[38;5;241;43m.[39;49m[43mexecute[49m[43m([49m [1;32m 500[0m [43m [49m[38;5;28;43mstr[39;49m[43m([49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43msignature[49m[38;5;241;43m.[39;49m[43mname[49m[43m)[49m[43m,[49m [1;32m 501[0m [43m [49m[43mnum_outputs[49m[38;5;241;43m=[39;49m[38;5;28;43mself[39;49m[38;5;241;43m.[39;49m[43m_num_outputs[49m[43m,[49m [1;32m 502[0m [43m [49m[43minputs[49m[38;5;241;43m=[39;49m[43margs[49m[43m,[49m [1;32m 503[0m [43m [49m[43mattrs[49m[38;5;241;43m=[39;49m[43mattrs[49m[43m,[49m [1;32m 504[0m [43m [49m[43mctx[49m[38;5;241;43m=[39;49m[43mctx[49m[43m)[49m [1;32m 505[0m [38;5;28;01melse[39;00m: [1;32m 506[0m outputs [38;5;241m=[39m execute[38;5;241m.[39mexecute_with_cancellation( [1;32m 507[0m [38;5;28mstr[39m([38;5;28mself[39m[38;5;241m.[39msignature[38;5;241m.[39mname), [1;32m 508[0m num_outputs[38;5;241m=[39m[38;5;28mself[39m[38;5;241m.[39m_num_outputs, [0;32m (...)[0m [1;32m 511[0m ctx[38;5;241m=[39mctx, [1;32m 512[0m cancellation_manager[38;5;241m=[39mcancellation_manager) File [0;32m~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/eager/execute.py:54[0m, in [0;36mquick_execute[0;34m(op_name, num_outputs, inputs, attrs, ctx, name)[0m [1;32m 52[0m [38;5;28;01mtry[39;00m: [1;32m 53[0m ctx[38;5;241m.[39mensure_initialized() [0;32m---> 54[0m tensors [38;5;241m=[39m [43mpywrap_tfe[49m[38;5;241;43m.[39;49m[43mTFE_Py_Execute[49m[43m([49m[43mctx[49m[38;5;241;43m.[39;49m[43m_handle[49m[43m,[49m[43m [49m[43mdevice_name[49m[43m,[49m[43m [49m[43mop_name[49m[43m,[49m [1;32m 55[0m [43m [49m[43minputs[49m[43m,[49m[43m [49m[43mattrs[49m[43m,[49m[43m [49m[43mnum_outputs[49m[43m)[49m [1;32m 56[0m [38;5;28;01mexcept[39;00m core[38;5;241m.[39m_NotOkStatusException [38;5;28;01mas[39;00m e: [1;32m 57[0m [38;5;28;01mif[39;00m name [38;5;129;01mis[39;00m [38;5;129;01mnot[39;00m [38;5;28;01mNone[39;00m: [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)
