added slides

This commit is contained in:
Morten Hjorth-Jensen
2024-11-03 14:40:38 +01:00
parent 2c804a14e4
commit e9d6ea5784
27 changed files with 7141 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
Outlook,Temperature,Humidity,Wind,Ride
Sunny,Hot,High,Weak,0
Sunny,Hot,High,Strong,1
Overcast,Hot,High,Weak,1
Rain,Mild,High,Weak,1
Rain,Cool,Normal,Weak,1
Rain,Cool,Normal,Strong,0
Overcast,Cool,Normal,Strong,1
Sunny,Mild,High,Weak,0
Sunny,Cool,Normal,Weak,1
Rain,Mild,Normal,Weak,1
Sunny,Mild,Normal,Strong,1
Overcast,Mild,High,Strong,1
Overcast,Hot,Normal,Weak,1
Rain,Mild,High,Strong,0
@@ -0,0 +1,39 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 730, in _async_poll_for_reply
msg = await ensure_async(self.kc.shell_channel.get_msg(timeout=new_timeout))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 96, in ensure_async
result = await obj
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_client/channels.py", line 315, in get_msg
raise Empty
_queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 949, in async_execute_cell
exec_reply = await self.task_poll_for_reply
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 754, in _async_poll_for_reply
await self._async_handle_timeout(timeout, cell)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 801, in _async_handle_timeout
raise CellTimeoutError.error_from_timeout_and_cell(
nbclient.exceptions.CellTimeoutError: A cell timed out while it was being executed, after 30 seconds.
The message was: Cell execution timed out.
Here is a preview of the cell contents:
-------------------
['eta_vals = np.logspace(-5, 1, 7)', 'lmbd_vals = np.logspace(-5, 1, 7)', '# store the models for later use', 'DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)', '']
...
[' ', ' print("Learning rate = ", eta)', ' print("Lambda = ", lmbd)', ' print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))', ' print()']
-------------------
@@ -0,0 +1,245 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
import autograd.numpy as np
from autograd import grad, elementwise_grad
import autograd.numpy.random as npr
from matplotlib import pyplot as plt
def sigmoid(z):
return 1/(1 + np.exp(-z))
# The neural network with one input layer and one output layer,
# but with number of hidden layers specified by the user.
def deep_neural_network(deep_params, x):
# N_hidden is the number of hidden layers
N_hidden = np.size(deep_params) - 1 # -1 since params consists of
# parameters to all the hidden
# layers AND the output layer.
# Assumes input x being an one-dimensional array
num_values = np.size(x)
x = x.reshape(-1, num_values)
# Assume that the input layer does nothing to the input x
x_input = x
# Due to multiple hidden layers, define a variable referencing to the
# output of the previous layer:
x_prev = x_input
## Hidden layers:
for l in range(N_hidden):
# From the list of parameters P; find the correct weigths and bias for this layer
w_hidden = deep_params[l]
# Add a row of ones to include bias
x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)
z_hidden = np.matmul(w_hidden, x_prev)
x_hidden = sigmoid(z_hidden)
# Update x_prev such that next layer can use the output from this layer
x_prev = x_hidden
## Output layer:
# Get the weights and bias for this layer
w_output = deep_params[-1]
# Include bias:
x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)
z_output = np.matmul(w_output, x_prev)
x_output = z_output
return x_output
# The trial solution using the deep neural network:
def g_trial_deep(x,params, g0 = 10):
return g0 + x*deep_neural_network(params, x)
# The right side of the ODE:
def g(x, g_trial, gamma = 2):
return -gamma*g_trial
# The same cost function as before, but calls deep_neural_network instead.
def cost_function_deep(P, x):
# Evaluate the trial function with the current parameters P
g_t = g_trial_deep(x,P)
# Find the derivative w.r.t x of the neural network
d_net_out = elementwise_grad(deep_neural_network,1)(P,x)
# Find the derivative w.r.t x of the trial function
d_g_t = elementwise_grad(g_trial_deep,0)(x,P)
# The right side of the ODE
func = g(x, g_t)
err_sqr = (d_g_t - func)**2
cost_sum = np.sum(err_sqr)
return cost_sum / np.size(err_sqr)
# Solve the exponential decay ODE using neural network with one input and one output layer,
# but with specified number of hidden layers from the user.
def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):
# num_hidden_neurons is now a list of number of neurons within each hidden layer
# The number of elements in the list num_hidden_neurons thus represents
# the number of hidden layers.
# Find the number of hidden layers:
N_hidden = np.size(num_neurons)
## Set up initial weights and biases
# Initialize the list of parameters:
P = [None]*(N_hidden + 1) # + 1 to include the output layer
P[0] = npr.randn(num_neurons[0], 2 )
for l in range(1,N_hidden):
P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias
# For the output layer
P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included
print('Initial cost: %g'%cost_function_deep(P, x))
## Start finding the optimal weights using gradient descent
# Find the Python function that represents the gradient of the cost function
# w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer
cost_function_deep_grad = grad(cost_function_deep,0)
# Let the update be done num_iter times
for i in range(num_iter):
# Evaluate the gradient at the current weights and biases in P.
# The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases
# in the hidden layers and output layers evaluated at x.
cost_deep_grad = cost_function_deep_grad(P, x)
for l in range(N_hidden+1):
P[l] = P[l] - lmb * cost_deep_grad[l]
print('Final cost: %g'%cost_function_deep(P, x))
return P
def g_analytic(x, gamma = 2, g0 = 10):
return g0*np.exp(-gamma*x)
# Solve the given problem
if __name__ == '__main__':
npr.seed(15)
## Decide the vales of arguments to the function to solve
N = 10
x = np.linspace(0, 1, N)
## Set up the initial parameters
num_hidden_neurons = np.array([10,10])
num_iter = 10000
lmb = 0.001
P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
res = g_trial_deep(x,P)
res_analytical = g_analytic(x)
plt.figure(figsize=(10,10))
plt.title('Performance of a deep neural network solving an ODE compared to the analytical solution')
plt.plot(x, res_analytical)
plt.plot(x, res[0,:])
plt.legend(['analytical','dnn'])
plt.ylabel('g(x)')
plt.show()
------------------
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/numpy/core/fromnumeric.py:3255, in size(a, axis)
 3254 try:
