python - ValueError:使用 cvxopt 进行 SVM 的域错误?
问题描述
我尝试使用 cvxopt 进行优化并使用iris
数据集。我定义了一个函数fit(X, y)
,输入X
和y
输出权重w
和b
。但是为什么会出现错误?
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
......
解决方案
推荐阅读
- jupyter-notebook - 有没有办法将另一个笔记本中的函数导入 AWS EMR 笔记本?
- python - CatBoost __init__() 得到了一个意外的关键字参数 'silent'
- c - 链接列表上的冒泡排序在交换期间删除元素
- reactjs - 输入 React props 返回错误
- kubernetes - 在 AKS 中用入口替换 haproxy
- python - 使用curl时如何在ubuntu 20.04中解决“无法获取本地颁发者证书(_ssl.c:1123)”?
- c# - Unity C# IOS 滑动检测
- events - Google 活动中的 Zoom 会议地址
- reactjs - useRef TypeScript - 不可分配给类型 LegacyRef
- git - 多平台 git 策略是怎样的?