如何动态指定纸浆中的约束?

时间:2017-08-29 04:48:09

标签: python constraints linear-programming pulp

我想检查我的数据是否可以线性分离。为此,我使用了此link中提到的等式。以下是我正在使用的代码:

try:
        import os
        #import random
        import traceback
        import datetime
        #import numpy as np
        import scipy.io as sio
        import pulp
        os.system('cls')
        dicA  = sio.loadmat('A1.mat')
        A = dicA.get('A1')        
        var = pulp.LpVariable.dicts("var",range(11),pulp.LpContinuous)
        A = A[:,0:10]
        model = pulp.LpProblem("Data linearly seaparable", pulp.LpMinimize)
        model+= 0
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        for i in range(len(A)):
            expr = pulp.LpAffineExpression()
            for j in range(len(A[i])):
                expr += var[j]*A[i][j]
            expr+= var[10] <= -1
            model+= expr
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        model.solve()
        print(pulp.LpStatus[model.status])
        print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
except:
        print('exception')
        tb = traceback.format_exc()
        print(tb)
finally:
        print('reached finally')

这是我得到的输出:

C:\Users\puneet\Anaconda3\lib\site-packages\pulp\pulp.py:1348: UserWarning: Overwriting previously set objective.
  warnings.warn("Overwriting previously set objective.")
2017-08-29 10:06:21
exception
Traceback (most recent call last):
  File "C:/Hackerearth Challenge/Machine Learning #3/LInearlySeaparblePulp.py", line 31, in <module>
    model.solve()
  File "C:\Users\puneet\Anaconda3\lib\site-packages\pulp\pulp.py", line 1664, in solve
    status = solver.actualSolve(self, **kwargs)

  File "C:\Users\puneet\Anaconda3\lib\site-packages\pulp\solvers.py", line 1362, in actualSolve
    return self.solve_CBC(lp, **kwargs)
  File "C:\Users\puneet\Anaconda3\lib\site-packages\pulp\solvers.py", line 1384, in solve_CBC
    tmpMps, rename = 1)
  File "C:\Users\puneet\Anaconda3\lib\site-packages\pulp\pulp.py", line 1484, in writeMPS
    f.write(" LO BND       %-8s  % .12e\n" % (n, v.lowBound))
TypeError: must be real number, not str

reached finally

我添加0以指定链接中没有提到目标函数。此外,由于A变量中有大约12000行,因此我试图动态创建约束。但是那里似乎存在一些问题。那么,我做错了什么呢?

1 个答案:

答案 0 :(得分:3)

    var = pulp.LpVariable.dicts("var",range(11),pulp.LpContinuous)

需要

    var = pulp.LpVariable.dicts("var",range(11),cat=pulp.LpContinuous)

因为LpVariable.dicts fn看起来像这样

def dicts(self, name, indexs, lowBound = None, upBound = None, cat = LpContinuous, indexStart = []):