微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Scipy.minimize 不适用于 np.random.choice 作为输入的概率

如何解决Scipy.minimize 不适用于 np.random.choice 作为输入的概率

我是 Python 新手,在 scipy 中进行优化有困难。

当输入是控制随机数的概率时,我正在尝试使用 scipy.minimize 执行最小化,但没有任何运气。

这是我工作的非常简化的代码

import numpy as np
import pandas as pd
from scipy.optimize import minimize

#Creating a pandas Series,where random numbers will be stored
Store=pd.Series(np.nan,index=np.arange(0,100))

# defining objective function
def fun(x):
    for i in range(0,100): # for 100 iteration
        xx=int(np.random.choice(a=[0,1,2],size=1,p=x)) # ...the code generates random numbers
        Store[i]=xx #...stores in Store series
    
    return sum(Store) # and returns their sum

# the sum of probabilities should be equal to 1
def cons_1(x):
    return x[0]+x[1]+x[2]-1.0
constraint1={'type':'eq','fun': cons_1}

# each probability must be between 0 and 1
b=(0,1)
bnds = (b,b,b)

#Initial guess is...
x0=[0.3,0.3,0.4]

# I want to minimize the sum of random numbers...
minimize(fun,x0,bounds=bnds,constraints=constraint1)

很明显,使用这个向量可以达到最佳解决方案:x=[1,0],但是当我运行代码时,最小化算法根本没有做任何事情。这是我得到的错误

 fun: 91.0
     jac: array([9.39524096e+08,1.20795955e+09,5.36870912e+08])
 message: 'Inequality constraints incompatible'
    nfev: 4
     nit: 1
    njev: 1
  status: 4
 success: False
       x: array([0.3,0.4])

知道我做错了什么吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。