下面的python代码是以某种特殊的顺序遍历(c,g)的一个2D网格,存储在“jobs”和“job_queue”中。但是在尝试理解代码之后,我不确定它是哪种顺序。有人能够说出订单并为每个功能的目的提供一些解释吗?谢谢并恭祝安康!
import Queue
c_begin, c_end, c_step = -5, 15, 2
g_begin, g_end, g_step = 3, -15, -2
def range_f(begin,end,step):
# like range, but works on non-integer too
seq = []
while True:
if step > 0 and begin > end: break
if step < 0 and begin < end: break
seq.append(begin)
begin = begin + step
return seq
def permute_sequence(seq):
n = len(seq)
if n <= 1: return seq
mid = int(n/2)
left = permute_sequence(seq[:mid])
right = permute_sequence(seq[mid+1:])
ret = [seq[mid]]
while left or right:
if left: ret.append(left.pop(0))
if right: ret.append(right.pop(0))
return ret
def calculate_jobs():
c_seq = permute_sequence(range_f(c_begin,c_end,c_step))
g_seq = permute_sequence(range_f(g_begin,g_end,g_step))
nr_c = float(len(c_seq))
nr_g = float(len(g_seq))
i = 0
j = 0
jobs = []
while i < nr_c or j < nr_g:
if i/nr_c < j/nr_g:
# increase C resolution
line = []
for k in range(0,j):
line.append((c_seq[i],g_seq[k]))
i = i + 1
jobs.append(line)
else:
# increase g resolution
line = []
for k in range(0,i):
line.append((c_seq[k],g_seq[j]))
j = j + 1
jobs.append(line)
return jobs
def main():
jobs = calculate_jobs()
job_queue = Queue.Queue(0)
for line in jobs:
for (c,g) in line:
job_queue.put((c,g))
main()
编辑:
每个 (c,g) 都有一个值。代码其实就是在(c,g)的二维网格中搜索,找到值最小的网格点。我猜代码正在使用某种启发式搜索算法?原始代码在这里http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/gridsvr/gridregression.py,这是一个脚本,用于搜索 svm 算法两个参数 c 和 g 的最佳值,最小验证错误。