66 KiB
66 KiB
In [1]:
import autograd.numpy as np
from autograd import gradIn [2]:
np.random.seed(2024)
def ReLU(z):
return np.where(z > 0, z, 0)
x = np.random.randn(2) # network input
W1 = np.random.randn(4, 2) # first layer weightsIn [3]:
b1 = np.random.randn(4)In [4]:
z1 = W1 @ x + b1In [5]:
a1 = ReLU(z1)In [6]:
sol1 = np.array([0.60610368, 4.0076268, 0.0, 0.56469864])
print(np.allclose(a1, sol1))True
In [7]:
W2 = np.random.randn(8, 4)
b2 = np.random.randn(8)In [8]:
z2 = W2 @ a1
a2 = ReLU(z2)In [9]:
print(a2.shape == (8,))True
In [10]:
def create_layers(network_input_size, output_sizes):
layers = []
i_size = network_input_size
for output_size in output_sizes:
W = np.random.rand(output_size, i_size)
b = np.random.rand(output_size)
layers.append((W, b))
i_size = output_size
return layersIn [11]:
def feed_forward(layers, input):
a = input
for W, b in layers:
z = W @ a + b
a = ReLU(z)
return aIn [ ]:
In [12]:
def create_layers_4(network_input_size, output_sizes, activation_funcs):
layers = []
i_size = network_input_size
for output_size, activation in zip(output_sizes, activation_funcs):
W = np.random.rand(output_size, i_size)
b = np.random.rand(output_size)
layers.append((W, b, activation))
i_size = output_size
return layersIn [13]:
def feed_forward_4(layers, input):
a = input
for W, b, activation in layers:
z = W @ a + b
a = activation(z)
return aIn [14]:
from scipy.special import softmax
network_input_size = 4
output_sizes = [12, 10, 3]
activation_funcs = [ReLU, ReLU, softmax]
layers = create_layers_4(network_input_size, output_sizes, activation_funcs)
x = np.random.randn(network_input_size)
predict = feed_forward_4(layers, x)In [15]:
# Loading and plotting iris dataset
from sklearn import datasets
import matplotlib.pyplot as plt
iris = datasets.load_iris()
_, ax = plt.subplots()
scatter = ax.scatter(iris.data[:, 0], iris.data[:, 1], c=iris.target)
ax.set(xlabel=iris.feature_names[0], ylabel=iris.feature_names[1])
_ = ax.legend(
scatter.legend_elements()[0], iris.target_names, loc="lower right", title="Classes"
)In [16]:
# No need to change this cell! Just make sure it works!
for x in iris.data:
prediction = feed_forward_4(layers, x)