全局优化函数:
import dlib
from math import sin,cos,pi,exp,sqrt
# This is a standard test function for these kinds of optimization problems.
# It has a bunch of local minima, with the global minimum resulting in
# holder_table()==-19.2085025679.
def holder_table(x0,x1):
return -abs(sin(x0)*cos(x1)*exp(abs(1-sqrt(x0*x0+x1*x1)/pi)))
# Find the optimal inputs to holder_table(). The print statements that follow
# show that find_min_global() finds the optimal settings to high precision.
x,y = dlib.find_min_global(holder_table,
[-10,-10], # Lower bound constraints on x0 and x1 respectively
[10,10], # Upper bound constraints on x0 and x1 respectively
80) # The number of times find_min_global() will call holder_table()
print("optimal inputs: {}".format(x));
print("optimal output: {}".format(y));
最佳分配问题:
假设需要为N个工作分配N个人。另外,每个工人会得到相应报酬,但每一份工作都需要有不同的技能,所以他们在某些工作中表现更好或更糟糕
其他。您希望找到将人员分配到这些工作的最佳方式,并希望报酬最大化。对于这样的问题模型,可以直接调用max_cost_assignment来实现,输入为一给矩阵,第N行为第N个工人所得到的报酬。如第1个工人做3分工作的报酬为1,2,6;第2个工人是5,3,6;第3个为4,5,0。这个函数可以用于高效的计算最大损失。
cost = dlib.matrix([[1, 2, 6],
[5, 3, 6],
[4, 5, 0]])
# To find out the best assignment of people to jobs we just need to call this
# function.
assignment = dlib.max_cost_assignment(cost)
# This prints optimal assignments: [2, 0, 1]
# which indicates that we should assign the person from the first row of the
# cost matrix to job 2, the middle row person to job 0, and the bottom row
# person to job 1.
print("Optimal assignments: {}".format(assignment))
# This prints optimal cost: 16.0
# which is correct since our optimal assignment is 6+5+5.
print("Optimal cost: {}".format(dlib.assignment_cost(cost, assignment)))