-> 3255 return a.size
 3256 except AttributeError:
AttributeError: 'list' object has no attribute 'size'
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
Cell In[2], line 146
 143 num_iter = 10000
 144 lmb = 0.001
--> 146 P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
 148 res = g_trial_deep(x,P)
 149 res_analytical = g_analytic(x)
Cell In[2], line 108, in solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb)
 105 # For the output layer
 106 P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included
--> 108 print('Initial cost: %g'%cost_function_deep(P, x))
 110 ## Start finding the optimal weights using gradient descent
 111
 112 # Find the Python function that represents the gradient of the cost function
 113 # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer
 114 cost_function_deep_grad = grad(cost_function_deep,0)
Cell In[2], line 69, in cost_function_deep(P, x)
 66 def cost_function_deep(P, x):
 67
 68 # Evaluate the trial function with the current parameters P
---> 69 g_t = g_trial_deep(x,P)
 71 # Find the derivative w.r.t x of the neural network
 72 d_net_out = elementwise_grad(deep_neural_network,1)(P,x)
Cell In[2], line 59, in g_trial_deep(x, params, g0)
 58 def g_trial_deep(x,params, g0 = 10):
---> 59 return g0 + x*deep_neural_network(params, x)
Cell In[2], line 14, in deep_neural_network(deep_params, x)
 11 def deep_neural_network(deep_params, x):
 12 # N_hidden is the number of hidden layers
---> 14 N_hidden = np.size(deep_params) - 1 # -1 since params consists of
 15 # parameters to all the hidden
 16 # layers AND the output layer.
 17
 18 # Assumes input x being an one-dimensional array
 19 num_values = np.size(x)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/tracer.py:48, in primitive.<locals>.f_wrapped(*args, **kwargs)
 46 return new_box(ans, trace, node)
 47 else:
---> 48 return f_raw(*args, **kwargs)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/numpy/core/fromnumeric.py:3257, in size(a, axis)
 3255 return a.size
 3256 except AttributeError:
-> 3257 return asarray(a).size
 3258 else:
 3259 try:
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (3,) + inhomogeneous part.
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (3,) + inhomogeneous part.
@@ -0,0 +1,70 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
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)
------------------
---------------------------------------------------------------------------
NotFoundError Traceback (most recent call last)
Cell In[4], line 1
----> 1 from tensorflow.keras import datasets, layers, models
 2 from tensorflow.keras.layers import Input
 3 from tensorflow.keras.models import Sequential #This allows appending layers to existing models
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/__init__.py:440
 438 _plugin_dir = _os.path.join(_s, 'tensorflow-plugins')
 439 if _os.path.exists(_plugin_dir):
