首页 > 解决方案 > ValueError:使用 cvxopt 进行 SVM 的域错误?

问题描述

我尝试使用 cvxopt 进行优化并使用iris数据集。我定义了一个函数fit(X, y),输入Xy输出权重wb。但是为什么会出现错误?

import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
iris_df = pd.DataFrame(data= np.c_[iris["data"], iris["target"]], columns= iris["feature_names"] + ["target"])
# Retain only 2 linearly separable classesiris_df = iris_df[iris_df["target"].isin([0,1])]iris_df["target"] = iris_df[["target"]].replace(0,-1)
# Select only 2 attributesiris_df = iris_df[["petal length (cm)", "petal width (cm)", "target"]]
iris_df.head()

X = iris_df[["petal length (cm)", "petal width (cm)"]].to_numpy()
y = iris_df[["target"]].to_numpy()
from cvxopt import matrix as cvxopt_matrix
from cvxopt import solvers as cvxopt_solvers

def fit(X, y):

  m, n= X.shape
  y = y.reshape(-1,1) * 1.
  X_dash = y * X
  H = np.dot(X_dash , X_dash.T) * 1.

#Converting into cvxopt format
  P = cvxopt_matrix(H)
  q = cvxopt_matrix(-np.ones((m, 1)))
  G = cvxopt_matrix(-np.eye(m))
  h = cvxopt_matrix(np.zeros(m))
  A = cvxopt_matrix(y.reshape(1, -1))
  b = cvxopt_matrix(np.zeros(1))

#Setting solver parameters (change default to decrease tolerance)
  cvxopt_solvers.options['show_progress'] = False
  cvxopt_solvers.options['abstol'] = 1e-10
  cvxopt_solvers.options['reltol'] = 1e-10
  cvxopt_solvers.options['feastol'] = 1e-10
#Run solver
  sol = cvxopt_solvers.qp(P, q, G, h, A, b)
  alphas = np.array(sol['x'])
#w parameter in vectorized form
  w = ((y * alphas).T @ X).reshape(-1,1)
#Selecting the set of indices S corresponding to non zero parameters
  S = (alphas > 1e-4).flatten()
#Computing b
  b1 = y[S] - np.dot(X[S], w)
#Display results
#print('Alphas = ',alphas[alphas > 1e-4])
 #print('w = ', w.flatten())
 #print('b = ', b[0])
  return(w, b1)
pre=fit(X=X, y=y)

错误报告是ValueError: domain error......

标签: pythonsvm

解决方案


推荐阅读