首页 > 解决方案 > 在 Python CVXPY 中,变量矩阵中是否有针对不同元素的计数函数?

问题描述

对于CVXPY变量矩阵及其变形差分矩阵h,如何计算每列不同非零元素的个数。

当前的错误是 CVXPY 与 Numpy Reshape 和 Delete 函数不兼容

我想解决一个作业分配问题,目标是尽可能将相同类型的任务分配给一台机器,我用矩阵“C”代表作业和机器能力矩阵,矩阵“D”代表作业类型,为易于使用的数组乘法函数,我重复 3 次,我的想法是最小化作业分配矩阵在每列中不同非零元素的数量。

# The output #
(CVXPY) Apr 21 06:43:55 PM: Problem status: optimal
(CVXPY) Apr 21 06:43:55 PM: Optimal value: 2.000e+00
(CVXPY) Apr 21 06:43:55 PM: Compilation took 7.812e-02 seconds
(CVXPY) Apr 21 06:43:55 PM: Solver (including time spent in interface) took 0.000e+00 seconds
Best sloution is:
 [[1. 0. 0.]
 [1. 0. 0.]
 [1. 0. 0.]
 [0. 0. 1.]
 [0. 0. 1.]
 [0. 0. 1.]
 [1. 0. 0.]
 [1. 0. 0.]
 [1. 0. 0.]]
Best sloution is:
 [[1. 0. 0.]
 [1. 0. 0.]
 [3. 0. 0.]
 [0. 0. 2.]
 [0. 0. 2.]
 [0. 0. 2.]
 [3. 0. 0.]
 [3. 0. 0.]
 [3. 0. 0.]]
Traceback (most recent call last):
  File "C:/Users/N000377/Documents/python/help need.py", line 47, in <module>
    print("Best sloution is:\n",h.value)
AttributeError: 'numpy.ndarray' object has no attribute 'value'
## The input python code ##
#Basic 9 lots 3 tool assignment 

import cvxpy as cp
import numpy as np
# Task assignable schema matrix--c #
c=np.array([[1,1,0],
            [1,1,0],
            [1,1,0],
            [1,1,1],
            [1,1,1],
            [1,1,1],
            [1,0,0],
            [1,0,0],
            [1,0,0],
            ])
# Task type matrix#
d = np.array ([[1,1,1],
               [1,1,1],
               [3,3,3],
               [2,2,2],
               [2,2,2],
               [2,2,2],
               [3,3,3],
               [3,3,3],
               [3,3,3],
               ])
# variable matrix #
x = cp.Variable((9,3),integer=True)

x1 = cp.multiply(d,x)
# Task type matrix #
h = cp.diff(x1,axis=0)
h=np.reshape(h,(1,-1))
#print(h)
g= np.delete(h,np.where (h==0))
obj = cp.Minimize(np.size(g)+1)
con= [0 <= x, x <= 1,cp.sum(x, axis=1, keepdims=True)==1,cp.sum(cp.multiply(c,x))==9]
prob = cp.Problem(obj, con)

print("Is DCP? ", obj.is_dcp())

prob.solve(solver='CBC',verbose =True)

print("Best sloution is:\n",x.value)
print("Best sloution is:\n",x1.value)
print("Best sloution is:\n",h.value)

当前的错误是 CVXPY 与 Numpy Reshape 和 Delete 函数不兼容

标签: pythonnumpycountassigncvxpy

解决方案


推荐阅读