Institute of Engineering and Technology Davv, Indore: Lab Assingment On
Institute of Engineering and Technology Davv, Indore: Lab Assingment On
Institute of Engineering and Technology Davv, Indore: Lab Assingment On
DAVV , INDORE
(2018-2019)
LAB ASSINGMENT ON
SUBMITTED TO SUBMITTED BY
Professor
1
Assignment-1
Q) Explain types of neural networks.
1. Feedforward Neural Network – Artificial Neuron
This is one of the simplest types of artificial neural networks. In a feedforward neural network, the
data passes through the different input nodes till it reaches the output node.
In other words, data moves in only one direction from the first tier onwards until it reaches the
output node. This is also known as a front propagated wave which is usually achieved by using a
classifying activation function.
Unlike in more complex types of neural networks, there is no backpropagation and data moves in
one direction only. A feedforward neural network may have a single layer or it may have hidden
layers. In a feedforward neural network, the sum of the products of the inputs and their weights
are calculated. This is then fed to the output. Here is an example of a single layer feedforward
neural network.
Feedforward neural networks are used in technologies like face recognition and computer vision.
This is because the target classes in these applications are hard to classify.
A simple feedforward neural network is equipped to deal with data which contains a lot of noise.
Feedforward neural networks are also relatively simple to maintain.
2
Radial Basis Function Neural Network
The radial basis function neural network is applied extensively in power restoration systems. In
recent decades, power systems have become bigger and more complex.
This increases the risk of a blackout. This neural network is used in the power restoration systems
in order to restore power in the shortest possible time.
3. Multilayer Perceptron
A multilayer perceptron has three or more layers. It is used to classify data that cannot be separated
linearly. It is a type of artificial neural network that is fully connected. This is because every single
node in a layer is connected to each node in the following layer. A multilayer perceptron uses a
nonlinear activation function (mainly hyperbolic tangent or logistic function). Here’s what a
multilayer perceptron looks like. This type of neural network is applied extensively in speech
recognition and machine translation technologies.
Multilayer Perceptron
3
4. Convolutional Neural Network
A convolutional neural network(CNN) uses a variation of the multilayer perceptrons. A CNN
contains one or more than one convolutional layers. These layers can either be completely
interconnected or pooled.
Before passing the result to the next layer, the convolutional layer uses a convolutional operation
on the input. Due to this convolutional operation, the network can be much deeper but with much
fewer parameters.
Due to this ability, convolutional neural networks show very effective results in image and video
recognition, natural language processing, and recommender systems.
Convolutional neural networks also show great results in semantic parsing and paraphrase
detection. They are also applied in signal processing and image classification.
CNNs are also being used in image analysis and recognition in agriculture where weather features
are extracted from satellites like LSAT to predict the growth and yield of a piece of land. Here’s
an image of what a Convolutional Neural Network looks like.
4
Recurrent Neural Network(RNN) – Long Short Term Memory
5
Assignment-2
Q)Write a code to implement neural networks in python. Also explain the
dataset you choose for training and testing.
import numpy as np # linear algebra
import pandas as pd
# load iris database
data = pd.read_csv("C:/Users/Rishi/Desktop/test/ptest/iris.csv")
data.sample(n=5)
data.describe()
df_norm = data[['SepalLengthCm', 'SepalWidthCm',
'PetalLengthCm', 'PetalWidthCm']].apply(lambda x: (x - x.min())
/ (x.max() - x.min()))
df_norm.sample(n=5)
df_norm.describe()
target = data[['Species']]
target.sample(n=5)
df = pd.concat([df_norm, target], axis=1)
df.sample(n=5)
train_test_per = 90/100.0
df['train'] = np.random.rand(len(df)) < train_test_per
df.sample(n=5)
train = df[df.train == 1]
train = train.drop('train', axis=1).sample(frac=1)
train.sample(n=5)
test = df[df.train == 0]
test = test.drop('train', axis=1)
test.sample(n=5)
X = train.values[:,:4]
#X[:5]
targets = [[1,0,0],[0,1,0],[0,0,1]]
y = np.array([targets[int(x)] for x in train.values[:,4:5]])
#y[:5]
num_inputs = len(X[0])
hidden_layer_neurons = 5
np.random.seed(4)
w1 = 2*np.random.random((num_inputs, hidden_layer_neurons)) - 1
num_outputs = len(y[0])
w2 = 2*np.random.random((hidden_layer_neurons, num_outputs)) - 1
learning_rate = 0.2 # slowly update the network
for epoch in range(50000):
l1 = 1/(1 + np.exp(-(np.dot(X, w1)))) # sigmoid function
l2 = 1/(1 + np.exp(-(np.dot(l1, w2))))
er = (abs(y - l2)).mean()
6
l2_delta = (y - l2)*(l2 * (1-l2))
l1_delta = l2_delta.dot(w2.T) * (l1 * (1-l1))
w2 += l1.T.dot(l2_delta) * learning_rate
w1 += X.T.dot(l1_delta) * learning_rate
print('Error:', er)
X = test.values[:,:4]
y = np.array([targets[int(x)] for x in test.values[:,4:5]])
l1 = 1/(1 + np.exp(-(np.dot(X, w1))))
l2 = 1/(1 + np.exp(-(np.dot(l1, w2))))
np.round(l2,3)
yp = np.argmax(l2, axis=1) # prediction
res = yp == np.argmax(y, axis=1)
correct = np.sum(res)/len(res)
testres = test[['Species']].replace([0,1,2], ['Iris-
setosa','Iris-versicolor','Iris-virginica'])
testres['Prediction'] = yp
testres['Prediction'] = testres['Prediction'].replace([0,1,2],
['Iris-setosa','Iris-versicolor','Iris-virginica'])
print(testres)
print('Correct:',sum(res),'/',len(res), ':', (correct*100),'%')
Output:
Error: 0.04100736886034659
Species Prediction
10 Iris-setosa Iris-setosa
40 Iris-setosa Iris-setosa
49 Iris-setosa Iris-setosa
71 Iris-versicolor Iris-versicolor
83 Iris-versicolor Iris-virginica
90 Iris-versicolor Iris-versicolor
96 Iris-versicolor Iris-versicolor
97 Iris-versicolor Iris-versicolor
104 Iris-virginica Iris-virginica
108 Iris-virginica Iris-virginica
127 Iris-virginica Iris-virginica
138 Iris-virginica Iris-virginica
140 Iris-virginica Iris-virginica
149 Iris-virginica Iris-virginica
Correct: 13 / 14 : 92.85714285714286 %
7
Assignment-3
Q) Explain fuzzy systems and its operators.
Fuzzy logic is a superset of conventional(Boolean) logic that has been extended to handle the
concept of partial truth- truth values between "completely true" and "completely false". As its
name suggests, it is the logic underlying modes of reasoning which are approximate rather than
exact. The importance of fuzzy logic derives from the fact that most modes of human reasoning
and especially common sense reasoning are approximate in nature.
The essential characteristics of fuzzy logic as founded by Zader Lotfi are as follows.
In fuzzy logic, exact reasoning is viewed as a limiting case of approximate reasoning.
In fuzzy logic everything is a matter of degree.
Any logical system can be fuzzified
In fuzzy logic, knowledge is interpreted as a collection of elastic or, equivalently , fuzzy
constraint on a collection of variables
Inference is viewed as a process of propagation of elastic constraints.
The third statement hence, define Boolean logic as a subset of Fuzzy logic.
Fuzzy Sets
Fuzzy Set Theory was formalised by Professor Lofti Zadeh at the University of California in
1965. What Zadeh proposed is very much a paradigm shift that first gained acceptance in the Far
East and its successful application has ensured its adoption around the world.
Let's talk about people and "youthness". In this case the set S (the universe of discourse) is the
set of people. A fuzzy subset YOUNG is also defined, which answers the question "to what
degree is person x young?" To each person in the universe of discourse, we have to assign a
degree of membership in the fuzzy subset YOUNG. The easiest way to do this is with a
membership function based on the person's age.
8
Given this definition, here are some example values:
Person Age degree of youth
--------------------------------------
Johan 10 1.00
Edwin 21 0.90
Parthiban 25 0.50
Arosha 26 0.40
Chin Wei 28 0.20
Rajkumar 83 0.00
So given this definition, we'd say that the degree of truth of the statement "Parthiban is YOUNG"
is 0.50.
Note: Membership functions almost never have as simple a shape as age(x). They will at least
tend to be triangles pointing up, and they can be much more complex than that. Furthermore,
membership functions so far is discussed as if they always are based on a single criterion, but
this isn't always the case, although it is the most common case. One could, for example, want to
have the membership function for YOUNG depend on both a person's age and their height
(Arosha's short for his age). This is perfectly legitimate, and occasionally used in practice. It's
referred to as a two-dimensional membership function. It's also possible to have even more
criteria, or to have the membership function depend on elements from two completely different
universes of discourse.
Fuzzy Set Operations:.
Union
The membership function of the Union of two fuzzy sets A and B with membership
functions and respectively is defined as the maximum of the two individual
membership functions. This is called the maximum criterion.
The Union operation in Fuzzy set theory is the equivalent of the OR operation in Boolean
algebra.
9
Intersection
The membership function of the Intersection of two fuzzy sets A and B with membership
functions and respectively is defined as the minimum of the two individual
membership functions. This is called the minimum criterion.
The Intersection operation in Fuzzy set theory is the equivalent of the AND operation in
Boolean algebra.
Complement
The membership function of the Complement of a Fuzzy set A with membership function
is defined as the negation of the specified membership function. This is caleed the
negation criterion.
10
The Complement operation in Fuzzy set theory is the equivalent of the NOT operation in
Boolean algebra.
The following rules which are common in classical set theory also apply to Fuzzy set theory.
De Morgans law
,
Associativity
Commutativity
Distributivity
11
Assignment-4
Q) Write a code to illustrate various fuzzy logic operations.
def fuzzyunion(x,y,z):
c={}
for a in z:
if a in x.keys():
if a in y.keys():
c[a]=max(x[a],y[a])
else:
c[a]=x[a]
else:
c[a]=y[a]
return c
def fuzzyintersect(x,y,z):
c={}
for a in z:
if a in x.keys():
if a in y.keys():
c[a]=min(x[a],y[a])
return c
if len(m1)!=len(one):
print("wrong data")
exit(-1)
if len(m2)!=len(two):
12
print("wrong data")
exit(-1)
print(one)
print(m1)
print(two)
print(m2)
d1=dict(zip(one,m1))
d2=dict(zip(two,m2))
one.extend(two)
s=set(one)
print("Union of given fuzzy sets is:")
u=fuzzyunion(d1,d2,s)
print(u)
Output
Enter the first fuzzy set as list of numbers separated by space:
123
Enter the first fuzzy set's elements characteristic function values as list of numbers separated by
space:
0.1 0.3 0.2
Enter the second fuzzy set as list of numbers separated by space:
2435
Enter the second fuzzy set's elements characteristic function values as list of numbers separated
by space:
0.4 0.7 0.02 0.01
['1', '2', '3']
[0.1, 0.3, 0.2]
['2', '4', '3', '5']
[0.4, 0.7, 0.02, 0.01]
Union of given fuzzy sets is:
{'3': 0.2, '5': 0.01, '4': 0.7, '2': 0.4, '1': 0.1}
Intersection of given fuzzy sets is:
{'3': 0.02, '2': 0.3}
13
14