How specify constraints in pulp dynamically?

1.1k views Asked by At

I want to check if my data is linearly separable or not.For that I am using the equations mentioned at this link. Below is the code that I am using:

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')

And here is the output that I am getting:

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

I am adding 0 to specify that there is no objective function as mentioned in the link. Also since there are about 12000 rows in A variable, hence I am trying to create constraints dynamically.But there seems to be some problem in that.So, what is it that I am doing wrong?

1

There are 1 answers

1
Stuart Mitchell On BEST ANSWER
    var = pulp.LpVariable.dicts("var",range(11),pulp.LpContinuous)

needs to be

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

as the LpVariable.dicts fn looks like this

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