0% found this document useful (0 votes)
2 views10 pages

ML practical Lovepreet 6-10

The document outlines practical implementations of various machine learning algorithms including Naïve Bayes, K-Nearest Neighbors (K-NN), and Support Vector Machines (SVM). It provides a brief description of each algorithm, their applications, and includes Python code for simulating these algorithms using a dataset. The practical outcomes highlight the effectiveness and ease of use of these algorithms in classification and prediction tasks.
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)
2 views10 pages

ML practical Lovepreet 6-10

The document outlines practical implementations of various machine learning algorithms including Naïve Bayes, K-Nearest Neighbors (K-NN), and Support Vector Machines (SVM). It provides a brief description of each algorithm, their applications, and includes Python code for simulating these algorithms using a dataset. The practical outcomes highlight the effectiveness and ease of use of these algorithms in classification and prediction tasks.
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/ 10

Practical no.

Aim: Simulate Naïve Bayes algorithm


Naïve Bayes algorithm is a supervised learning algorithm, which is based on Bayes theorem and used for
solving classification problems. It is mainly used in text classification that includes a high-dimensional
training dataset. Naïve Bayes Classifier is one of the simple and most effective Classification algorithms
which helps in building the fast machine learning models that can make quick predictions.
It is a probabilistic classifier, which means it predicts on the basis of the probability of an object. Some
popular examples of Naïve Bayes Algorithm are spam filtration, Sentimental analysis, and classifying
articles. Working of Naïve Bayes' Classifier:
Working of Naïve Bayes' Classifier can be understood with the help of the below example: Suppose we have
a dataset of weather conditions and corresponding target variable "Play". So using this dataset we need to
decide that whether we should play or not on a particular day according to the weather conditions. So to
solve this problem, we need to follow the below steps: Convert the given dataset into frequency tables.
Generate Likelihood table by finding the probabilities of given features. Now, use Bayes theorem to
calculate the posterior probability.

Python Code:
# Naive Bayes
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd

# Importing the dataset dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:, [2,


3]].values y = dataset.iloc[:, -1].values

# Splitting the dataset into the Training set and Test set from sklearn.model_selection import
train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state
= 0)

# Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train


= sc.fit_transform(X_train) X_test = sc.transform(X_test)

# Training the Naive Bayes model on the Training set from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB() classifier.fit(X_train, y_train)

# Predicting the Test set results y_pred = classifier.predict(X_test)

# Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm =


confusion_matrix(y_test, y_pred) print(cm)

# Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set =
X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:,
0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Naive Bayes (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend()
plt.show()

Lovepreet Kaur 2220974 A2


# Visualising the Test set results from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:,
0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in
enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Naive Bayes (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary')
plt.legend() plt.show()

Output:

Practical Outcomes:

The rain forest algorithm is a machine learning algorithm that is easy to use and flexible. It uses ensemble
learning, which enables organizations to solve regression and classification problems. This is an ideal
algorithm for developers because it solves the problem of overfitting of datasets. It’s a very resourceful tool
for making accurate predictions needed in strategic decision making in organizations.

Applications of Naïve Bayes


It is used for Credit Scoring.
It is used in medical data classification.
It can be used in real-time predictions because Naïve Bayes Classifier is an
eager learner. It is used in Text classification such as Spam filtering and
Sentiment analysis.

Lovepreet Kaur 2220974 A2


Practical no. 7

Aim: Implement K-Nearest Neighbors (K-NN), k-Means


K-Nearest Neighbour is one of the simplest Machine Learning algorithms based on Supervised Learning
technique. K-NN algorithm assumes the similarity between the new case/data and available cases and put
the new case into the category that is most similar to the available categories. K-NN algorithm stores all the
available data and classifies a new data point based on the similarity. This means when new data appears
then it can be easily classified into a well suite category by using K- NN algorithm. K-NN algorithm can be
used for Regression as well as for Classification but mostly it is used for the Classification problems. K-NN
is a non-parametric algorithm, which means it does not make any assumption on underlying data. It is also
called a lazy learner algorithm because it does not learn from the training set immediately instead it stores
the dataset and at the time of classification, it performs an action on the dataset. KNN algorithm at the
training phase just stores the dataset and when it gets new data, then it classifies that data into a category
that is much similar to the new data. Example: Suppose, we have an image of a creature that looks similar
to cat and dog, but we want to know either it is a cat or dog. So for this identification, we can use the KNN
algorithm, as it works on a similarity measure. Our KNN model will find the similar features of the new
data set to the cats and dogs images and based on the most similar features it will put it in either cat or dog
category.
How does K-NN work?
The K-NN working can be explained on the basis of the below algorithm:
Step-1: Select the number K of the neighbors
Step-2: Calculate the Euclidean distance of K number of neighbors
Step-3: Take the K nearest neighbors as per the calculated Euclidean distance.
Step-4: Among these k neighbors, count the number of the data points in each category.
Step-5: Assign the new data points to that category for which the number of the neighbor is maximum.
Step-6: Our model is ready.

Python Code:
# K-Nearest Neighbors (K-NN) # Importing the libraries import numpy as np import
matplotlib.pyplot as plt import pandas as pd

# Importing the dataset dataset = pd.read_csv('Social_Network_Ads.csv')

X = dataset.iloc[:, [2, 3]].values


y = dataset.iloc[:, -1].values

# Splitting the dataset into the Training set and Test set from sklearn.model_selection import
train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)

# Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train =


sc.fit_transform(X_train) X_test = sc.transform(X_test)

# Training the K-NN model on the Training set from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2) classifier.fit(X_train,
y_train)

