dimanche 13 juin 2021

Scipy.minimize doesn't work with probabilities of np.random.choice as input

I'm new in Python, and have difficulties with optimization in scipy.

I'm trying to perform minimization with scipy.minimize when the inputs are probabilities governing the random numbers, but without any luck.

Here's the very simplified code of my work:

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)

Its obvious, that the best solution will be reached with this vector: x=[1,0,0], but when I run the code, the minimization algorithm does not do a thing at all. Here is the error I get:

 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.3, 0.4])

Any ideas what I am doing wrong?




Aucun commentaire:

Enregistrer un commentaire