I am trying to use multiprocessing inside a cost function called by scipy.optimize's minimize function. Inside the cost function I have a loop I want to compute in parallel.
A simplified version of the code is as follows:
import numpy as np
from scipy.optimize import minimize
import multiprocessing as mp
def cost_fun(Z, arg1, arg2):
f = 0
shift_args = []
for k in range(8):
shift_args.append((arg1[ :, k], arg2[ :, k]))
p = mp.Pool(mp.cpu_count())
R = p.starmap(calc_R, shift_args)
p.close()
f = f + sum([s**2 for s in R])*Z
return f
def calc_R(x, y):
print('You are here')
return x[0] * y[3]
tmp = minimize(fun=cost_fun, x0=1, method='BFGS', options={'disp': False, 'gtol': 1e-10}, args = (np.random.rand(10,8), np.random.rand(10,8)))
The code freezes at the R = p.starmap(calc_R, shift_args)
line.
How can the multiprocessing be done?
Any help is highly appreciated.