顺序编程和并行编程之间的解决方案差异

时间:2018-09-17 18:32:03

标签: python python-2.7 parallel-processing multiprocessing

我创建了一个python代码,用于解决组套索惩罚线性模型。对于那些不习惯使用这些模型的人,基本思想是为数据集(x)和响应变量(y)以及参数值(lambda1)提供输入,从而改变此参数更改模型的解。因此,我决定使用多重处理库并求解不同的模型(与不同的参数值关联)。我创建了一个名为“ model.py”的python文件,其中包含以下功能:

# -*- coding: utf-8 -*-
from __future__ import division
import functools
import multiprocessing as mp
import numpy as np
from cvxpy import *

def lm_gl_preprocessing(x, y, index, lambda1=None):
    lambda_vector = [lambda1]
    m = x.shape[1]
    n = x.shape[0]
    lambda_param = Parameter(sign="positive")
    m = m+1
    index = np.append(0, index)
    x = np.c_[np.ones(n), x]
    group_sizes = []
    beta_var = []
    unique_index = np.unique(index)
    for idx in unique_index:
        group_sizes.append(len(np.where(index == idx)[0]))
        beta_var.append(Variable(len(np.where(index == idx)[0])))
    num_groups = len(group_sizes)
    group_lasso_penalization = 0
    model_prediction = x[:, np.where(index == unique_index[0])[0]] * beta_var[0]
    for i in range(1, num_groups):
        model_prediction += x[:, np.where(index == unique_index[i])[0]] * beta_var[i]
        group_lasso_penalization += sqrt(group_sizes[i]) * norm(beta_var[i], 2)
    lm_penalization = (1.0/n) * sum_squares(y - model_prediction)
    objective = Minimize(lm_penalization + (lambda_param * group_lasso_penalization))
    problem = Problem(objective)
    response = {'problem': problem, 'beta_var': beta_var, 'lambda_param': lambda_param, 'lambda_vector': lambda_vector}
    return response

def solver(problem, beta_var, lambda_param, lambda_vector):
    beta_sol_list = []
    for i in range(len(lambda_vector)):
        lambda_param.value = lambda_vector[i]
        problem.solve(solver=ECOS)
        beta_sol = np.asarray(np.row_stack([b.value for b in beta_var])).flatten()
        beta_sol_list.append(beta_sol)
    return beta_sol_list

def parallel_solver(problem, beta_var, lambda_param, lambda_vector):
    # Divide parameter vector into chunks to be executed in parallel
    num_chunks = mp.cpu_count()
    chunks = np.array_split(lambda_vector, num_chunks)
    # Solve problem in parallel
    pool = mp.Pool(num_chunks)
    global_results = pool.map(functools.partial(solver, problem, beta_var, lambda_param), chunks)
    pool.close()
    pool.join()
    return global_results
  • 函数lm_gl_preprocessing基本上定义了要使用cvxpy模块求解的模型。
  • 函数求解器从先前的函数中获取模型详细信息,并解决导致模型最终解决的优化问题。
  • parallel_solver函数使用多重处理并行化求解器函数。

如果在python控制台中启动runnig并行求解器,它将提供解决方案。该解决方案不同于顺序求解器提供的解决方案。 如果我重新启动python控制台并启动顺序求解器runnig,然后运行并行求解器,则并行求解器将提供与顺序求解器相同的解决方案。我将显示:

from __future__ import division
from sklearn.datasets import load_boston
import numpy as np
import model as t

boston = load_boston()
x = boston.data
y = boston.target
index = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5])

lambda1 = 1e-3

r1 = t.lm_gl_preprocessing(x=x, y=y, index=index, lambda1=lambda1)
s_parallel_1 = t.parallel_solver(problem=r1['problem'], beta_var=r1['beta_var'], lambda_param=r1['lambda_param'], lambda_vector=r1['lambda_vector'])
print(s_parallel_1)
[[array([  4.61648376e+01,  -1.22394832e-04,   0.00000000e+00,
       0.00000000e+00,   1.37065733e-04,   1.51910696e-03,
       0.00000000e+00,   1.51910696e-03,   0.00000000e+00,
       7.00079603e-03,   1.52776114e-03,  -8.67357376e-01,
       7.16429750e-03,  -8.67357376e-01])], [], [], []]
