0% found this document useful (0 votes)
51 views19 pages

Pattern - Recognigation - Lab 3 Sept 23 - Practical File

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views19 pages

Pattern - Recognigation - Lab 3 Sept 23 - Practical File

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Lingaya’s Vidyapeeth, Faridabad

School of Computer Science & Information Technology

Nachauli, Old Faridabad-Jasana Road,


Faridabad 121002, Phone: (129) 2201008, 2201009
Web: www.lingayasuniversity.edu.in

Lab Manual
CS-455
Pattern Recognition Lab

Submitted to : Dr Manisha Vashisht (CSE Department)

NAME :

CLASS : B. TECH(7th SEMESTER)


ROLL NO. :
BRANCH : COMPUTER SCIENCE & ENGINEERING

Session 2024-20245
INDEX
S No. Program

1. Write a program to calculate distance between two places

2. Write a program for Classification of Iris Flower

3. Write a program for analysis of sensor input data

4. Automatic classification of sample data

5. Speech recognition and understanding

Write a program for image processing in different ways using


6. computer vision concept.

7. Program to analyze an image using Histogram

8. Implementation of Image Segmentation


Introduction
Most children under the age of five can recognize digits and letters – small characters, huge characters,
handwritten, machine printed or rotated – all of which are easily identified by the young. Humans can do the
best pattern recognition in most cases, but we don’t understand how they accomplish it.

The continuously increasing volume of data created makes human interpretation impractical, boosting the need
for machines to be able to spot patterns quickly and effectively. The capacity to automatically recognize
patterns and regularities in data has many uses, ranging from facial recognition software to tumor diagnosis.
Pattern recognition is one of the most popular applications of machine learning. There are patterns everywhere.
It permeates all aspects of our everyday existence. Everything, from the style and color of our clothing to the
use of clever voice assistants, includes a pattern.

What Does Pattern Recognition Mean?


Pattern Recognition is a way to find global or local trends in a pattern. A pattern is something that follows a
movement and has some form of regularity. It can be accomplished physically, mathematically, or using
algorithms.

A pattern in literature or film would be a description of a genre. If a user consistently chooses to watch dark
comedy on Netflix, the streaming service is unlikely to suggest any sad melodramas.

In the context of machine learning, “pattern recognition” refers to the use of complex algorithms to identify
patterns in the input data. Computer vision, voice recognition, face identification, etc., are only a few of the
many contemporary technical applications of pattern recognition.
How is Pattern Recognition Implemented?
The notion of learning is used to produce pattern recognition. Learning allows the system to be taught and
become more adaptive, resulting in more accurate outcomes. A portion of the dataset is used to train the
system, while the remainder is used to test it.

Source: geeksforgeeks
The training set comprises pictures or data that will be used to train or develop the model. Training rules
provide the criterion for output decisions.

Training algorithms are used to match a set of input data with an output choice. The algorithms and rules are
then used to help in training. The system generates results based on the information gathered from the data.

The testing set is used to validate the system’s accuracy. After the system has been trained, the testing data is
used to determine whether the accurate output is obtained. This data accounts for around 20% of the total data
in the system.

The Pattern Recognition method is divided into five stages. These stages can be described as follows:

• Phase 1 Sensing: The system turns the incoming data into similar data during this step.
• Phase 2 Segmentation: The perceived objects are isolated during this step.
• Phase 3 Feature extraction: In this step, the features or qualities of the objects are computed and sent for
further classification.
• Phase 4 Classification: The detected objects are classified or arranged in groups or cases at this step.
• Phase 5 Post-processing: Here, further considerations are done before concluding.
Different Types of Pattern Recognition
Image:

This form of pattern recognition identifies certain things portrayed in photographs. Image recognition is a
fundamental element of computer vision, which is a machine’s capacity to recognize pictures and execute
appropriate actions (e.g., a self-driving car slowing down after identifying a pedestrian ahead).

Image recognition is often used in operations like Face detection, visual search, and OCR (optical character
recognition).

Sound:

This pattern recognition approach is used to detect distinct sounds. After evaluating them, the system identifies
audio signals as belonging to a certain category. Here are some applications for sound pattern recognition:

• Surveillance alarm detection


Animal species identification
• melody recognition Voice:

This kind of pattern recognition examines human speech sounds to identify the speaker. Unlike voice
recognition, it does not include language processing and only detects personal features in a speaking pattern. It
is usually used for security purposes (personal identification).

Common applications involve- the Internet of things and mobile or web apps.
Speech: Speech recognition catches aspects of a language in the sound of a person speaking, similar to how
optical character recognition detects letters and words on an image. Popular applications for this technology
include- Voice-to-text converters, video auto-captioning, and virtual assistants.

Applications and Use Cases of Pattern


Recognition
• Seismic Analysis: studies how natural phenomena like earthquakes influence rocks, structures, and soils.
Pattern recognition is used in seismic events to detect and understand patterns.
• Trend Analysis: It aids in spotting trends in data so that suitable analysis may be performed. For example,
future sales may be forecasted by examining current