--> 440 _ll.load_library(_plugin_dir)
 441 # Load Pluggable Device Library
 442 _ll.load_pluggable_device_library(_plugin_dir)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/framework/load_library.py:151, in load_library(library_location)
 148 kernel_libraries = [library_location]
 150 for lib in kernel_libraries:
--> 151 py_tf.TF_LoadLibrary(lib)
 153 else:
 154 raise OSError(
 155 errno.ENOENT,
 156 'The file or folder to load kernel libraries from does not exist.',
 157 library_location)
NotFoundError: dlopen(/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '_TF_GetInputPropertiesList'
NotFoundError: dlopen(/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '_TF_GetInputPropertiesList'
@@ -0,0 +1,120 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
%matplotlib inline
# Start importing packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU
from tensorflow.keras import optimizers
from tensorflow.keras import regularizers
from tensorflow.keras.utils import to_categorical
# convert into dataset matrix
def convertToMatrix(data, step):
X, Y =[], []
for i in range(len(data)-step):
d=i+step
X.append(data[i:d,])
Y.append(data[d,])
return np.array(X), np.array(Y)
step = 4
N = 1000
Tp = 800
t=np.arange(0,N)
x=np.sin(0.02*t)+2*np.random.rand(N)
df = pd.DataFrame(x)
df.head()
plt.plot(df)
plt.show()
values=df.values
train,test = values[0:Tp,:], values[Tp:N,:]
# add step elements into train and test
test = np.append(test,np.repeat(test[-1,],step))
train = np.append(train,np.repeat(train[-1,],step))
trainX,trainY =convertToMatrix(train,step)
testX,testY =convertToMatrix(test,step)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
model = Sequential()
model.add(SimpleRNN(units=32, input_shape=(1,step), activation="relu"))
model.add(Dense(8, activation="relu"))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='rmsprop')
model.summary()
model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)
trainPredict = model.predict(trainX)
testPredict= model.predict(testX)
predicted=np.concatenate((trainPredict,testPredict),axis=0)
trainScore = model.evaluate(trainX, trainY, verbose=0)
print(trainScore)
index = df.index.values
plt.plot(index,df)
plt.plot(index,predicted)
plt.axvline(df.index[Tp], c="r")
plt.show()
------------------
---------------------------------------------------------------------------
NotFoundError Traceback (most recent call last)
Cell In[1], line 7
 5 import numpy as np
 6 import matplotlib.pyplot as plt
----> 7 import tensorflow as tf
 8 from tensorflow.keras import datasets, layers, models
 9 from tensorflow.keras.layers import Input
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/__init__.py:440
 438 _plugin_dir = _os.path.join(_s, 'tensorflow-plugins')
 439 if _os.path.exists(_plugin_dir):
--> 440 _ll.load_library(_plugin_dir)
 441 # Load Pluggable Device Library
 442 _ll.load_pluggable_device_library(_plugin_dir)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/framework/load_library.py:151, in load_library(library_location)
 148 kernel_libraries = [library_location]
 150 for lib in kernel_libraries:
--> 151 py_tf.TF_LoadLibrary(lib)
 153 else:
 154 raise OSError(
 155 errno.ENOENT,
 156 'The file or folder to load kernel libraries from does not exist.',
 157 library_location)
