0

我正在尝试使用 cvxpy 创建一个支持向量机,通过解决它的对偶形式

在此处输入图像描述

这是代码:

import cvxpy as cp
import numpy as np

DIM = 2
NUM = 50
#COLORS = ['red', 'blue']
M1 = np.ones((DIM,))
M2 = 2 * np.ones((DIM,))
C1 = np.diag(0.3 * np.ones((DIM,)))
C2 = np.diag(0.2 * np.ones((DIM,)))

def generate_gaussian(m, c, num):
     return np.random.multivariate_normal(m, c, num)

NUM = 50
x1 = generate_gaussian(M1, C1, NUM)
y1 = np.ones((x1.shape[0],))
x2 = generate_gaussian(M2, C2, NUM)
y2 = -np.ones((x2.shape[0],))
# join
x = np.concatenate((x1, x2), axis = 0)
y = np.concatenate((y1, y2), axis = 0)
print('x {} y {}'.format(x.shape, y.shape))

alphas = cp.Variable(2*NUM)
Cd = cp.Parameter()
Cd.value = 0.95

alphas_constraint_1 = [alphas[i] >=0 for i in range(2*NUM)]
alphas_constraint_2 = [alphas[i] <= Cd for i in range(2*NUM)]
alpha_y_constraint = [alphas@y.T == 0]

constraints = alphas_constraint_1 + alphas_constraint_2 + alpha_y_constraint

K = y[:,None]*x
K = np.dot(K,K.T)

objective_dual = cp.Minimize(-cp.sum(alphas)+cp.quad_form(alphas,K))

prob_dual = cp.Problem(objective_dual,constraints)
prob_dual.solve()

当我运行时prob_dual.solve()出现此错误

DCPError: Problem does not follow DCP rules. Specifically:
The objective is not DCP. Its following subexpressions are not:
QuadForm(var14498, [[ 2.64314065  3.52503472  3.06058033 ... -4.66774474 
-4.06204535
 -4.25545758]
 [ 3.52503472  4.70705211  4.09996823 ... -6.26760728 -5.41784971
  -5.71519635]
 [ 3.06058033  4.09996823  3.60040302 ... -5.53652152 -4.70508757
  -5.05117747]
 ...
 [-4.66774474 -6.26760728 -5.53652152 ...  8.54985838  7.17702844
   7.80325227]
 [-4.06204535 -5.41784971 -4.70508757 ...  7.17702844  6.24269435
   6.5432026 ]
 [-4.25545758 -5.71519635 -5.05117747 ...  7.80325227  6.5432026
   7.12207384]])

SVM 的对偶形式怎么可能不是凸问题?错误在哪里?想不通。

我运行了这段代码:

expr1 = alphas.T@alphas
expr2 = cp.quad_form(alphas,K)
print(expr1.curvature, expr1.sign, expr1.is_dcp())
print(expr2.curvature, expr2.sign, expr2.is_dcp())

我得到了相同的输出

UNKNOWN UNKNOWN False
4

0 回答 0