以COBYLA和SVM分类器为约束的函数最小化

时间:2019-02-26 08:46:05

标签: python constraints classification svm mathematical-optimization

我试图在约束c <1的情况下最小化以x1 = x2 = 1.5为中心的二维二次函数,其中对于x1 <1和x2 <1,c = 0,在其他任何地方,c = 1。约束模型由SVM分类器提供。代码如下。运行它时,我收到错误消息

COBYLA failed to find a solution: Did not converge to a solution satisfying the constraints. See `maxcv` for magnitude of violation.

建议的最小值为[1.5,1.5]。您对我可以采取什么措施来强制遵守约束条件有何建议?背景是我在结构约束下优化了空气动力学形状,因此不能违反这些约束。因此,问题的表达方式类似于下面的代码。

# import required libraries
import random
import matplotlib.pyplot as plt
from scipy.optimize import fmin_cobyla
from sklearn import svm

# generate grid with random positions
x1_rand=[]
x2_rand=[]
for x in range(5000):
    x1_rand.append(random.uniform(-4,4))
    x2_rand.append(random.uniform(-4,4))

# generate classes for the grid (classes are 0 and 1)
y_class=[]
x1_pos=[]
x2_pos=[]
x1_neg=[]
x2_neg=[]
for i in range(len(x1_rand)):
    if x1_rand[i]<1 and x2_rand[i] < 1:
        x1_pos.append(x1_rand[i])
        x2_pos.append(x2_rand[i])
        y_class.append('0')
    else:
        x1_neg.append(x1_rand[i])
        x2_neg.append(x2_rand[i])
        y_class.append('1')

# build the SVM model to separate the data
C=1.0
model    = svm.SVC(kernel='rbf',gamma=0.7,C=C)
features = [x1_rand, x2_rand]
features = zip(*features)
model.fit(features,y_class)

# plot data, the classification is color coded
# red=constraint fulfilled; blue=constraint violated
plt.scatter(x1_pos,x2_pos,c='r')
plt.scatter(x1_neg,x2_neg,c='b')

# define the constraint function
def constr1(x):
    return 0.5-float(model.predict([x[0],x[1]])[0])

# define the objective function
fun = lambda x: (x[0] - 1.5)**2 + (x[1] - 1.5)**2

# minimize the objective function
res = fmin_cobyla(fun,[0.5,0.5],constr1,rhoend=1e-5)
print res

0 个答案:

没有答案