Introduction To Artificial Intelligence..
Introduction To Artificial Intelligence..
Mining
Ms. Mayuri Shelke
Introduction to Artificial
Intelligence
WHAT IS A.I.?
DISADVANTAGES OF A.I.
• High cost
• Decrease in demand for human labour
• The storage and access are not as effective as human brains
Applications of A.I.…
Gaming Entertainmen
t
Social Education
Media
Healthcare
GENERAL A.I. AGENTS WITH PLATFORMS
WHAT WILL THE NEXT DECADE BRING?
• Improved speech, voice ,image, video recognition will change the way interact
with our devices
• More and more systems will run autonomously in a point.
What is logic programming?
• Object Oriented: This groups the code within the program in such a way that each object is
responsible for itself.
• Procedural: This groups the code into functions and each function is responsible for a
particular series of steps.
• Symbolic: This uses a particular style of syntax and grammar through which the program can
modify its own components by treating them as plain data.
• Logic: This views computation as automatic reasoning over a database of knowledge consisting
of facts and rules.
Understanding the building blocks of logic programming.
13
How to Solve ?
14
How to Solve ?
15
How to Solve?
• In the case where a logic program and a goal don't contain any variables,
the solver comes up with a tree that constitutes the search space for
solving the problem and getting to the goal.
• One of the most important things about logic programming is how we
treat the rules. Rules can be viewed as logical statements.
E.g. : 1)Horror movies, English => James Wan
•It can be read as the implication If you like Horror movies in English, then you
would like movies made by James Wan.
2)Grandfather(X,Y):- Father(X,Z),Parent(Z,Y)
• This implies that for X to be the grandfather of Y, Z should be a parent of Y
and X should be father of Z.
•This construction is used in various forms throughout logic programming to
solve various types of problems.
16
Installing Python Packages
You can also install the packages directly into Pycharm IDE as shown
below.
Installing Python Packages
List of primes in the list: (3, 11, 13, 17, 19, 23, 29)
List of first 7 prime numbers: (2, 3, 5, 7, 11, 13, 17)
Validating Primes
• Primes are important because the security of many encryption
algorithms are based on the fact that it is very fast to multiply two large
prime numbers and get the result, while it is extremely computer-
intensive to do the reverse.
• This is also the reason why prime numbers are used to calculate hash-
codes – because they are co-prime with the maximum number of
integers. A correct and fast algorithm to check whether a number is
prime has been seeked for a long time by mathematicians and
computer scientists.
What is Heuristic?
● A rule of thumb that helps us narrow down the search by eliminating the options that are
obviously wrong.
● Rational/Problem-Solving Agent
● Search Space
● Start State and Goal Test
● Search Tree
● Completeness
● Optimality
● Complexity
Informed Search
• Search algorithms like DFS or BFS explore all the search space systematically by
keeping one or more paths in memory and by recording which alternatives have
been explored.
• When a goal is found, the path to that goal constitutes a solution.
• There are some problems where path is irrevelevant eg:8 Queens
• Local search algorithms can be very helpful if we are interested in the solution
state but not in the path to that goal.
• Local search algorithm is a heuristic search algorithm.
Optimization
ADVANTAGES:
• They use very little memory
• They can find reasonable solutions in large or infinite (continuous) state
spaces.
EXAMPLES :
• Hill-climbing
• Simulated annealing
• Tabu Search
Hill Climbing Algorithm
• Hill climbing is a popular local search technique, it is also called greedy local search.
• It is a loop that continuously moves towards the increasing value and terminates when
peak is reached. This value can be objective function/ heuristic function .
• The heuristic function measures the difference between the current state and the goal.
• When we start, it checks if the state is the final goal. If it is, then it stops. If not, then it
selects an update and generates a new state. If it's closer to the goal than the current
state, then it makes that the current state. If not, it ignores it and continues the process
until it checks all possible updates. It basically climbs the hill until it reaches the summit
• It does not look ahead of its immediate neighbours.
• LOCAL MAXIMA
• PLATEAUS
• DIAGONAL RIDGES
SIMULATED ANNEALING
WHAT IS ANNEALING?
• Annealing is a thermal process for obtaining low energy states
of a solid in a heat bath.
• The process contains two steps:
• Increase the temperature of the heat bath to a maximum value at
which the solid melts.
• Decrease carefully the temperature of the heat bath until the particles
arrange themselves in the ground state of the solid. Ground state is a
minimum energy state of the solid
• The rate of cooling is important because it directly impacts the
final result.
Simulated Annealing
P= 1/(1+exp(-ΔE/T))
Disadvantages
• In practice, the convergence of the algorithm depends of
the cooling schedule.Can take a long time to run if the
schedule is very long
• There are a lot of tuneable parameters in this algorithm
Applications
• Facilities layout
1. Construct a string using greedy search
47
Algorithm
● To recreate the input string based on the alphabets.
48
Applications
49
2. Solving a problem with constraints
51
3.Solving the region coloring problem
Definition
We have a few regions in the diagram that
are labeled with names. Our aim being
coloring with four colors so that no
adjacent regions have the same color.
(Constraint Satisfaction Framework)
52
Algorithm
● Define the list of possible colors
● Define the constraints by their adjacent nodes
● Use the variables to initialize the objects
● Thereafter solve the problem using the backtracking
solution
53
54
Applications
● Making Timetables
● Map Coloring
● Checking Bipartite graphs
● Mobile radio frequency assignment
55
Introduction
1 2 3 1 2 3
4 6 4 5 6
7 5 8 7 8
• Example: 7 5 8 7 8
Right Dow
Up
n
1 2 3 2 3 1 2 3
4 6 1 4 6 7 4 6
7 5 8 7 5 8 5 8
Up Right
Dow
n
1 3 1 2 3 1 2 3
4 2 6 4 5 6 4 6
7 5 8 7 8 7 5 8
Informed Search
• This method uses Heuristic Search to find the solution as early as possible.
• Heuristic search uses Heuristic value for optimizing the search.
• A* algorithm is an example of Informed search algorithms which can be used to
solve 8-puzzle problem.
A* Algorithm
• A* algorithm is one of the best and popular technique used in path finding and
graph traversal.
• It starts with the initial node and chooses the next node based on its f-score.
f(n) = h(n) + g(n)
where h(n) 🡪 no. of misplaced tiles
g(n) 🡪 no. of nodes traversed from start node to current node.
A* Algorithm
1 2 3 1 2 3
Initial State
4 6 4 5 6 Final State
g=0, h=3,
• Example: 7 5 8
f=0+3=3
7 8
g=1, h=4, g=1, h=2, g=1, h=4,
f=4+1=5 f=2+1=3 f=4+1=5
2 3 1 2 3 1 2 3
1 4 6 4 6 7 4 6
7 5 8 7 5 8 5 8
Optimization is the process of making something better. In any process, we have a set of
inputs and a set of outputs as shown in the following figure.
The aim of optimization is to find that point or set of points in the search space.
Understanding evolutionary and genetic algorithms
GAs were developed by John Holland and his students and colleagues
at the University of Michigan, most notably David E. Goldberg and has
since been tried on various optimization problems with a high degree
of success.
Genetic Algorithms are sufficiently randomized in nature, but they
perform much better than random local search (in which we just try
various random solutions, keeping track of the best so far), as they
exploit historical information as well.
Genetic Algorithm
Apply crossover and mutation operators on the parents to generate new off-springs.
And finally these off-springs replace the existing individuals in the population and
the process repeats. In this way genetic algorithms actually try to mimic the human
evolution to some extent.
Flow chart of the
working of Genetic
Algorithm
Framework of Genetic
Algorithms:
A generalized pseudo-code for a GA is explained in the following
program −
GA()
initialize population
find fitness of population
● Vehicle routing problems − With multiple soft time windows, multiple depots
and a heterogeneous fleet.
● Robot Trajectory Generation − GAs have been used to plan the path which a
robot arm takes by moving from one point to another.
● Traveling salesman problem and its applications − GAs have been used to
solve the TSP, which is a well-known combinatorial problem using novel
crossover and packing strategies.
Genetic Algorithm
• A genetic algorithm is an evolutionary algorithm where
we use a heuristic to find a string of bits that solves a
problem.
• We continuously iterate on a population to arrive at a
solution.
• We do this by generating new populations containing
stronger individuals.
• We apply probabilistic operators such as selection,
crossover, and mutation in order to generate the next
generation of individuals.
• The individuals are basically strings, where every string
is the encoded version of a potential solution.
Deap Library (Distributed Evolutionary
Algorithms in Python)
⮚ Distributed Evolutionary Algorithms in Python (DEAP)
is an evolutionary computation framework for
rapid prototyping and testing of ideas.
⮚ It incorporates the data structures and tools required to
implement most common evolutionary computation
techniques such as genetic algorithm, genetic
programming, evolution strategies etc.
⮚ Installation through command prompt:
$ pip3 install deap
$ python3
>>> import deap
One Max Problem using Deap library
❑ Create a new python file and import the following
import random from deap
import base, creator, tools
❑ Let's say we want to generate a bit pattern of length 75, and
we want it to contain 45 ones. We need to define an
evaluation function that can be used to target this objective:
# Evaluation function
def eval_func(individual):
target_sum = 45
return len(individual) - abs(sum(individual) -
target_sum)
Creating toolbox
⮚ We now need to define a function to create the toolbox.
Let's define a creator object for the fitness function and to keep track of the individuals.
The Fitness class used here is an abstract class and it needs the weights attribute to be
defined.
⮚ We are building a maximizing fitness using positive weights:
# Create the toolbox with the right parameters
def create_toolbox(num_bits):
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
⮚ The first line creates a single objective maximizing fitness named FitnessMax.
⮚ The second line deals with producing the individual.
⮚ In a given process, the first individual that is created is a list of floats. In order to
produce this individual, we must create an Individual class using the creator.
toolbox.register("evaluate", eval_func)
toolbox.register("mate", tools.cxTwoPoint)
return toolbox
Implementation of All the Concepts
if __name__ == "__main__":
# Define the number of bits
num_bits = 75 parameters
# Create a toolbox using the above parameter num_bits = 75
toolbox = create_toolbox(num_bits) Population size= 500
# Seed the random number generator No of generations= 60
random.seed(7)
Max. no. of ones= 45
# Create an initial population of 500 individuals
population = toolbox.population(n=500)
# Define probabilities of crossing and mutating
probab_crossing, probab_mutating = 0.5, 0.2
# Define the number of generations
num_generations = 60
# Evaluate all the individuals in the population using the fitness functions:
print('\nStarting the evolution process’)
# Evaluate the entire population
fitnesses = list(map(toolbox.evaluate, population))
for ind, fit in zip(population, fitnesses):
ind.fitness.values = fit
print('\nEvaluated', len(population), 'individuals’)
# Iterate through generations
for g in range(num_generations):
print("\n===== Generation", g)
# Select the next generation individuals
offspring = toolbox.select(population, len(population))
# Clone the selected individuals
offspring = list(map(toolbox.clone, offspring))
# Apply crossover and mutation on the offspring
for child1, child2 in zip(offspring[::2], offspring[1::2]):
# Cross two individuals
if random.random() < probab_crossing:
toolbox.mate(child1, child2)
# "Forget" the fitness values of the children
del child1.fitness.values
del child2.fitness.values
# Apply mutation
for mutant in offspring:
# Mutate an individual
if random.random() < probab_mutating:
toolbox.mutate(mutant)
del mutant.fitness.values
# Evaluate the individuals with an invalid fitness
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
print('Evaluated', len(invalid_ind), 'individuals’)
# The population is entirely replaced by the offspring
population[:] = offspring
Print the stats for the current generation to see how it's progressing:
# Gather all the fitnesses in one list and print the stats
fits = [ind.fitness.values[0] for ind in population]
length = len(population)
mean = sum(fits) / length
sum2 = sum(x*x for x in fits)
std = abs(sum2 / length - mean**2)**0.5
print('Min =', min(fits), ', Max =', max(fits))
print('Average =', round(mean, 2), ', Standard deviation =', round(std, 2))
print("\n==== End of evolution")
best_ind = tools.selBest(population, 1)[0]
print('\nBest individual:\n', best_ind)
print('\nNumber of ones:', sum(best_ind))
OUTPUT
1. Importing libraries
• One of the most important aspects of genetic algorithms is the randomness. In order to iterate, it
relies on the random sampling of individuals. This means that the process is non-deterministic.
So, if you run the same algorithm multiple times, you might end up with different solutions.
• A population is a set of individuals that are possible candidate solutions. In a genetic algorithm,
we do not maintain a single best solution at any given stage. It maintains a set of potential
solutions, one of which is the best.
Solving the symbol regression problem
• It is important to understand that genetic programming is not the same as genetic algorithms. Genetic
programming is a type of evolutionary algorithm in which the solutions occur in the form of computer
programs. Basically, the individuals in each generation would be computer programs and their fitness
level corresponds to their ability to solve problems. These programs are modified, at each iteration,
using a genetic algorithm. In essence, genetic programming is the application of a genetic algorithm.
• Coming to the symbol regression problem, we have a polynomial expression that needs to be
approximated here. It's a classic regression problem where we try to estimate the underlying
function. In this example, we will use the expression: f(x) = 2x^3 - 3x^2 + 4x - 1
The code here is a variant of the symbol regression problem given in the DEEP library. Create a new
Python file and import the following:
import operator
import math
import random
import numpy as np
from deap import algorithms, base, creator, tools, gp
Define the evaluation function that will be used for fitness calculation. We need to define a callable
function to run computations on the input individual:
# Define the evaluation function
def eval_func(individual, points):
# Transform the tree expression in a callable function
func = toolbox.compile(expr=individual)
Compute the mean squared error (MSE) between the function defined earlier and the original
expression:
# Evaluate the mean squared error
mse = ((func(x) - (2 * x**3 - 3 * x**2 - 4 * x + 1))**2 for x in points)
return math.fsum(mse) / len(points),
Define a function to create the toolbox. In order to create the toolbox here, we need to create a set of
primitives. These primitives are basically operators that will be used during the evolution. They serve as
building blocks for the individuals. We are going to use basic arithmetic functions as our primitives here:
We now need to declare an ephemeral constant. It is a special terminal type that does not have a fixed
value. When a given program appends such an ephemeral constant to the tree, the function gets
executed. The result is then inserted into the tree as a constant terminal. These constant terminals can
take the values -1, 0 or 1:
pset.addEphemeralConstant("rand101", lambda: random.randint(-1,1))
The default name for the arguments is ARGx. Let's rename it x. It's not exactly necessary, but it's a useful feature
that comes in handy:
pset.renameArguments(ARG0='x')
We need to define two object types - fitness and an individual. Let's do it using the creator:
creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", gp.PrimitiveTree,
fitness=creator.FitnessMin)
Create the toolbox and register the functions. The registration process is similar to previous sections:
toolbox = base.Toolbox()
toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=2)
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("compile", gp.compile, pset=pset)
toolbox.register("evaluate", eval_func, points=[x/10. for x in range(-10,10)])
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.register("mate", gp.cxOnePoint)
toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)
Define the initial population using the method available in the toolbox object. We will use 450individuals. The
user defines this number, so you should feel free to experiment with it. Also define the hall_of_fame objects:
population = toolbox.population(n=450)
hall_of_fame = tools.HallOfFame(1)
Register
mstats the stats using the objects defined
= tools.MultiStatistics(fitness=stats_fit, previously
size=stats_size)
mstats.register("avg", np.mean)
mstats.register("std", np.std)
mstats.register("min", np.min)
mstats.register("max", np.max)
probab_crossover = 0.4
probab_mutate = 0.2
num_generations = 60
Run the evolutionary algorithm using the above parameters:
population, log = algorithms.eaSimple(population, toolbox,
probab_crossover, probab_mutate, num_generations,
stats=mstats, halloffame=hall_of_fame, verbose=True)
If you run the code, you will see the following on your Terminal at the start of the evolution:
At the end, you will see the following:
GOAL
DEAP
• It stand for Distributed Evolutionary Algorithms In Python
• DEAP is a novel evolutionary computation framework for rapid
prototyping and testing of ideas.
• It seeks to make algorithms explicit and data structures
transparent. It works in perfect harmony with parallelization
mechanisms such as multiprocessing and SCOOP.
• DEAP is compatible with Python 2.7 and 3.4 or higher.
• Command to install : pip install deap
Introduction
Robot Controller
● One of the capabilities of robots is to move from one point to another which called is
autonomous navigation.
● Autonomous robot is a robot that can perform certain work independently without the
human help.
● There are many techniques that can be used to solve the problem of building Intelligent
Robot controller. Some of them include genetic algorithm (GA)
● To apply an algorithm to the robotic as a method of designing robotic controllers that
enable the robot to perform complex tasks and behaviors.
Introduction
Genetic algorithm
● Genetic Algorithm is a search-based optimization technique based on the principles
of Genetics and Natural Selection.
● It is frequently used to find optimal or near-optimal solutions to difficult problems
which otherwise would take a lifetime to solve.
● It is frequently used to solve optimization problems, in research, and in machine
learning.
● It uses techniques inspired by biological evolution such as inheritance, mutation,
selection, and crossover.
Steps
in
generic algorithm
Working of GA
When the termination condition is finally met, the algorithm will break out of the loop and typically return its finial search results back to
the user.
WORKING OF GA
• Selection : if the termination condition is not met, the population goes through a
selection stage in which individuals from the population are selected based on their
fitness score.
• Crossover : the next stage is to apply crossover and mutation to the selected
individuals.
• Mutation : at this point the new population goes back to the evaluation step and the
process starts again.