NotFoundError: dlopen(/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '_TF_GetInputPropertiesList'
NotFoundError: dlopen(/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '_TF_GetInputPropertiesList'
@@ -0,0 +1,72 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
from random import random, seed
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
x = np.arange(0, 1, 0.05)
y = np.arange(0, 1, 0.05)
x, y = np.meshgrid(x,y)
def FrankeFunction(x,y):
term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
return term1 + term2 + term3 + term4
z = FrankeFunction(x, y)
# Plot the surface.
surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
# Customize the z axis.
ax.set_zlim(-0.10, 1.40)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
------------------
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[30], line 9
 6 from random import random, seed
 8 fig = plt.figure()
----> 9 ax = fig.gca(projection='3d')
 11 # Make data.
 12 x = np.arange(0, 1, 0.05)
TypeError: gca() got an unexpected keyword argument 'projection'
TypeError: gca() got an unexpected keyword argument 'projection'
@@ -0,0 +1,124 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
%matplotlib inline
# Common imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from sklearn.metrics import mean_squared_error
from IPython.display import display
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("chddata.csv"),'r')
# Read the chd data as csv file and organize the data into arrays with age group, age, and chd
chd = pd.read_csv(infile, names=('ID', 'Age', 'Agegroup', 'CHD'))
chd.columns = ['ID', 'Age', 'Agegroup', 'CHD']
output = chd['CHD']
age = chd['Age']
agegroup = chd['Agegroup']
numberID = chd['ID']
display(chd)
plt.scatter(age, output, marker='o')
plt.axis([18,70.0,-0.1, 1.2])
plt.xlabel(r'Age')
plt.ylabel(r'CHD')
plt.title(r'Age distribution and Coronary heart disease')
plt.show()
------------------
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/matplotlib/style/core.py:137, in use(style)
 136 try:
--> 137 style = _rc_params_in_file(style)
 138 except OSError as err:
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/matplotlib/__init__.py:870, in _rc_params_in_file(fname, transform, fail_on_error)
 869 rc_temp = {}
--> 870 with _open_file_or_url(fname) as fd:
 871 try:
File ~/miniforge3/envs/myenv/lib/python3.9/contextlib.py:119, in _GeneratorContextManager.__enter__(self)
 118 try:
--> 119 return next(self.gen)
 120 except StopIteration:
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/matplotlib/__init__.py:847, in _open_file_or_url(fname)
 846 fname = os.path.expanduser(fname)
--> 847 with open(fname, encoding='utf-8') as f:
 848 yield f
FileNotFoundError: [Errno 2] No such file or directory: 'seaborn'
The above exception was the direct cause of the following exception:
OSError Traceback (most recent call last)
Cell In[1], line 14
 12 from IPython.display import display
 13 from pylab import plt, mpl
---> 14 plt.style.use('seaborn')
 15 mpl.rcParams['font.family'] = 'serif'
 17 # Where to save the figures and data files
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/matplotlib/style/core.py:139, in use(style)
 137 style = _rc_params_in_file(style)
 138 except OSError as err:
--> 139 raise OSError(
 140 f"{style!r} is not a valid package style, path of style "
 141 f"file, URL of style file, or library style name (library "
 142 f"styles are listed in `style.available`)") from err
 143 filtered = {}
 144 for k in style: # don't trigger RcParams.__getitem__('backend')
OSError: 'seaborn' is not a valid package style, path of style file, URL of style file, or library style name (library styles are listed in `style.available`)
OSError: 'seaborn' is not a valid package style, path of style file, URL of style file, or library style name (library styles are listed in `style.available`)
@@ -0,0 +1,41 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
# Import the necessary packages
import numpy
from cvxopt import matrix
from cvxopt import solvers
P = matrix(numpy.diag([1,0]), tc=d)
q = matrix(numpy.array([3,4]), tc=d)
G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=d)
h = matrix(numpy.array([0,0,-15,100,80]), tc=d)
# Construct the QP, invoke solver
sol = solvers.qp(P,q,G,h)
# Extract optimal value and solution
sol[x]
sol[primal objective]
------------------
 Cell In[5], line 5
 P = matrix(numpy.diag([1,0]), tc=d)
 ^
SyntaxError: invalid character '' (U+2019)
SyntaxError: invalid character '' (U+2019) (3974140161.py, line 5)
@@ -0,0 +1,45 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
heads_proba = 0.51
coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
plt.figure(figsize=(8,3.5))
plt.plot(cumulative_heads_ratio)
plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
plt.xlabel("Number of coin tosses")
plt.ylabel("Heads ratio")
plt.legend(loc="lower right")
plt.axis([0, 10000, 0.42, 0.58])
save_fig("votingsimple")
plt.show()
------------------
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 2
 1 heads_proba = 0.51
----> 2 coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
 3 cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
 4 plt.figure(figsize=(8,3.5))
