Quiz Pertemuan 3 Dan Pertemuan 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Quiz Pertemuan 3 dan Pertemuan 4

# 1. Install Python
# 2. Install library python seperti pandas dll
# 3. Buat laporan terkait proses instalasi, hasil running coding, dan coding yang telah diberi comment
# 4. Latihan python dengan coding yang diberikan (Panduan Python, Struktur Data Pada Python, Pemrograman
Berorientasi Objek Dengan Python)
# 5. Buat laporan dengan latihan python ini
# 5. Jalankan coding pada UI python berikut ini dan lihat hasilnya (Breadth-First Search, Depth-First Search,
Uniform-Cost Search, Hill Climbing, Simulated Annealing, Genetic Algorithm)
# 6. Berikan comment dalam Bahasa Indonesia, dan buat laporan tentang running coding dan comment ini
#BREADTH-FIRST SEARCH

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = []
queue = []

def bfs(visited, graph, node):


visited.append(node)
queue.append(node)

while queue:
s = queue.pop(0)
print (s, end = " ")

for neighbour in graph[s]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
bfs(visited, graph, 'A')
# DEPTH-FIRST SEARCH

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = set()

def dfs(visited, graph, node):


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, 'A')
# UNIFORM-COST SEARCH

def uniform_cost_search(goal, start):


global graph, cost
answer = []
queue = []
for i in range(len(goal)):
answer.append(10**8)
queue.append([0, start])
visited = {}
count = 0
while (len(queue) > 0):
queue = sorted(queue)
p = queue[-1]
del queue[-1]
p[0] *= -1
if (p[1] in goal):
index = goal.index(p[1])
if (answer[index] == 10**8):
count += 1
if (answer[index] > p[0]):
answer[index] = p[0]
del queue[-1]
queue = sorted(queue)
if (count == len(goal)):
return answer
if (p[1] not in visited):
for i in range(len(graph[p[1]])):
queue.append( [(p[0] + cost[(p[1], graph[p[1]][i])])* -1, graph[p[1]][i]])
visited[p[1]] = 1

return answer

if __name__ == '__main__':
graph,cost = [[] for i in range(8)],{}

graph[0].append(1)
graph[0].append(3)
graph[3].append(1)
graph[3].append(6)
graph[3].append(4)
graph[1].append(6)
graph[4].append(2)
graph[4].append(5)
graph[2].append(1)
graph[5].append(2)
graph[5].append(6)
graph[6].append(4)

cost[(0, 1)] = 2
cost[(0, 3)] = 5
cost[(1, 6)] = 1
cost[(3, 1)] = 5
cost[(3, 6)] = 6
cost[(3, 4)] = 2
cost[(2, 1)] = 4
cost[(4, 2)] = 4
cost[(4, 5)] = 3
cost[(5, 2)] = 6
cost[(5, 6)] = 3
cost[(6, 4)] = 7

goal = []

goal.append(6)

answer = uniform_cost_search(goal, 0)

print("Minimum cost from 0 to 6 is = ",answer[0])


# HILL CLIMBING

import random

def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []

for i in range(len(tsp)):
randomCity = cities[random.randint(0, len(cities) - 1)]
solution.append(randomCity)
cities.remove(randomCity)

return solution

def routeLength(tsp, solution):


routeLength = 0
for i in range(len(solution)):
routeLength += tsp[solution[i - 1]][solution[i]]
return routeLength

def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours

def getBestNeighbour(tsp, neighbours):


bestRouteLength = routeLength(tsp, neighbours[0])
bestNeighbour = neighbours[0]
for neighbour in neighbours:
currentRouteLength = routeLength(tsp, neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength = currentRouteLength
bestNeighbour = neighbour
return bestNeighbour, bestRouteLength

def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)

while bestNeighbourRouteLength < currentRouteLength:


currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)

return currentSolution, currentRouteLength

def main():
tsp = [
[0, 400, 500, 300],
[400, 0, 300, 500],
[500, 300, 0, 400],
[300, 500, 400, 0]
]

print(hillClimbing(tsp))

if __name__ == "__main__":
main()
# SIMULATED ANNEALING

def simulated_annealing(objective, bounds, n_iterations, step_size, temp):


best = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
best_eval = objective(best)
curr, curr_eval = best, best_eval
for i in range(n_iterations):
candidate = curr + randn(len(bounds)) * step_size
candidate_eval = objective(candidate)
if candidate_eval < best_eval:
best, best_eval = candidate, candidate_eval
print('>%d f(%s) = %.5f' % (i, best, best_eval))
diff = candidate_eval - curr_eval
t = temp / float(i + 1)
metropolis = exp(-diff / t)
if diff < 0 or rand() < metropolis:
curr, curr_eval = candidate, candidate_eval
return [best, best_eval]

