我正在尝试解决一个零和博弈,找到玩家I的最优概率分布。为此,我使用了scipy linprog单纯形法。
我看过一个例子,我需要改变这个游戏:
G=np.array([
[ 0 2 -3 0]
[-2 0 0 3]
[ 3 0 0 -4]
[ 0 -3 4 0]])进入这个线性优化问题:
Maximize z
Subject to: 2*x2 - 3*x3 + z <= 0
-2*x1 + + 3*x4 + z <= 0
3*x1 + - 4*x4 + z <= 0
- 3*x2 + 4*x3 + z <= 0
with x1 + x2 + x3 + x4 = 1下面是我的实际代码:
def simplex(G):
(n,m) = np.shape(G)
A_ub = np.transpose(G)
# we add an artificial variable to maximize, present in all inequalities
A_ub = np.append(A_ub, np.ones((m,1)), axis = 1)
# all inequalities should be inferior to 0
b_ub = np.zeros(m)
# the sum of all variables except the artificial one should be equal to one
A_eq = np.ones((1,n+1))
A_eq[0][n] = 0
b_eq = np.ones(1)
c = np.zeros(n + 1)
# -1 to maximize the artificial variable we're going to add
c[n] = -1
res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=(0,None))
return (res.x[:-1], res.fun)下面是我得到的分布:[5.87042987e-01 1.77606350e-10 2.79082859e-10 4.12957014e-01],它的总和是1,但我希望是[0 0.6 0.4 0]
我正在尝试一个更大的游戏,有6到7行(以及变量),它的总和甚至不到1。我做错了什么?
感谢您能提供的任何帮助。
发布于 2019-08-17 23:37:59
自从我找到解决方案后,我就没有更新过这篇文章。我建议不要使用Scipy linprog函数,如果你不太了解线性编程,它的文档很糟糕,而且我发现它在很多例子中都是不精确和不一致的(我当时确实尝试添加了一个负号,正如oyamad所建议的那样)。
我切换到PuLP python库,从一开始就没有问题。
发布于 2019-08-16 10:33:05
(我假设玩家1(行玩家)是最大化的,玩家2(列玩家)是最小化的。)
在这个博弈的纳什均衡中,玩家1的策略是任何有4/7 <= x2 <= 3/5,x2 + x3 = 1的[0, x2, x3, 0]。
在您的代码中,不等式约束-G.T x + z <= 0缺少一个负号。尝试以下代码:
def simplex(G, method='simplex'):
(n,m) = np.shape(G)
A_ub = -np.transpose(G) # negative sign added
# we add an artificial variable to maximize, present in all inequalities
A_ub = np.append(A_ub, np.ones((m,1)), axis = 1)
# all inequalities should be inferior to 0
b_ub = np.zeros(m)
# the sum of all variables except the artificial one should be equal to one
A_eq = np.ones((1,n+1))
A_eq[0][n] = 0
b_eq = np.ones(1)
c = np.zeros(n + 1)
# -1 to maximize the artificial variable we're going to add
c[n] = -1
res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=(0,None),
method=method) # `method` option added
return (res.x[:-1], res.fun)使用单纯型方法:
simplex(G, method='simplex')(array([0. , 0.57142857, 0.42857143, 0. ]), 0.0)
# 4/7 = 0.5714285...使用内点方法:
simplex(G, method='interior-point')(array([1.77606350e-10, 5.87042987e-01, 4.12957014e-01, 2.79082859e-10]),
-9.369597151936987e-10)
# 4/7 < 5.87042987e-01 < 3/5使用修改后的单纯形法:
simplex(G, method='revised simplex')(array([0. , 0.6, 0.4, 0. ]), 0.0)
# 3/5 = 0.6(使用SciPy v1.3.0运行)
https://stackoverflow.com/questions/56416331
复制相似问题