# Predicting the Test set results y_pred = classifier.predict(X_test)

# Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm =


confusion_matrix(y_test, y_pred) print(cm)

Lovepreet Kaur 2220974 A2


# Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set =
X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() +
1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)

plt.title('K-NN (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()


# Visualising the Test set results from matplotlib.colors import ListedColormap X_set, y_set = X_test,
y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step =
0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('K-NN (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()

Output

Practical Outcomes:
Since the KNN algorithm requires no training before making predictions, new data can be added
seamlessly, which will not impact the accuracy of the algorithm. KNN is very easy to implement. There
are only two parameters required to implement KNN—the value of K and the distance function (e.g.
Euclidean, Manhattan, etc.

Applications:
KNN is widely used in almost all industries, such as healthcare, financial services, eCommerce, political
campaigns, etc. Healthcare companies use the KNN algorithm to determine if a patient is susceptible to
certain diseases and conditions. Financial institutions predict credit card ratings or qualify loan
applications and the likelihood of default with the help of the KNN algorithm. Political analysts classify
potential voters into separate classes based on whom they are likely to vote for.

Lovepreet Kaur 2220974 A2


Practical no. 8

Aim: Deploy Support Vector Machine, Apriori algorithm


Support Vector Machines are a type of supervised machine learning algorithm that provides analysis of
data for classification and regression analysis. While they can be used for regression, SVM is mostly used
for classification. We carry out plotting in the n-dimensional space. Value of each feature is also the value
of the specific coordinate. Then, we find the ideal hyperplane that differentiates between the two classes.
These support vectors are the coordinate representations of individual observation. It is a frontier method
for segregating the two classes.

Python Code:
# Support Vector Machine (SVM)

# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd

# Importing the dataset dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:, [2, 3]].values y


= dataset.iloc[:, -1].values

# Splitting the dataset into the Training set and Test set from sklearn.model_selection import
train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
# Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train =
sc.fit_transform(X_train) X_test = sc.transform(X_test)

# Training the SVM model on the Training set from sklearn.svm import SVC classifier = SVC(kernel =
'linear', random_state = 0) classifier.fit(X_train, y_train)

# Predicting the Test set results y_pred = classifier.predict(X_test)

# Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm =


confusion_matrix(y_test, y_pred) print(cm)

# Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set =
X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1,
step = 0.01),

np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))


plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),

alpha = 0.75, cmap = ListedColormap(('red', 'green')))


plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)):

plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],


c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('SVM (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()
# Visualising the Test set results from matplotlib.colors import ListedColormap X_set, y_set = X_test,
y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step =
0.01),

np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))


plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),

alpha = 0.75, cmap = ListedColormap(('red', 'green')))


plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)):

plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],


c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('SVM (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary')

Lovepreet Kaur 2220974 A2


plt.legend() plt.show()

Output:

Practical Outcomes:
It works really well with a clear margin of separation It is effective in high dimensional spaces. It is effective in
cases where the number of dimensions is greater than the number of samples. It uses a subset of training points
in the decision function (called support vectors), so it is also memory efficient.

Applications:
Face detection – SVMc classify parts of the image as a face and non-face and create a square boundary around
the face. Text and hypertext categorization – SVMs allow Text and hypertext categorization for both inductive
and transductive models. They use training data to classify documents into different categories. It categorizes
on the basis of the score generated and then compares with the threshold value. Classification of images – Use
of SVMs provides better search accuracy for image classification. It provides better accuracy in comparison to
the traditional query-based searching techniques. Bioinformatics – It includes protein classification and cancer
classification. We use SVM for identifying the classification of genes, patients on the basis of genes and other
biological problems. Protein fold and remote homology detection – Apply SVM algorithms for protein remote
homology detection. Handwriting recognition – We use SVMs to recognize handwritten characters used
widely. Generalized predictive control(GPC) – Use SVM based GPC to control chaotic dynamics with useful
parameters.