s_1 = t.solver(problem=r1['problem'], beta_var=r1['beta_var'], lambda_param=r1['lambda_param'], lambda_vector=r1['lambda_vector'])
print(s_1)
[array([  3.62813738e+01,  -1.06995338e-01,   4.64210526e-02,
      1.97112192e-02,   2.68475527e+00,  -1.75142155e+01,
      3.80741843e+00,   5.14842823e-04,  -1.47105323e+00,
      3.04949407e-01,  -1.23508259e-02,  -9.50143293e-01,
      9.40708993e-03,  -5.25758097e-01])]
#####################################################
r1 = t.lm_gl_preprocessing(x=x, y=y, index=index, lambda1=lambda1)
s_1 = t.solver(problem=r1['problem'], beta_var=r1['beta_var'], lambda_param=r1['lambda_param'], lambda_vector=r1['lambda_vector'])
print(s_1)
[array([  3.62813738e+01,  -1.06995338e-01,   4.64210526e-02,
      1.97112192e-02,   2.68475527e+00,  -1.75142155e+01,
      3.80741843e+00,   5.14842823e-04,  -1.47105323e+00,
      3.04949407e-01,  -1.23508259e-02,  -9.50143293e-01,
      9.40708993e-03,  -5.25758097e-01])]
s_parallel_1 = t.parallel_solver(problem=r1['problem'], beta_var=r1['beta_var'], lambda_param=r1['lambda_param'], lambda_vector=r1['lambda_vector'])
print(s_parallel_1)
[[array([  3.62813738e+01,  -1.06995338e-01,   4.64210526e-02,
       1.97112192e-02,   2.68475527e+00,  -1.75142155e+01,
       3.80741843e+00,   5.14842823e-04,  -1.47105323e+00,
       3.04949407e-01,  -1.23508259e-02,  -9.50143293e-01,
       9.40708993e-03,  -5.25758097e-01])], [], [], []]

PS:我知道在此示例中,我正在使用并行编程来解决具有一个可能参数值的一个模型,但这只是一个小示例,旨在说明此处的顺序编程和并行编程提供的解决方案的区别。因为我在这里完全迷路了,所以我要感谢任何提示。

1 个答案:

答案 0 :(得分:1)

如果我执行您的代码,在所有情况下我都会得到相同的结果。这是我正在运行的代码(我合并了两个文件):

from __future__ import division
import functools
import multiprocessing as mp
import numpy as np
from cvxpy import *
from sklearn.datasets import load_boston

def lm_gl_preprocessing(x, y, index, lambda1=None):
    lambda_vector = [lambda1]
    m = x.shape[1]
    n = x.shape[0]
    lambda_param = Parameter(sign="positive")
    m = m+1
    index = np.append(0, index)
    x = np.c_[np.ones(n), x]
    group_sizes = []
    beta_var = []
    unique_index = np.unique(index)
    for idx in unique_index:
        group_sizes.append(len(np.where(index == idx)[0]))
        beta_var.append(Variable(len(np.where(index == idx)[0])))
    num_groups = len(group_sizes)
    group_lasso_penalization = 0
    model_prediction = x[:, np.where(index == unique_index[0])[0]] * beta_var[0]
    for i in range(1, num_groups):
        model_prediction += x[:, np.where(index == unique_index[i])[0]] * beta_var[i]
        group_lasso_penalization += sqrt(group_sizes[i]) * norm(beta_var[i], 2)
    lm_penalization = (1.0/n) * sum_squares(y - model_prediction)
    objective = Minimize(lm_penalization + (lambda_param * group_lasso_penalization))
    problem = Problem(objective)
    response = {'problem': problem, 'beta_var': beta_var, 'lambda_param': lambda_param, 'lambda_vector': lambda_vector}
    return response

def solver(problem, beta_var, lambda_param, lambda_vector):
    beta_sol_list = []
    for i in range(len(lambda_vector)):
        lambda_param.value = lambda_vector[i]
        problem.solve(solver=ECOS)
        beta_sol = np.asarray(np.row_stack([b.value for b in beta_var])).flatten()
        beta_sol_list.append(beta_sol)
    return beta_sol_list

