W: 이길 가능성이 있는 줄의 수 L: 질 가능성이 있는 줄의 수 F = W - LUCB1(ni) = v̄i + C × sqrt(ln(Np) / Ni) v̄i: 평균 가치 Ni: 자식 노드의 방문 횟수 Np: 부모 노드의 방문 횟수 C: 탐사 강도를 조절하는 상수AlphaGo는 MCTS를 바탕으로 게임 트리를 탐색하고,
정책망과 가치망을 통해 최적의 수를 선택함
주요 구성:
# 최소값을 찾고 싶은 함수 (목표)
def objective_function(x):
return (x - 3)**2
import random
def hill_climbing(objective_function, start_x, step_size=0.1, max_iterations=100):
current_x = start_x
current_value = objective_function(current_x)
for i in range(max_iterations):
# 현재 위치 주변의 두 점을 확인
neighbors = [current_x + step_size, current_x - step_size]
# 이웃 중 더 나은(값이 더 작은) 점을 선택
next_x = min(neighbors, key=objective_function)
next_value = objective_function(next_x)
print(f"Iteration {i}: x = {current_x:.5f}, f(x) = {current_value:.5f}")
# 더 이상 개선이 없으면 멈춤
if next_value >= current_value:
break
current_x, current_value = next_x, next_value
print(f"최적해 추정: x = {current_x}, 최소값 = {current_value}")
return current_x
# 실행
hill_climbing(objective_function, start_x=random.uniform(-10, 10))
import math
def simulated_annealing(objective_function, start_x, initial_temp=100.0, cooling_rate=0.95, max_iterations=1000):
current_x = start_x
current_value = objective_function(current_x)
temperature = initial_temp
for i in range(max_iterations):
# 온도가 너무 낮아지면 중단
if temperature < 1e-6:
break
# 근처의 랜덤한 이웃 선택
new_x = current_x + random.uniform(-1, 1)
new_value = objective_function(new_x)
# 차이 계산
delta = new_value - current_value
# 개선되었거나, 확률적으로 허용하는 경우 이동
if delta < 0 or random.random() < math.exp(-delta / temperature):
current_x = new_x
current_value = new_value
print(f"Iteration {i}: x = {current_x:.5f}, f(x) = {current_value:.5f}, T = {temperature:.5f}")
# 온도 감소
temperature *= cooling_rate
print(f"최적해 추정: x = {current_x}, 최소값 = {current_value}")
return current_x
# 실행
simulated_annealing(objective_function, start_x=random.uniform(-10, 10))
import heapq
# A*에서 사용할 노드 정의 (단순화된 x값만 있음)
class Node:
def __init__(self, x, g):
self.x = x # 현재 상태 (x값)
self.g = g # 시작점에서 현재까지의 비용 (실제 비용)
self.h = (x - 3)**2 # 목표까지의 예측 비용
self.f = self.g + self.h # 평가함수 f(x) = g(x) + h(x)
def __lt__(self, other):
return self.f < other.f # 우선순위 비교
def astar_search(start_x, goal_range=0.01):
open_list = []
heapq.heappush(open_list, Node(start_x, g=0))
visited = set()
while open_list:
current = heapq.heappop(open_list)
print(f"x = {current.x:.5f}, f(x) = {current.f:.5f}, g = {current.g:.5f}, h = {current.h:.5f}")
# 목표에 도달했는지 검사
if abs(current.x - 3) <= goal_range:
print(f"최적해 도달: x = {current.x}, 최소값 = {objective_function(current.x)}")
return current.x
visited.add(round(current.x, 5))
# 이웃 생성 (양옆으로 조금씩 이동)
for dx in [-0.1, 0.1]:
neighbor_x = current.x + dx
if round(neighbor_x, 5) in visited:
continue
heapq.heappush(open_list, Node(neighbor_x, g=current.g + abs(dx)))
print("해를 찾지 못함")
return None
# 실행
astar_search(start_x=random.uniform(-10, 10))