NameError: name 'np' is not defined
NameError: name 'np' is not defined
@@ -0,0 +1,55 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
%matplotlib inline
import numpy as np
import numpy.linalg as la
import scipy.optimize as sopt
import matplotlib.pyplot as pt
from mpl_toolkits.mplot3d import axes3d
def f(x):
return 0.5*x[0]**2 + 2.5*x[1]**2
def df(x):
return np.array([x[0], 5*x[1]])
fig = pt.figure()
ax = fig.gca(projection="3d")
xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]
fmesh = f(np.array([xmesh, ymesh]))
ax.plot_surface(xmesh, ymesh, fmesh)
------------------
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[1], line 18
 15 return np.array([x[0], 5*x[1]])
 17 fig = pt.figure()
---> 18 ax = fig.gca(projection="3d")
 20 xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]
 21 fmesh = f(np.array([xmesh, ymesh]))
TypeError: gca() got an unexpected keyword argument 'projection'
TypeError: gca() got an unexpected keyword argument 'projection'
@@ -0,0 +1,61 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
%matplotlib inline
import time
import numpy as np
import tensorflow as tf
from matplotlib import image
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from IPython.display import display
np.random.seed(2021)
------------------
---------------------------------------------------------------------------
NotFoundError Traceback (most recent call last)
Cell In[1], line 5
 3 import time
 4 import numpy as np
----> 5 import tensorflow as tf
 6 from matplotlib import image
 7 import matplotlib.pyplot as plt
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/__init__.py:440
 438 _plugin_dir = _os.path.join(_s, 'tensorflow-plugins')
 439 if _os.path.exists(_plugin_dir):
--> 440 _ll.load_library(_plugin_dir)
 441 # Load Pluggable Device Library
 442 _ll.load_pluggable_device_library(_plugin_dir)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/framework/load_library.py:151, in load_library(library_location)
 148 kernel_libraries = [library_location]
 150 for lib in kernel_libraries:
--> 151 py_tf.TF_LoadLibrary(lib)
 153 else:
 154 raise OSError(
 155 errno.ENOENT,
 156 'The file or folder to load kernel libraries from does not exist.',
 157 library_location)