Lovepreet Kaur 2220974 A2


Practical no. 9

Aim: Simulate Artificial Neural Network


Neural networks (NN), also called artificial neural networks (ANN) are a subset of learning algorithms
within the machine learning field that are loosely based on the concept of biological neural networks.
Andrey Bulezyuk, who is a German-based machine learning specialist with more than five years of
experience, says that “neural networks are revolutionizing machine learning because they are capable of
efficiently modeling sophisticated abstractions across an extensive range of disciplines and industries.”
An input layer that receives data and pass it on A hidden layer An output layer Weights between the layers
A deliberate activation function for every hidden layer. In this simple neural network Python tutorial, we’ll
employ the Sigmoid activation function. There are several types of neural networks. In this project, we are
going to create the feed-forward or perception neural networks. This type of ANN relays data directly from
the front to the back.
Training the feed-forward neurons often need back-propagation, which provides the network with
corresponding set of inputs and outputs. When the input data is transmitted into the neuron, it is processed,
and an output is generated.
Summarizing an Artificial Neural Network:
Take inputs Add bias (if required) Assign random weights to input features Run the code for training. Find
the error in prediction. Update the weight by gradient descent algorithm. Repeat the training phase with
updated weights.
Basically, an ANN comprises of the following components:
Make predictions.

Python Code:
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd

# Importing the dataset dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:, [2, 3]].values y


= dataset.iloc[:, -1].values

# Splitting the dataset into the Training set and Test set from sklearn.model_selection import
train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)

# Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train =


sc.fit_transform(X_train) X_test = sc.transform(X_test)

# Training the SVM model on the Training set from sklearn.svm import SVC classifier = SVC(kernel =
'linear', random_state = 0) classifier.fit(X_train, y_train)

# Predicting the Test set results y_pred = classifier.predict(X_test)

# Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm =


confusion_matrix(y_test, y_pred) print(cm)

# Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set =
X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1,
step = 0.01),

np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))


plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),

alpha = 0.75, cmap = ListedColormap(('red', 'green')))


plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)):

plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],


c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('SVM (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()

Lovepreet Kaur 2220974 A2


from joblib.numpy_pickle_utils import xrange from numpy import *
class NeuralNet(object):
def __init__(self):
# Generate random numbers random.seed(1)
# Assign random weights to a 3 x 1 matrix, self.synaptic_weights = 2 * random.random((3, 1)) - 1
# The Sigmoid function
def __sigmoid(self, x):
return 1 / (1 + exp(-x))
# The derivative of the Sigmoid function.
# This is the gradient of the Sigmoid curve. def __sigmoid_derivative(self, x):
return x * (1 - x)
# Train the neural network and adjust the weights each time. def train(self, inputs, outputs,
training_iterations):
for iteration in xrange(training_iterations):
# Pass the training set through the network. output = self.learn(inputs)
# Calculate the error error = outputs - output
# Adjust the weights by a factor
factor = dot(inputs.T, error * self.__sigmoid_derivative(output))
self.synaptic_weights += factor
# The neural network thinks.
def learn(self, inputs):
return self.__sigmoid(dot(inputs, self.synaptic_weights))
if __name__ == "__main__":
# Initialize neural_network = NeuralNet()
# The training set. inputs = array([[0, 1, 1], [1, 0, 0], [1, 0, 1]]) outputs = array([[1, 0, 1]]).T
# Train the neural network neural_network.train(inputs, outputs, 10000)
# Test the neural network with a test example. print(neural_network.learn(array([1, 0, 1])))

Output:

Practical Outcomes:
Know the main provisions neuromathematics; Know the main types of neural networks; Know and apply the
methods of training neural networks; Know the application of artificial neural networks; To be able to formalize
the problem, to solve it by using a neural network
Applications of ANN a. Classification of data
b. Anomaly detection:
Given the details about transactions of a person, it can say that whether the transaction is fraud or not.
c. Speech recognition:
We can train our neural network to recognize speech patterns. Example: Siri, Alexa, Google assistant.
d. Audio generation:
Given the inputs as audio files, it can generate new music based on various factors like genre, singer, and others.
e. Time series analysis:
A well trained neural network can predict the stock price.
f. Spell checking:
We can train a neural network that detects misspelled spellings and can also suggest a similar meaning for words.
Example: Grammarly
g. Character recognition:
A well trained neural network can detect handwritten characters.
h. Machine translation:
We can develop a neural network that translates one language into another language.
i. Image processing:
We can train a neural network to process an image and extract pieces of information from it.
:
Based on a set of data, our trained neural network predicts whether it is a dog or a cat?

Lovepreet Kaur 2220974 A2


Practical no. 10

