inteligencia artificial 3

53
Inteligência Artificial Professor: Francisco Nauber Bernardo Gois Inteligência Artificial - Aula 3 1

Upload: nauber-gois

Post on 22-Jan-2018

129 views

Category:

Technology


0 download

TRANSCRIPT

Inteligência ArtificialProfessor: Francisco Nauber Bernardo Gois

Inteligência Artificial - Aula 3

1

2

Grafos e digrafos

Um objeto combinatório conhecido como digrafo, ou grafo dirigido, ou ainda grafo orientado. Digrafos são importantes modelos para uma grande variedade de problemas de engenharia, computação, matemática, economia, biologia, etc.

3

Problemas de Busca

4

5

6

Busca de um caminho

7

Breadth First Search

8

package BreadthFirstSearch;

import java.util.ArrayList; import java.util.List;

public class Vertex {

private int data; private boolean visited; private List<Vertex> neighbourList; public Vertex(int data){ this.data=data; this.neighbourList = new ArrayList<>(); }

Vertice

9

public void addNeighbour(Vertex neighbour) { this.neighbourList.add(neighbour); } @Override public String toString() { return ""+this.data; }

Vertice

10

public class BreadthFirstSearch {

public void bfs(Vertex root){ Queue<Vertex> queue = new LinkedList<>(); root.setVisited(true); queue.add(root); while( !queue.isEmpty() ){ Vertex actualVertex = queue.remove(); System.out.print(actualVertex+" "); for( Vertex v : actualVertex.getNeighbourList() ){ if( !v.isVisited() ){ v.setVisited(true); queue.add(v); } } } } }

11

public class App {

public static void main(String[] args) { BreadthFirstSearch breadthFirstSearch = new BreadthFirstSearch(); Vertex vertex1 = new Vertex(1); Vertex vertex2 = new Vertex(2); Vertex vertex3 = new Vertex(3); Vertex vertex4 = new Vertex(4); Vertex vertex5 = new Vertex(5); vertex1.addNeighbour(vertex2); vertex1.addNeighbour(vertex4); vertex4.addNeighbour(vertex5); vertex2.addNeighbour(vertex3); breadthFirstSearch.bfs(vertex1);

} }

12

Deep First Search

13

private String name; private List<Vertex> neighbourList; private boolean visited; private Vertex predecessor; private int startingRank; private int finishingRank;

public Vertex(String name) { this.name = name; this.neighbourList = new ArrayList<>(); }

@Override public String toString() { return this.name+"- StartTime: "+startingRank+"- EndTime: "+finishingRank; }

14

public class DepthFirstSearch {

private List<Vertex> vertexList; private int time = 0; public DepthFirstSearch(List<Vertex> vertexList){ this.vertexList = vertexList; } public void runDfs(){ for( Vertex vertex : vertexList ){ if( !vertex.isVisited() ){ dfs(vertex); } } } public void printVertices(){ for(Vertex vertex : vertexList){ System.out.println(vertex+""); } } }

15

public void dfs(Vertex vertex){ System.out.print(vertex.getName()+"-"); time++; vertex.setStartingRank(time); for( Vertex v : vertex.getNeighbourList() ){ if( !v.isVisited() ){ v.setVisited(true); v.setPredecessor(vertex); dfs(v); } } time++; vertex.setFinishingRank(time); }

16

17

18

19

20

21

22

23

24

25

26

27

Algoritmo A* (Lê-se: A-estrela) é um algoritmo para Busca de Caminho. Ele busca o caminho em um grafo de um vértice inicial até um vértice final. Ele é a combinação de aproximações heurísticas como do algoritmo Best-first Search e da formalidade do Algoritmo de Dijkstra.

28

29

package AStarSearch;

public class Edge { public final double cost; public final Node targetNode;

public Edge(Node targetNode, double cost) { this.targetNode = targetNode; this.cost = cost; }

public double getCost() { return cost; }

public Node getTargetNode() { return targetNode; } }

30

package AStarSearch;

import java.util.ArrayList; import java.util.List;

public class Node implements Comparable<Node> {

private String value; private double gScore; private double fScore = 0; private double x; private double y; private List<Edge> adjacenciesList; private Node parentNode;

public Node(String value) { this.value = value; this.adjacenciesList = new ArrayList<>(); }

public double getgScore() { return gScore; } public void addNeighbour(Edge edge){ this.adjacenciesList.add(edge); }

31

@Override public int compareTo(Node otherNode) { return Double.compare(this.fScore, otherNode.getfScore()); }

32

package AStarSearch;

import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Set;

public class Algorithm {

public void aStarSearch(Node sourceNode, Node goalNode) {

Set<Node> exploredNodes = new HashSet<Node>();

PriorityQueue<Node> unexploredNodesQueue = new PriorityQueue<Node>(); sourceNode.setgScore(0); unexploredNodesQueue.add(sourceNode); boolean found = false;

while ( !unexploredNodesQueue.isEmpty() && !found ) {

Node currentNode = unexploredNodesQueue.poll(); exploredNodes.add(currentNode);

if (currentNode.getValue().equals(goalNode.getValue())) { found = true; }

33

for (Edge e : currentNode.getAdjacenciesList()) { Node childNode = e.getTargetNode(); double cost = e.getCost(); double tempGScore = currentNode.getgScore() + cost; double tempFScore = tempGScore + heuristic(childNode, goalNode);

if( exploredNodes.contains(childNode) && (tempFScore >= childNode.getfScore()) ) { continue; } else if ( !unexploredNodesQueue.contains(childNode) || (tempFScore < childNode.getfScore()) ) {

childNode.setParentNode(currentNode); childNode.setgScore(tempGScore); childNode.setfScore(tempFScore);

if (unexploredNodesQueue.contains(childNode)) { unexploredNodesQueue.remove(childNode); }

unexploredNodesQueue.add(childNode); } } } }

34

public List<Node> printPath(Node targetNode) {

List<Node> pathList = new ArrayList<Node>();

for (Node node = targetNode; node != null; node = node.getParentNode()) { pathList.add(node); }

Collections.reverse(pathList);

return pathList; } // Manhattan heuristic/distance !!! public double heuristic(Node node1, Node node2){ return Math.abs( node1.getX() - node2.getX() ) + Math.abs( node2.getY() - node2.getY() ); }

MetaHeurítica

Uma meta-heurística é um método heurístico para resolver de forma genérica problemas de otimização (normalmente da área de otimização combinatória).

Metaheurísticas são geralmente aplicadas a problemas que não se conhece algoritmo eficiente (veja problemas NP-completos).

35

36

37

38

39

40

package com.balazsholczer.max;

public class HillClimbing {

public static double f(double x){ return -(x-1)*(x-1)+2; } public static void main(String[] args) { double dx = 0.01; double actualPointX = -2; double max = f( actualPointX ); while( f(actualPointX+dx) >= max){ max = f(actualPointX+dx); System.out.println("X:"+actualPointX+" y:"+f(actualPointX)); actualPointX+=dx; } System.out.println("Min with hill climbing: "+max); } }

41

42

SIMULATED ANNEALING

43

A metaheurística usada é uma metáfora de um processo térmico, dito annealing ou recozimento, utilizado em metalurgia para obtenção de estados de baixa energia num sólido. O processo consiste de duas etapas: na primeira, a temperatura do sólido é aumentada para um valor próximo de 1100°C; na segunda, o resfriamento deve ser realizado lentamente até que o material se solidifique, sendo acompanhado e controlado esse ar re fec imento . Nesta segunda fase, executada lentamente, os átomos que compõem o material organizam-se numa estrutura uniforme com energia mínima. Isto resulta em que os átomos desse material ganhem energia para se movimentarem l ivremente e, ao arrefecer de forma controlada, dar-lhes uma melhor hipótese de se organizarem numa configuração com menor energia interna, para ter uma redução dos defeitos do material, como resultado prático.

44

package com.balazsholczer.sa;

public class Constants {

private Constants(){ } public static final double MIN_COORDINATE = -2; public static final double MAX_COORDINATE = 2; public static final double MIN_TEMPERATURE = 1; public static final double START_TEMPERATURE = 100; public static final double COOLING_RATE = 0.02; }

45

public class SimulatedAnnealing {

private Random randomGenerator; private double currentCoordinateX; private double nextCoordinateX; private double bestCoordinateX; public SimulatedAnnealing(){ this.randomGenerator = new Random(); }

46

public void findOptimum(){ double temperature = Constants.START_TEMPERATURE; while( temperature > Constants.MIN_TEMPERATURE ){ nextCoordinateX = getRandomX(); double currentEnergy = getEnergy(currentCoordinateX); double newEnergy = getEnergy(nextCoordinateX); if( acceptanceProbability(currentEnergy, newEnergy, temperature) > Math.random() ){ currentCoordinateX = nextCoordinateX; } if( f(currentCoordinateX) < f(bestCoordinateX)){ bestCoordinateX = currentCoordinateX; } temperature *= 1 - Constants.COOLING_RATE; } System.out.println("Global extremum is: x="+bestCoordinateX + "f(x) = " + f(bestCoordinateX)); }

47

private double getRandomX() { return randomGenerator.nextDouble()*(Constants.MAX_COORDINATE - Constants.MIN_COORDINATE) + Constants.MIN_COORDINATE; }

private double f(double x){ return (x-0.3)*(x-0.3)*(x-0.3)-5*x+x*x-2; } public double acceptanceProbability(double energy, double newEnergy, double temperature) { // If the new solution is better, accept it if (newEnergy < energy) { return 1.0; } // If the new solution is worse, calculate an acceptance probability // T is small: we accept worse solutions with lower probability !!! return Math.exp((energy - newEnergy) / temperature); }

48

package com.balazsholczer.sa;

public class App {

public static void main(String[] args) { SimulatedAnnealing annealing = new SimulatedAnnealing(); annealing.findOptimum(); } }

49

MetaHeuríticas Evolutivas ou Single Point

50

Algorítmos Genéticos

52

Suge

stão

53