NotFoundError: dlopen(/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '_TF_GetInputPropertiesList'
NotFoundError: dlopen(/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '_TF_GetInputPropertiesList'
@@ -0,0 +1,57 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
sol1 = np.array([0.60610368, 4.0076268, 0.0, 0.56469864])
print(np.allclose(a1, sol1))
------------------
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 3
 1 sol1 = np.array([0.60610368, 4.0076268, 0.0, 0.56469864])
----> 3 print(np.allclose(a1, sol1))
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/tracer.py:48, in primitive.<locals>.f_wrapped(*args, **kwargs)
 46 return new_box(ans, trace, node)
 47 else:
---> 48 return f_raw(*args, **kwargs)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/numpy/core/numeric.py:2241, in allclose(a, b, rtol, atol, equal_nan)
 2170 @array_function_dispatch(_allclose_dispatcher)
 2171 def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
 2172  """
 2173  Returns True if two arrays are element-wise equal within a tolerance.
 2174
 (...)
 2239
 2240  """
-> 2241 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
 2242 return bool(res)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/numpy/core/numeric.py:2348, in isclose(a, b, rtol, atol, equal_nan)
 2345 dt = multiarray.result_type(y, 1.)
 2346 y = asanyarray(y, dtype=dt)
-> 2348 xfin = isfinite(x)
 2349 yfin = isfinite(y)
 2350 if all(xfin) and all(yfin):
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
@@ -0,0 +1,101 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
autograd_one_layer = grad(cost_one_layer, [0, 1])
W_g, b_g = autograd_one_layer(W, b, x, target)
print(W_g, b_g)
------------------
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/tracer.py:118, in new_box(value, trace, node)
 117 try:
--> 118 return box_type_mappings[type(value)](value, trace, node)
 119 except KeyError:
KeyError: <class 'ellipsis'>
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
Cell In[3], line 2
 1 autograd_one_layer = grad(cost_one_layer, [0, 1])
----> 2 W_g, b_g = autograd_one_layer(W, b, x, target)
 3 print(W_g, b_g)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/wrap_util.py:20, in unary_to_nary.<locals>.nary_operator.<locals>.nary_f(*args, **kwargs)
 18 else:
 19 x = tuple(args[i] for i in argnum)
---> 20 return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/differential_operators.py:28, in grad(fun, x)
 21 @unary_to_nary
 22 def grad(fun, x):
 23  """
 24  Returns a function which computes the gradient of `fun` with respect to
 25  positional argument number `argnum`. The returned function takes the same
 26  arguments as `fun`, but returns the gradient instead. The function `fun`
 27  should be scalar-valued. The gradient has the same type as the argument."""
---> 28 vjp, ans = _make_vjp(fun, x)
 29 if not vspace(ans).size == 1:
 30 raise TypeError("Grad only applies to real scalar-output functions. "
 31 "Try jacobian, elementwise_grad or holomorphic_grad.")
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/core.py:10, in make_vjp(fun, x)
 8 def make_vjp(fun, x):
 9 start_node = VJPNode.new_root()
---> 10 end_value, end_node = trace(start_node, fun, x)
 11 if end_node is None:
 12 def vjp(g): return vspace(x).zeros()
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/tracer.py:10, in trace(start_node, fun, x)
 8 with trace_stack.new_trace() as t:
 9 start_box = new_box(x, t, start_node)
---> 10 end_box = fun(start_box)
 11 if isbox(end_box) and end_box._trace == start_box._trace:
 12 return end_box._value, end_box._node
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/wrap_util.py:14, in unary_to_nary.<locals>.nary_operator.<locals>.nary_f.<locals>.unary_f(x)
 12 subargs = subvals(args, [(argnum, x)])
 13 else:
---> 14 subargs = subvals(args, zip(argnum, x))
 15 return fun(*subargs, **kwargs)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/util.py:6, in subvals(x, ivs)
 4 def subvals(x, ivs):
 5 x_ = list(x)
----> 6 for i, v in ivs:
 7 x_[i] = v
 8 return tuple(x_)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/tracer.py:46, in primitive.<locals>.f_wrapped(*args, **kwargs)
 44 ans = f_wrapped(*argvals, **kwargs)
 45 node = node_constructor(ans, f_wrapped, argvals, kwargs, argnums, parents)
---> 46 return new_box(ans, trace, node)
 47 else:
 48 return f_raw(*args, **kwargs)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/autograd/tracer.py:120, in new_box(value, trace, node)
 118 return box_type_mappings[type(value)](value, trace, node)
 119 except KeyError:
--> 120 raise TypeError("Can't differentiate w.r.t. type {}".format(type(value)))
TypeError: Can't differentiate w.r.t. type <class 'ellipsis'>
TypeError: Can't differentiate w.r.t. type <class 'ellipsis'>
@@ -0,0 +1,30 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
scipy.misc.imread
------------------
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[2], line 1
----> 1 scipy.misc.imread
NameError: name 'scipy' is not defined
NameError: name 'scipy' is not defined
@@ -0,0 +1,46 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
new_hobbit = {'First Name': ["Peregrin"],
'Last Name': ["Took"],
'Place of birth': ["Shire"],
'Date of Birth T.A.': [2990]
}
data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
display(data_pandas)
------------------
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/var/folders/td/3yk470mj5p931p9dtkk0y6jw0000gn/T/ipykernel_20912/1326197715.py in ?()
----> 6 new_hobbit = {'First Name': ["Peregrin"],
 7 'Last Name': ["Took"],
 8 'Place of birth': ["Shire"],
 9 'Date of Birth T.A.': [2990]
~/miniforge3/envs/myenv/lib/python3.9/site-packages/pandas/core/generic.py in ?(self, name)
 6200 and name not in self._accessors
 6201 and self._info_axis._can_hold_identifiers_and_holds_name(name)
 6202 ):
 6203 return self[name]
-> 6204 return object.__getattribute__(self, name)

AttributeError: 'DataFrame' object has no attribute 'append'
AttributeError: 'DataFrame' object has no attribute 'append'
@@ -0,0 +1,40 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
import numpy as np
X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
Xinv = np.linlag.pinv(X)
------------------
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[6], line 3
 1 import numpy as np
 2 X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])
----> 3 Xinv = np.linlag.pinv(X)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/numpy/__init__.py:333, in __getattr__(attr)
 330 "Removed in NumPy 1.25.0"
 331 raise RuntimeError("Tester was removed in NumPy 1.25.")
--> 333 raise AttributeError("module {!r} has no attribute "
 334 "{!r}".format(__name__, attr))