Aim: Implement the Genetic Algorithm code


One of the advanced algorithms in the field of computer science is Genetic Algorithm inspired by the
Human genetic process of passing genes from one generation to another. It is generally used for
optimization purpose and is heuristic in nature and can be used at various places. For eg – solving np
problem, game theory, code-
Here are quick steps for how the genetic algorithm works:

Initial Population
Fitness function
Selection
population
Cross-over
Mutation
Repeat step 2-5 again for each generation
– Initialize the population randomly based on the data.
– Find the fitness value of the each of the chromosomes(a chromosome is a set of parameters which define a
proposed solution to the problem that the genetic algorithm is trying to solve)
– Select the best fitted chromosomes as parents to pass the genes for the next generation and create a new
– Create new set of chromosome by combining the parents and add them to new population set
– Perform mutation which alters one or more gene values in a chromosome in the new population set
generated.
Mutation helps in getting more diverse opportunity. Obtained population will be used in the next
generation

Python Code:
import numpy as np import pandas as pd import random import matplotlib.pyplot from sklearn.datasets
import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.linear_model
import LogisticRegression from sklearn.metrics import accuracy_score #import the breast cancer dataset
from sklearn.datasets import load_breast_cancer cancer=load_breast_cancer() df =
pd.DataFrame(cancer['data'],columns=cancer['feature_names']) label=cancer["target"] #splitting the model
into training and testing set X_train, X_test, y_train, y_test = train_test_split(df,
#training a logistics regression model logmodel = LogisticRegression() logmodel.fit(X_train,y_train)
predictions = logmodel.predict(X_test) print("Accuracy = "+ str(accuracy_score(y_test,predictions)))
#defining various steps required for the genetic algorithm def initilization_of_population(size,n_feat):
chromosome = np.ones(n_feat,dtype=np.bool) chromosome[:int(0.3*n_feat)]=False
np.random.shuffle(chromosome) population.append(chromosome)
for chromosome in population:
logmodel.fit(X_train.iloc[:,chromosome],y_train) predictions =
logmodel.predict(X_test.iloc[:,chromosome]) scores.append(accuracy_score(y_test,predictions))
scores, population = np.array(scores), np.array(population) inds = np.argsort(scores) return
list(scores[inds][::-1]), list(population[inds,:][::-1])
def selection(pop_after_fit,n_parents):
population_nextgen.append(pop_after_fit[i])
return population_nextgen
def crossover(pop_after_sel):
population_nextgen=pop_after_sel for i in range(len(pop_after_sel)):
child=pop_after_sel[i] child[3:7]=pop_after_sel[(i+1)%len(pop_after_sel)][3:7]
population_nextgen.append(child)
return population_nextgen
def mutation(pop_after_cross,mutation_rate):
population_nextgen = [] for i in range(0,len(pop_after_cross)):
chromosome = pop_after_cross[i] for j in range(len(chromosome)):

Lovepreet Kaur 2220974 A2


f random.random() < mutation_rate:
chromosome[j]= not chromosome[j]
population_nextgen.append(chromosome)
#print(population_nextgen) return population_nextgen
def generations(size,n_feat,n_parents,mutation_rate,n_gen,X_train,

X_test, y_train, y_test):


best_chromo= [] best_score= [] population_nextgen=initilization_of_population(size,n_feat) for i in
range(n_gen):
scores, pop_after_fit = fitness_score(population_nextgen) print(scores[:2]) pop_after_sel =
selection(pop_after_fit,n_parents) pop_after_cross = crossover(pop_after_sel) population_nextgen =
mutation(pop_after_cross,mutation_rate) best_chromo.append(pop_after_fit[0])
best_score.append(scores[0])
return best_chromo,best_score

Output:

Practical Outcomes:
The use of genetic algorithm in the field of robotics is quite big. Actually, genetic algorithm is being used to
create learning robots which will behave as a human and will do tasks like cooking our meal, do our laundry etc
Traffic and Shipment Routing (Travelling Salesman Problem)
This is a famous problem and has been efficiently adopted by many sales-based companies as it is time saving
and economical. This is also achieved using genetic algorithm.
Genetic Algorithms might be costly in computational terms since the evaluation of each individual requires the
training of a model. These algorithms can take a long time to converge since they have a stochastic nature
Genetic algorithms work on the Chromosome, which is an encoded version of potential solutions’ parameters,
rather the parameters themselves. Genetic algorithms use fitness score, which is obtained from objective
functions, without other derivative or auxiliary information
Applications: Robotics

Engineering Design
Engineering design has relied heavily on computer modeling and simulation to make design cycle process fast
and economical. Genetic algorithm has been used to optimize and provide a robust solution

Lovepreet Kaur 2220974 A2

You might also like