trends in a company’s or organization’s sales.


• Healthcare: It is used in the healthcare industry to enhance health services. Medical practitioners keep
patient data and use it for future studies. This process is used to identify objects or damage in human bodies
too.
• Fingerprint Recognition: This method recognizes fingerprints on computer and smartphone devices.
Modern smartphones have a fingerprint recognition function that allows you to unlock your phone after
authenticating your fingerprint.
• Computer Vision: The user interacts with the system by providing input as an image or video. The system
compares them to hundreds and millions of photographs recorded in its database to detect comparable
patterns. The fundamental characteristics are drawn using an algorithm designed primarily for grouping
similar appearing items and patterns. An example is cancer detection.

Advantages of Pattern Recognition


• Even the tiniest concealed or untraceable data may be identified and predicted using it.
• The challenge of biometric detection is solved through it.
• It is used to address categorization difficulties.
• It can help visually impaired blind persons recognize fabric patterns.
• In the medical sector, it is helpful for forensic investigation and DNA (deoxyribonucleic acid) sequencing.
• It can recognize and identify an object at different distances.
• Using learning approaches provides appropriate predictions.
• It not only aids in the prediction of unknown data but in the formulation of meaningful recommendations
too.
Disadvantages of Pattern Recognition
Several limitations can affect its performance and accuracy:

• Overfitting: occurs when a model is trained too well on the training data, resulting in poor generalization to
new, unseen data. This can be mitigated by using techniques like regularization and cross-validation.
• Underfitting: Underfitting occurs when a model is not complex enough to capture the underlying patterns
in the data. This can be mitigated by using more complex models or by increasing the amount of training
data.
• The Curse of Dimensionality: As the number of features in the data increases, the amount of data required
to model the patterns in the data accurately increases too. This can be mitigated by using dimensionality
reduction techniques.
• Data Bias: If the training data is not representative of the population, the model will not be able to generalize
well to new, unseen data. This can be mitigated by using techniques like oversampling or SMOTE.
• Noise and Outliers: Noise and outliers in the data can make it difficult for the model to identify the
underlying patterns. This can be mitigated by using robust estimation techniques or removing outliers from
the data.
• Nonlinearity: Some patterns in the data may not be linear, making it difficult for linear models to capture
the underlying patterns accurately. This can be mitigated using non-linear models like neural networks or
decision trees.
• Lack of Interpretability: Some models, like neural networks, can be difficult to interpret and understand,
making it hard to understand why a particular decision was made.
Experiment No: 1
AIM : Write a program to calculate distance between two places .

Explanation:
To calculate distance between two landmark/place we have to use python library geopy. geopy makes it
easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across
the globe. Geocoding is the process of transforming a description of a location—such as a pair of
coordinates, an address, or a name of a place—to a location on the earth's surface.

From geopy we import Nominatim and distance to locate and calculate the distance of two places.
Nominatim uses OpenStreetMap data to find locations on Earth by name and address (geocoding). It can
also do the reverse, find an address for any location on the planet. Now with the help of distance function
we calculate the distance between the places.

CODE:

#importing library Nominatim and distance

from geopy.geocoders import Nominatim


from geopy import distance

a=Nominatim(user_agent="Surya")

#Assigning two places


destination1="Noida"
destination2="Faridabad"
#obtaining coordinates like latitude and longitude
place1=a.geocode(destination1)
place2=a.geocode(destination2)
lat1,long1=(place1.latitude),(place1.longitude)
lat2,long2=(place2.latitude),(place2.longitude)
length1=(lat1,long1)
length2=(lat2,long2)
#Display the calculated distance
print("Distance Between "+destination1+" and "+destination2+" is :")
print(distance.distance(length1,length2))

OUTPUT

Distance Between Noida and Faridabad is :


18.633504903710797 km
Experiment 2

AIM: Write a program for Classification of Iris Flower

Explanation:
Iris flower has three species; setosa, versicolor, and virginica, which differs according to their
measurements.
Now assume that you have the measurements of the iris flowers according to their species, and here
your task
is to train a machine learning model that can learn from the measurements of the iris species and
classify them.

Data Sample
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 Iris-setosa
4.9 3 1.4 0.2 Iris-setosa
4.7 3.2 1.3 0.2 Iris-setosa
4.6 3.1 1.5 0.2 Iris-setosa
5 3.6 1.4 0.2 Iris-setosa
5.4 3.9 1.7 0.4 Iris-setosa
4.6 3.4 1.4 0.3 Iris-setosa
5 3.4 1.5 0.2 Iris-setosa
4.4 2.9 1.4 0.2 Iris-setosa

CODE
# Iris Flower Classification
# Import Packages
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

#Load the data


iris = pd.read_csv("IRIS.csv")

#have a look at the first five rows of this dataset:


print(iris.head())
#have a look at the descriptive statistics of this dataset:
print(iris.describe())

#The target labels of this dataset are present in the species column,have a look at
the target labels:
print("Target Labels", iris["Species"].unique())