AttributeError: module 'numpy' has no attribute 'linlag'
AttributeError: module 'numpy' has no attribute 'linlag'
@@ -0,0 +1,124 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
%matplotlib inline
# Common imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from sklearn.metrics import mean_squared_error
from IPython.display import display
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'
# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"
if not os.path.exists(PROJECT_ROOT_DIR):
os.mkdir(PROJECT_ROOT_DIR)
if not os.path.exists(FIGURE_ID):
os.makedirs(FIGURE_ID)
if not os.path.exists(DATA_ID):
os.makedirs(DATA_ID)
def image_path(fig_id):
return os.path.join(FIGURE_ID, fig_id)
def data_path(dat_id):
return os.path.join(DATA_ID, dat_id)
def save_fig(fig_id):
plt.savefig(image_path(fig_id) + ".png", format='png')
infile = open(data_path("chddata.csv"),'r')
# Read the chd data as csv file and organize the data into arrays with age group, age, and chd
chd = pd.read_csv(infile, names=('ID', 'Age', 'Agegroup', 'CHD'))
chd.columns = ['ID', 'Age', 'Agegroup', 'CHD']
output = chd['CHD']
age = chd['Age']
agegroup = chd['Agegroup']
numberID = chd['ID']
display(chd)
plt.scatter(age, output, marker='o')
plt.axis([18,70.0,-0.1, 1.2])
plt.xlabel(r'Age')
plt.ylabel(r'CHD')
plt.title(r'Age distribution and Coronary heart disease')
plt.show()
------------------
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/matplotlib/style/core.py:137, in use(style)
 136 try:
--> 137 style = _rc_params_in_file(style)
 138 except OSError as err:
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/matplotlib/__init__.py:870, in _rc_params_in_file(fname, transform, fail_on_error)
 869 rc_temp = {}
--> 870 with _open_file_or_url(fname) as fd:
 871 try:
File ~/miniforge3/envs/myenv/lib/python3.9/contextlib.py:119, in _GeneratorContextManager.__enter__(self)
 118 try:
--> 119 return next(self.gen)
 120 except StopIteration:
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/matplotlib/__init__.py:847, in _open_file_or_url(fname)
 846 fname = os.path.expanduser(fname)
--> 847 with open(fname, encoding='utf-8') as f:
 848 yield f
FileNotFoundError: [Errno 2] No such file or directory: 'seaborn'
The above exception was the direct cause of the following exception:
OSError Traceback (most recent call last)
Cell In[1], line 14
 12 from IPython.display import display
 13 from pylab import plt, mpl
---> 14 plt.style.use('seaborn')
 15 mpl.rcParams['font.family'] = 'serif'
 17 # Where to save the figures and data files
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/matplotlib/style/core.py:139, in use(style)
 137 style = _rc_params_in_file(style)
 138 except OSError as err:
--> 139 raise OSError(
 140 f"{style!r} is not a valid package style, path of style "
 141 f"file, URL of style file, or library style name (library "
 142 f"styles are listed in `style.available`)") from err
 143 filtered = {}
 144 for k in style: # don't trigger RcParams.__getitem__('backend')
OSError: 'seaborn' is not a valid package style, path of style file, URL of style file, or library style name (library styles are listed in `style.available`)
OSError: 'seaborn' is not a valid package style, path of style file, URL of style file, or library style name (library styles are listed in `style.available`)
@@ -0,0 +1,35 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
a += b
a -= b
a*= b
a /=b
------------------
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[27], line 1
----> 1 a += b
 2 a -= b
 3 a*= b
