在学校用的是Google的colab,体验非常棒。
但是回到国内,由于没有爬爬爬的能力,所以就没办法用colab继续啦。
不得不提colab是真的方便,线上的平台,并且提供免费的GPU,TPU加速。GPU在神经网络处理图像的时候速度明显有大的提升。CPU跑半天的,GPU不出一小时就可以搞定。
除了速度,编译环境也很友好。方便查错,会直接给Google的link。Tensorflow什么的也可以用啦。
回国之后嘛,就只可以用Jupyter Notebook查看.ipynb程序啦。
!!!之后的代码有一部分为教授上课给的样例,一部分为课后习题,总之就是不完全原创。
写这个博客只是为了我自己以后查找方便,等交完总结作业也会开成私密模式。
代码都是Python
Hill climbing
爬山算法
其想法就是随机取一点,比较它左边和右边,在两者之间选择更优的解。
这里得到的最终解法趋于一个局域最优解。在选解时加入一定概率选择差的那点有概率跳出当前局部最优解达到全局最优解。
大概就可以联想爬一座山和探索一组山脉。
下面使用N皇后问题的背景做一个爬山。
(N皇后当然有其他方法,比如进制回溯,这里仅仅是为了爬山算法而爬山算法)
import math
import random
import time
def generate_board(N=4):
board = [i for i in range(N)]
random.shuffle(board)
return board
class NQueenState(object):
def __init__(self, _board):
self.board = _board
self.heuristic_value = NQueenState.heuristic(self.board)
@staticmethod
def heuristic(board):
# heuristic for N queen
# no of pairs that attack each other either directly
# or indirectly
h = 0
N = len(board)
for i in range(N):
for j in range(i+1, N):
if board[i] == board[j]:
h+=1
if ((board[i] == board[j] + (j-i))
or (board[i] == board[j] - (j-i))):
h+=1
return h
@staticmethod
def successors(current_state):
successors = []
N = len(current_state.board)
for i in range(N):
for j in range(N):
if current_state.board[i] != j:
L = current_state.board[:]
L[L.index(current_state.board[i])] = j
successors.append(NQueenState(L))
return successors
@staticmethod
def best_successor(current):
lowest_successor = None
for successor in NQueenState.successors(current):
if lowest_successor is None:
lowest_successor = successor
elif lowest_successor.heuristic_value > successor.heuristic_value:
lowest_successor = successor
return lowest_successor
@staticmethod
def random_successor(current):
successors = NQueenState.successors(current)
return random.choice(successors)
@staticmethod
def random_state(N):
return NQueenState(generate_board(N))
def hill_climbing_search(problem):
current = problem
while True:
successor = NQueenState.best_successor(current)
if successor.heuristic_value <= current.heuristic_value:
return successor
current = successor
def hill_climbing_search_rr(problem):
current = problem
N = len(problem.board)
while True:
successor = NQueenState.best_successor(current)
if successor.heuristic_value > current.heuristic_value:
return current
elif successor.heuristic_value == current.heuristic_value:
successor = NQueenState.random_state(N)
current = successor
# RANDOM RESTART HILL CLIMBING