#plot the data using a scatter plot which will plot the iris species according to the
sepal length and sepal width:
import plotly.express as px
fig = px.scatter(iris, x="Sepal.Width", y="Sepal.Length", color="Species")
fig.show()

#iris classification
#split the data into training and test sets, and use the KNN classification algorithm
to train the iris classification model:
x = iris.drop("Species", axis=1)
y = iris["Species"]
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2,
random_state=0)

from sklearn.neighbors import KNeighborsClassifier


knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x_train, y_train)

#Now input a set of measurements of the iris flower and use the model to predict
the iris species:
x_new = np.array([[5, 2.9, 1, 0.2,0.3]])
prediction = knn.predict(x_new)
print("Prediction: {}".format(prediction))
OUTPUT

Prediction: ['Iris-versicolor']
Experiment 3

AIM: Analysis of sensor input data

Computers obtain data by reading from the standard input, files, and sensors, then store it in the memory
for processing. Data processing could be online or offline, depending on the preferences of the user.
Data processing is the conversion of raw data to meaningful information. The aim is to break down the
data and represent it to the end user graphically.

How to record mobile sensor’s data recording mobile data:-

We have two schemes in which you can capture and process data. These schemes are to record sensor
data offline and record them online. At the same time, you can access the data and process it on the
local PC using Python or Matlab.

Reading data and processing it offline is easy as compared to online. This is because it needs to establish
a real-time communication link.

Various mobile sensor

The image above shows the sensors that are available to android mobile phones. These
sensors could detect the position, motion and even the environment on request. This assists
when using many applications such as cameras, games, e.t.c. The user can also record them to
use in the implementation of various applications such as:

Control robots and machines.


Identify metallic and non-metallic objects.
To study the vibration of a machine part.
To differentiate normal or faulty operation of machines based on their sound.
To study the movement of a machine part.
To control some activities based on mobile orientation e.t.c

Reading data and processing it offline is easy as compared to online. This is because it needs
to establish a real-time communication link. The steps of reading mobile sensor and online
processing is as shownbelow:

The steps that are used to record and process data offline is shown below:

.csv file format

You can open this data in a notepad or MS excel software. This format arranges data in
columns and rows. An example of data opened in a notepad and MS excel is shown below:
The data in the first column shows the time. The second column represented by wx is the x-
axis data. The third column represented by wy is the y-axis data, and finally, wz represents the
z-axis data.

The first row in the data represents the next row. When importing this data, we should consider
this line. It should be separated from the data during importation and processing.

Third-party androids Apps to record mobile sensor data

Let us look at the third party android App that can collect sensor data. To get this App,

Go to play store on your mobile phone.

Search for sensors data collector in the search tab.

The result here is more than one. Note that all these applications are good. We recommend
data collector or physics toolbox for this article. This is because their interfaces are easy to
use.

There are two categories of applications. The first category collects data and saves them as
a .csv file for offline processing, e.g. data collector. The second category collects data and
sends them to a given web for online processing.

Since we are to process our data offline, we will install the physics toolbox. Once

installation is complete, open the App.

How to use third party App

:
When you open physics toolbox, you get the interface shown below

You notice that when you shake your mobile phone, there is variation in the waveform as
shown below:
From the left menu, you can select available sensors on your phone.

For example, select the sensor if you want to record g-force data. You then click on
the + sign. Once you click it, there is a pop-up data is being recorded. You can do
this for the required time. Once you stop recording, a new window opens up that
allows one to save the data.

Once this is done, you get a prompt to share your


data through any application you wish or save it in the local storage. For our case,
we store it in the local storage. After saving, you can import it to your pc for
processing using a USB cable or any other preferred method. For our case, we use
the accelerometer sensor.
Code:
#import the necessary libraries

import numpy as np

import matplotlib.pyplot as plt

import csv

#After importing the libraries, read the .csv file:

with open('gforce.csv', 'r') as f:

data = list(csv.reader(f, delimiter=',')) #reading csv file

#convert data into float array:

data1 = np.array(data[1:], dtype=np.float64)

# Extracting data

time = data1[:, 0]

ax = data1[:, 1]

ay = data1[:, 2]

az = data1[:, 3]

aT = data1[:, 4]

# Plotting all the data in the same axis

plt.figure(figsize=(20, 10))

plt.plot(time, ax, time, ay, time, az, time, aT)

plt.title('Accelerometer data', fontsize=20)

plt.xlabel('Time', fontsize=20)

plt.ylabel('Acc.values', fontsize=20)

plt.show()
#separate plots using subplots

plt.figure(figsize=(20, 20))

plt.subplot(2, 2, 1)

plt.plot(ax, color='r')

plt.title('a[x]', fontsize=30)

plt.subplot(2, 2, 2)

plt.plot(ax, color='g')

plt.title('a[y]', fontsize=30)

plt.subplot(2, 2, 3)

plt.plot(ax, color='b')

plt.title('a[z]', fontsize=30)

plt.subplot(2, 2, 4)

plt.plot(ax, color='k')

plt.title('a[Total]', fontsize=30)

plt.show()
Output:-

You might also like