Ai Lab Code
Ai Lab Code
def perceptron(and_input):
a = [0, 0, 1, 1]
b = [0, 1, 0, 1]
y = [0, 0, 0, 1]
bias = -1
w = [0.6, 0.8, 1.5]
threshold = 0.5
learning_rate = 0.5
i = 0
print("Perceptron Training")
print("####################")
print("________________")
while i<4:
summation = (a[i]*w[0] + b[i]*w[1]) + bias*w[2]
target_output = activation(summation, threshold)
print("Input : " + str(a[i]) + " , "+str(b[i]))
print("Weights : " + str(w[0]) + " , "+str(w[1]))
print("Summation : " + str(summation))
print("Actual output : " + str(y[i]) + " Predicted Output␣
↪"+str(target_output))
if(target_output != y[i]):
print(".........\nUpdating Weights")
w[0] = w[0] + learning_rate*(y[i] - target_output)*a[i]
w[1] = w[1] + learning_rate*(y[i] - target_output)*b[i]
print("Updated Weights: ", str(w[0]) + ','+str(w[1]))
i = -1
1
print("\nWeights Updated Training Again : ")
print("##################################")
i = i+1
#print("---------------")
summation = and_input[0]*w[0] + and_input[1]*w[1] + bias*w[2]
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 8))
x_min, x_max = -0.5, 1.5
y_min, y_max = -0.5, 1.5
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min,␣
↪y_max, 100))
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap='Oranges')
for i in range(len(y)):
if y[i] == 0:
plt.scatter(a[i], b[i], color='red', marker='x', label='Class 0')
else:
plt.scatter(a[i], b[i], color='green', marker='o', label='Class 1')
#plt.scatter(a,b, c=y, cmap = "Blues_r", label = "a & b values")
plt.title("AND GATE ")
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
#plt.xticks(())
#plt.yticks(())
#plt.grid()
plt.legend()
plt.show()
return activation(summation, threshold)
and_input = [1,1]
output = perceptron(and_input)
print("AND Gate Output for "+ str(and_input) + " : " + str(output))
Perceptron Training
####################
________________
Input : 0 , 0
Weights : 0.6 , 0.8
Summation : -1.5
Actual output : 0 Predicted Output 0
Input : 0 , 1
Weights : 0.6 , 0.8
Summation : -0.7
Actual output : 0 Predicted Output 0
Input : 1 , 0
2
Weights : 0.6 , 0.8
Summation : -0.9
Actual output : 0 Predicted Output 0
Input : 1 , 1
Weights : 0.6 , 0.8
Summation : -0.10000000000000009
Actual output : 1 Predicted Output 0
…
Updating Weights
Updated Weights: 1.1,1.3
3
AND Gate Output for [1, 1] : 1
4
while i<4:
summation = (a[i]*w[0] + b[i]*w[1]) + bias*w[2]
target_output = activation(summation, threshold)
print("Input : " + str(a[i]) + " , "+str(b[i]))
print("Weights : " + str(w[0]) + " , "+str(w[1]))
print("Summation : " + str(summation))
print("Actual output : " + str(y[i]) + " Predicted Output␣
↪"+str(target_output))
if(target_output != y[i]):
print(".........\nUpdating Weights")
w[0] = w[0] + learning_rate*(y[i] - target_output)*a[i]
w[1] = w[1] + learning_rate*(y[i] - target_output)*b[i]
print("Updated Weights: ", str(w[0]) + ','+str(w[1]))
i = -1
print("\nWeights Updated Training Again : ")
print("##################################")
i = i+1
print("---------------")
summation = and_input[0]*w[0] + and_input[1]*w[1] + bias*w[2]
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 8))
x_min, x_max = -0.5,1.5
y_min, y_max = -0.5,1.5
xx,yy = np.meshgrid(np.linspace(x_min, x_max,100),np.linspace(y_min,␣
↪y_max,100))
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap='Oranges')
for i in range(len(y)):
if y[i] == 0:
plt.scatter(a[i], b[i], color='red', marker='x', label='Class 0')
else:
plt.scatter(a[i], b[i], color='green', marker='o', label='Class 1')
5
and_input = [1,1]
print("OR Gate Output for "+ str(and_input) + " : " +␣
↪str(perceptron(and_input)))
Perceptron Training
####################
________________
Input : 0 , 0
Weights : 0.6 , 0.6
Summation : -1.0
Actual output : 0 Predicted Output 0
---------------
Input : 0 , 1
Weights : 0.6 , 0.6
Summation : -0.4
Actual output : 1 Predicted Output 0
…
Updating Weights
Updated Weights: 0.6,1.1
6
Actual output : 0 Predicted Output 0
---------------
Input : 0 , 1
Weights : 1.1 , 1.1
Summation : 0.10000000000000009
Actual output : 1 Predicted Output 1
---------------
Input : 1 , 0
Weights : 1.1 , 1.1
Summation : 0.10000000000000009
Actual output : 1 Predicted Output 1
---------------
Input : 1 , 1
Weights : 1.1 , 1.1
Summation : 1.2000000000000002
Actual output : 1 Predicted Output 1
---------------
7
3 Multi Layer Perceptron for X-OR
[3]: import numpy as np
import matplotlib.pyplot as plt
# Define the initial weights and biases for the hidden layer
hidden_layer_weights = np.random.normal(size=(2, hidden_layer_size))
hidden_layer_bias = np.zeros(hidden_layer_size)
# Define the initial weights and bias for the output layer
output_layer_weights = np.random.normal(size=(hidden_layer_size, 1))
output_layer_bias = 0.0
output_layer_activation = sigmoid(np.dot(hidden_layer_activation,␣
↪output_layer_weights) + output_layer_bias)
# Backpropagation
output_layer_error = y.reshape(-1, 1) - output_layer_activation
output_layer_delta = output_layer_error *␣
↪sigmoid_derivative(output_layer_activation)
hidden_layer_error = output_layer_delta.dot(output_layer_weights.T)
8
hidden_layer_delta = hidden_layer_error *␣
↪sigmoid_derivative(hidden_layer_activation)
# Predictions
t= np.array([[1,1]])
hidden_layer_activation = sigmoid(np.dot(t, hidden_layer_weights) +␣
↪hidden_layer_bias)
output_layer_activation = sigmoid(np.dot(hidden_layer_activation,␣
↪output_layer_weights) + output_layer_bias)
a2 = np.squeeze(output_layer_activation)
if a2>=0.5:
print("For input", t[0], "output is 1")
else:
print("For input", t[0], "output is 0")
#print(output_layer_activation)
for i in range(X1.shape[0]):
for j in range(X1.shape[1]):
hidden_layer_activation = sigmoid(np.dot(np.array([X1[i,j], X2[i,j]]),␣
↪hidden_layer_weights)+ hidden_layer_bias)
output_layer_activation = sigmoid(np.dot(hidden_layer_activation,␣
↪output_layer_weights)+ output_layer_bias)
Z[i,j] = output_layer_activation[0]
plt.contourf(X1, X2, Z, cmap='coolwarm', alpha=0.5)
#plt.colorbar()
# Plot the input data
for i in range(len(X)):
if y[i] == 0:
9
plt.scatter(X[i][0], X[i][1], color='red', marker='x', label='Class 0')
else:
plt.scatter(X[i][0], X[i][1], color='green', marker='o', label='Class␣
↪1')
plt.title('XOR')
plt.legend()
plt.show()
[16]: A B C Output
0 1 1 5 S
10
1 0 1 1 L
2 1 2 5 S
3 0 2 1 L
4 0 1 1 M
[17]: count_1 = 0
count_2 = 0
count_3 = 0
for i in range(len(data)):
if(data["Output"][i]=="S"):
count_1 = count_1+1
elif(data["Output"][i]=="M"):
count_2 = count_2 +1
else:
count_3 = count_3 +1
Total S : 10
Total M : 12
Total L : 8
Total Data : 30
Parent Entropy : 1.5655962303576019
11
for i in range(len(c_data)):
if(c_data[x][i]==1):
child1.append(c_data["Output"][i])
else:
child2.append(c_data["Output"][i])
#print(len(child1), len(child2))
#child = pd.DataFrame(list(zip(child1, child2)),columns =['child1',␣
↪'child2'])
def count_data(data):
count_1 = 0
count_2 = 0
count_3 = 0
for i in range(len(data)):
if(data[i]=="S"):
count_1 = count_1+1
elif(data[i]=="M"):
count_2 = count_2 +1
else:
count_3 = count_3 +1
return count_1, count_2, count_3
return avg_entropy
I_Gain= "{:.2f}".format(parent_Entropy-avg_entropy)
return I_Gain
12
Information Gain for attribute B : 0.06
df = pandas.read_excel("DataSet.xlsx")
X = df[features]
y = df['Output']
dtree = DecisionTreeClassifier(max_depth = 3)
dtree = dtree.fit(X, y)
plt.figure(figsize=(20, 10))
tree.plot_tree(dtree, feature_names=features,filled = True)
#plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
13
[ ]:
14