NameError: name 'b' is not defined
NameError: name 'b' is not defined
@@ -0,0 +1,39 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 730, in _async_poll_for_reply
msg = await ensure_async(self.kc.shell_channel.get_msg(timeout=new_timeout))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 96, in ensure_async
result = await obj
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_client/channels.py", line 315, in get_msg
raise Empty
_queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 949, in async_execute_cell
exec_reply = await self.task_poll_for_reply
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 754, in _async_poll_for_reply
await self._async_handle_timeout(timeout, cell)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 801, in _async_handle_timeout
raise CellTimeoutError.error_from_timeout_and_cell(
nbclient.exceptions.CellTimeoutError: A cell timed out while it was being executed, after 30 seconds.
The message was: Cell execution timed out.
Here is a preview of the cell contents:
-------------------
['eta_vals = np.logspace(-5, 1, 7)', 'lmbd_vals = np.logspace(-5, 1, 7)', '# store the models for later use', 'DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)', '']
...
[' ', ' print("Learning rate = ", eta)', ' print("Lambda = ", lmbd)', ' print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))', ' print()']
-------------------
@@ -0,0 +1,39 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 730, in _async_poll_for_reply
msg = await ensure_async(self.kc.shell_channel.get_msg(timeout=new_timeout))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 96, in ensure_async
result = await obj
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_client/channels.py", line 315, in get_msg
raise Empty
_queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 949, in async_execute_cell
exec_reply = await self.task_poll_for_reply
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 754, in _async_poll_for_reply
await self._async_handle_timeout(timeout, cell)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 801, in _async_handle_timeout
raise CellTimeoutError.error_from_timeout_and_cell(
nbclient.exceptions.CellTimeoutError: A cell timed out while it was being executed, after 30 seconds.
The message was: Cell execution timed out.
Here is a preview of the cell contents:
-------------------
['eta_vals = np.logspace(-5, 1, 7)', 'lmbd_vals = np.logspace(-5, 1, 7)', '# store the models for later use', 'DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)', '']
...
[' ', ' print("Learning rate = ", eta)', ' print("Lambda = ", lmbd)', ' print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))', ' print()']
-------------------
@@ -0,0 +1,39 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 730, in _async_poll_for_reply
msg = await ensure_async(self.kc.shell_channel.get_msg(timeout=new_timeout))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 96, in ensure_async
result = await obj
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_client/channels.py", line 315, in get_msg
raise Empty
_queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 949, in async_execute_cell
exec_reply = await self.task_poll_for_reply
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 754, in _async_poll_for_reply
await self._async_handle_timeout(timeout, cell)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 801, in _async_handle_timeout
raise CellTimeoutError.error_from_timeout_and_cell(
nbclient.exceptions.CellTimeoutError: A cell timed out while it was being executed, after 30 seconds.
The message was: Cell execution timed out.
Here is a preview of the cell contents:
-------------------
['eta_vals = np.logspace(-5, 1, 7)', 'lmbd_vals = np.logspace(-5, 1, 7)', '# store the models for later use', 'DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)', '']
...
[' ', ' print("Learning rate = ", eta)', ' print("Lambda = ", lmbd)', ' print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict))', ' print()']
-------------------
@@ -0,0 +1,70 @@
Traceback (most recent call last):
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/jupyter_cache/executors/utils.py", line 51, in single_nb_execution
executenb(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 1204, in execute
return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 84, in wrapped
return just_run(coro(*args, **kwargs))
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/util.py", line 62, in just_run
return loop.run_until_complete(coro)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/asyncio/base_events.py", line 647, in run_until_complete
return future.result()
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 663, in async_execute
await self.async_execute_cell(
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 965, in async_execute_cell
await self._check_raise_for_error(cell, cell_index, exec_reply)
File "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/nbclient/client.py", line 862, in _check_raise_for_error
raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
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)
------------------
---------------------------------------------------------------------------
NotFoundError Traceback (most recent call last)
Cell In[3], line 1
----> 1 from tensorflow.keras import datasets, layers, models
 2 from tensorflow.keras.layers import Input
 3 from tensorflow.keras.models import Sequential #This allows appending layers to existing models
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/__init__.py:440
 438 _plugin_dir = _os.path.join(_s, 'tensorflow-plugins')
 439 if _os.path.exists(_plugin_dir):
--> 440 _ll.load_library(_plugin_dir)
 441 # Load Pluggable Device Library
 442 _ll.load_pluggable_device_library(_plugin_dir)
File ~/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow/python/framework/load_library.py:151, in load_library(library_location)
 148 kernel_libraries = [library_location]
 150 for lib in kernel_libraries:
--> 151 py_tf.TF_LoadLibrary(lib)
 153 else:
 154 raise OSError(
 155 errno.ENOENT,
 156 'The file or folder to load kernel libraries from does not exist.',
 157 library_location)
NotFoundError: dlopen(/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '_TF_GetInputPropertiesList'
NotFoundError: dlopen(/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/tensorflow-plugins/libmetal_plugin.dylib, 0x0006): symbol not found in flat namespace '_TF_GetInputPropertiesList'
+1
View File
@@ -62,6 +62,7 @@ parts:
- file: week43.ipynb
- file: exercisesweek43.ipynb
- file: week44.ipynb
- file: week45.ipynb
- caption: Projects
numbered: false
chapters:
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

File diff suppressed because it is too large Load Diff