def parallel_solver(problem, beta_var, lambda_param, lambda_vector):
    # Divide parameter vector into chunks to be executed in parallel
    num_chunks = mp.cpu_count()
    chunks = np.array_split(lambda_vector, num_chunks)
    # Solve problem in parallel
    pool = mp.Pool(num_chunks)
    global_results = pool.map(functools.partial(solver, problem, beta_var, lambda_param), chunks)
    pool.close()
    pool.join()
    return global_results

if __name__ == "__main__":
     boston = load_boston()
     x = boston.data
     y = boston.target
     index = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5])

     lambda1 = 1e-3

     r1 = lm_gl_preprocessing(x=x, y=y, index=index, lambda1=lambda1)
     s_parallel_1 = parallel_solver(problem=r1['problem'], beta_var=r1['beta_var'], lambda_param=r1['lambda_param'], lambda_vector=r1['lambda_vector'])
     print(s_parallel_1)
     r1 = lm_gl_preprocessing(x=x, y=y, index=index, lambda1=lambda1)
     s_1 = solver(problem=r1['problem'], beta_var=r1['beta_var'], lambda_param=r1['lambda_param'], lambda_vector=r1['lambda_vector'])
     print(s_1)
     print ("#####################################################")
     r1 = lm_gl_preprocessing(x=x, y=y, index=index, lambda1=lambda1)
     s_1 = solver(problem=r1['problem'], beta_var=r1['beta_var'], lambda_param=r1['lambda_param'], lambda_vector=r1['lambda_vector'])
     print(s_1)
     r1 = lm_gl_preprocessing(x=x, y=y, index=index, lambda1=lambda1)
     s_parallel_1 = parallel_solver(problem=r1['problem'], beta_var=r1['beta_var'], lambda_param=r1['lambda_param'], lambda_vector=r1['lambda_vector'])
     print(s_parallel_1)

并输出:

[[array([ 3.62813738e+01, -1.06995338e-01,  4.64210526e-02,  1.97112192e-02,
        2.68475527e+00, -1.75142155e+01,  3.80741843e+00,  5.14842823e-04,
       -1.47105323e+00,  3.04949407e-01, -1.23508259e-02, -9.50143293e-01,
        9.40708993e-03, -5.25758097e-01])], [], [], []]
[array([ 3.62813738e+01, -1.06995338e-01,  4.64210526e-02,  1.97112192e-02,
        2.68475527e+00, -1.75142155e+01,  3.80741843e+00,  5.14842823e-04,
       -1.47105323e+00,  3.04949407e-01, -1.23508259e-02, -9.50143293e-01,
        9.40708993e-03, -5.25758097e-01])]
#####################################################
[array([ 3.62813738e+01, -1.06995338e-01,  4.64210526e-02,  1.97112192e-02,
        2.68475527e+00, -1.75142155e+01,  3.80741843e+00,  5.14842823e-04,
       -1.47105323e+00,  3.04949407e-01, -1.23508259e-02, -9.50143293e-01,
        9.40708993e-03, -5.25758097e-01])]
[[array([ 3.62813738e+01, -1.06995338e-01,  4.64210526e-02,  1.97112192e-02,
        2.68475527e+00, -1.75142155e+01,  3.80741843e+00,  5.14842823e-04,
       -1.47105323e+00,  3.04949407e-01, -1.23508259e-02, -9.50143293e-01,
        9.40708993e-03, -5.25758097e-01])], [], [], []]

如您所见,我拥有相同数量的CPU(4)。

我的环境是Linux上的Python2.7,这些是相关软件包的版本:

>>> import sklearn
>>> sklearn.__version__
'0.19.2'
>>> import scipy
>>> scipy.__version__
'1.1.0'
>>> import numpy 
>>> numpy.__version__
'1.15.2'
>>> import cvxpy
>>> cvxpy.__version__
'0.4.0'
>>> import multiprocessing
>>> multiprocessing.__version__
'0.70a1'