ANN Programs
ANN Programs
Write a Python program to plot a few activation functions that are being used in neural networks.
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
y = sigmoid(x)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('sigmoid(x)')
plt.show()
Practical no 2
—----------------------------------------------------------------------------------------------------------------------
--------
import numpy as np
return output
threshold = 1
return output
print(and_not(0, 0))
print(and_not(1, 0))
print(and_not(0, 1))
print(and_not(1, 1))
—----------------------------------------------------------------------------------------------------------------------------------
import numpy as np
# Define the input and output vectors for the AND NOT function
X = np.array([[0, 0],
[1, 0],
[0, 1]])
Y = np.array([1, 0, 1])
b = 0.0
lr = 0.1
n_iter = 10
def step(x):
for i in range(n_iter):
for j in range(len(X)):
x = X[j]
y = Y[j]
z = np.dot(x, w) + b
o = step(z)
dw = lr * (y - o) * x
db = lr * (y - o)
w += dw
b += db
test_z = np.dot(test_x, w) + b
test_o = step(test_z)
Write a Python Program using Perceptron Neural Network to recognize even and odd numbers.
Given numbers are in ASCII from 0 to 9
import numpy as np
training_data = [
input = np.array(data['input'])
label = data['label']
With a suitable example demonstrate the perceptron learning law with its decision regions using
python. Give the output in graphical form.
Ref:
https://pyimagesearch.com/2021/05/06/implementing-the-perceptron-neural-network-with-py
thon/
import numpy as np
np.random.seed(0)
X = np.random.randn(100, 2)
clf = Perceptron(random_state=0)
clf.fit(X, y)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.show()
—---------------------------------------------------------------------------------------------------------------------------------
import numpy as np
w = np.zeros(X.shape[1])
b=0
for _ in range(6):
for i in range(X.shape[0]):
y_pred = np.sign(np.dot(X[i], w) + b)
if y_pred != Y[i]:
b += 0.3 * Y[i]
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
Z = np.sign(np.dot(np.c_[xx.ravel(), yy.ravel()], w) + b)
Z = Z.reshape(xx.shape)
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()
Practical No- 5
Implement Artificial Neural Network training process in Python by using Forward Propagation,
Back Propagation
Program 1 :
class NeuralNet(object):
def __init__(self):
random.seed(1)
return 1 / (1 + exp(-x))
return x * (1 - x)
# Train the neural network and adjust the weights each time.
output = self.learn(inputs)
if __name__ == "__main__":
# Initialize
neural_network = NeuralNet()
print(neural_network.learn(array([1, 0, 1])))
********************************************************************************************
Program 2:
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
input_size = 2
hidden_size = 2
output_size = 1
learning_rate = 0.1
num_epochs = 10000
for i in range(num_epochs):
# Forward propagation
hidden_layer_activation = sigmoid(hidden_layer_input)
output_layer_activation = sigmoid(output_layer_input)
error = y - output_layer_activation
hidden_layer_activation = sigmoid(hidden_layer_input)
output_layer_activation = sigmoid(output_layer_input)
print(output_layer_activation)
Practical No. 6
Create a Neural network architecture from scratch in Python and use it to do multi-class
classification on any data
import numpy as np
import pandas as pd
'thal', 'heart_disease']
heart_df.fillna(heart_df.mean(), inplace=True)
X = heart_df.drop(columns=['heart_disease'])
# Replace target class with 0 and 1
y_label = heart_df['heart_disease'].values.reshape(-1, 1)
sc = StandardScaler()
Xtrain = sc.fit_transform(Xtrain)
Xtest = sc.transform(Xtest)
print(heart_df.dtypes)
class NeuralNet:
self.params = {}
self.learning_rate = learning_rate
self.iterations = iterations
self.loss = []
self.layers = layers
self.X = None
self.y = None
def init_weights(self):
np.random.seed(1)
return 1 / (1 + np.exp(-Z))
sig = self.sigmoid(Z)
return np.maximum(0, Z)
epsilon = 1e-10
return loss
def forward_propagation(self):
Z1 = self.X.dot(self.params['W1']) + self.params['b1']
A1 = self.relu(Z1)
Z2 = A1.dot(self.params['W2']) + self.params['b2']
yhat = self.sigmoid(Z2)
self.params['Z1'] = Z1
self.params['Z2'] = Z2
self.params['A1'] = A1
m = self.X.shape[0]
y_inv = 1 - self.y
yhat_inv = 1 - yhat
dl_wrt_sig = self.dSigmoid(self.params['Z2'])
dl_wrt_w2 = self.params['A1'].T.dot(dl_wrt_z2)
dl_wrt_w1 = self.X.T.dot(dl_wrt_z1)
self.X = X
self.y = y
self.init_weights()
for i in range(self.iterations):
self.back_propagation(yhat)
self.loss.append(loss)
if i % 100 == 0 and i != 0:
Z1 = X.dot(self.params['W1']) + self.params['b1']
A1 = self.relu(Z1)
Z2 = A1.dot(self.params['W2']) + self.params['b2']
yhat = self.sigmoid(Z2)
return np.round(yhat)
def plot_loss(self):
plt.plot(self.loss)
plt.xlabel("Iterations")
plt.ylabel("Loss")
plt.show()
nn.fit(Xtrain, ytrain)
y_pred = nn.predict(Xtest)
nn.plot_loss()
Practical No. 7
import numpy as np
weights = np.random.uniform(size=(input_dim,))
weights /= np.sum(weights)
return weights
while True:
return weights
else:
weights[np.argmax(input_pattern)] += 1
weights /= np.sum(weights)
matched_category = None
matched_category = category
break
if matched_category is None:
categories.append(matched_category)
matched_category["patterns"].append(pattern)
return categories
# Example usage
vigilance = 0.5
print(f"Category {i+1}:")
print("Patterns:")
print("Weights:")
print(category["weights"])
print()