from numpy import asarray


from numpy import exp
from numpy.random import randn
from numpy.random import rand
from numpy.random import seed

def objective(x):
return x[0]**2.0

def simulated_annealing(objective, bounds, n_iterations, step_size, temp):


best = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
best_eval = objective(best)
curr, curr_eval = best, best_eval
for i in range(n_iterations):
candidate = curr + randn(len(bounds)) * step_size
candidate_eval = objective(candidate)
if candidate_eval < best_eval:
best, best_eval = candidate, candidate_eval
print('>%d f(%s) = %.5f' % (i, best, best_eval))
print('>%d f(%s) = %.5f' % (i, candidate, candidate_eval))
diff = candidate_eval - curr_eval
t = temp / float(i + 1)
metropolis = exp(-diff / t)
if diff < 0 or rand() < metropolis:
curr, curr_eval = candidate, candidate_eval
return [best, best_eval]

seed(1)
bounds = asarray([[-5.0, 5.0]])
n_iterations = 1000
step_size = 0.1
temp = 10
best, score = simulated_annealing(objective, bounds, n_iterations, step_size, temp)
print('Done!')
print('f(%s) = %f' % (best, score))
# GENETICS ALGORITHM

import numpy
import ga

# The y=target is to maximize this equation ASAP:


# y = w1x1+w2x2+w3x3+w4x4+w5x5+6wx6
# where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7)
# What are the best values for the 6 weights w1 to w6?
# We are going to use the genetic algorithm for the best possible values after a number of generations.

equation_inputs = [4,-2,3.5,5,-11,-4.7]
num_weights = 6

# Genetic algorithm parameters:


# Mating pool size
# Population size

sol_per_pop = 8
num_parents_mating = 4

pop_size = (sol_per_pop,num_weights)
new_population = numpy.random.uniform(low=-4.0, high=4.0, size=pop_size)
print(new_population)

num_generations = 5
for generation in range(num_generations):
print("Generation : ", generation)
fitness = cal_pop_fitness(equation_inputs, new_population)
parents = select_mating_pool(new_population, fitness, num_parents_mating)
offspring_crossover = crossover(parents, offspring_size=(pop_size[0]-parents.shape[0], num_weights))
offspring_mutation = mutation(offspring_crossover)
new_population[0:parents.shape[0], :] = parents
new_population[parents.shape[0]:, :] = offspring_mutation
print("Best result : ", numpy.max(numpy.sum(new_population*equation_inputs, axis=1)))
fitness = cal_pop_fitness(equation_inputs, new_population)
best_match_idx = numpy.where(fitness == numpy.max(fitness))
print("Best solution : ", new_population[best_match_idx, :])
print("Best solution fitness : ", fitness[best_match_idx])
#ga library

import numpy
from random import random

# This project is extended and a library called PyGAD is released to build the genetic algorithm.
# PyGAD documentation: https://pygad.readthedocs.io
# Install PyGAD: pip install pygad
# PyGAD source code at GitHub: https://github.com/ahmedfgad/GeneticAlgorithmPython

def cal_pop_fitness(equation_inputs, pop):


# Calculating the fitness value of each solution in the current population.
# The fitness function caulcuates the sum of products between each input and its corresponding weight.
fitness = numpy.sum(pop*equation_inputs, axis=1)
return fitness

def select_mating_pool(pop, fitness, num_parents):


# Selecting the best individuals in the current generation as parents for producing the next offspring
parents = numpy.empty((num_parents, pop.shape[1]))
for parent_num in range(num_parents):
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
max_fitness_idx = max_fitness_idx[0][0]
parents[parent_num, :] = pop[max_fitness_idx, :]
fitness[max_fitness_idx] = -99999999999
return parents

def crossover(parents, offspring_size):


offspring = numpy.empty(offspring_size)
# The point at which crossover takes place between two parents. Usually it is at the center.
crossover_point = numpy.uint8(offspring_size[1]/2)

for k in range(offspring_size[0]):
# Index of the first parent to mate.
parent1_idx = k%parents.shape[0]
# Index of the second parent to mate.
parent2_idx = (k+1)%parents.shape[0]
# The new offspring will have its first half of its genes taken from the first parent.
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
# The new offspring will have its second half of its genes taken from the second parent.
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
return offspring

def mutation(offspring_crossover):
# Mutation changes a single gene in each offspring randomly.
for idx in range(offspring_crossover.shape[0]):
# The random value to be added to the gene.
offspring_crossover[idx, 4] = offspring_crossover[idx, 4] + random()
return offspring_crossover

You might also like