Python 使用SVM模型运行交叉验证时的收敛警告

Python 使用SVM模型运行交叉验证时的收敛警告,python,machine-learning,scikit-learn,svm,Python,Machine Learning,Scikit Learn,Svm,我试图训练一个LinearSVC模型,并在我创建的一个线性可分离数据集上使用交叉值对其进行评估,但我得到了一个错误 以下是一个可复制的示例: from sklearn.model_selection import cross_val_score, train_test_split from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC import matplotlib.pyplot

我试图训练一个LinearSVC模型,并在我创建的一个线性可分离数据集上使用
交叉值
对其进行评估,但我得到了一个错误

以下是一个可复制的示例:

from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


# creating the dataset
x1          = 2 * np.random.rand(100, 1)
y1          = 5 + 3 * x1 + np.random.randn(100, 1)
lable1  = np.zeros((100, 1))

x2          = 2 * np.random.rand(100, 1)
y2          = 15 + 3 * x2 + np.random.randn(100, 1)
lable2  = np.ones((100, 1))

x       = np.concatenate((x1, x2))
y       = np.concatenate((y1, y2))
lable = np.concatenate((lable1, lable2))

x       = np.reshape(x, (len(x),))
y       = np.reshape(y, (len(y),))
lable = np.reshape(lable, (len(lable),))

d   = {'x':x, 'y':y, 'lable':lable}
df  = pd.DataFrame(data=d)
df.plot(kind="scatter", x="x", y="y")



# preparing data and model
train_set, test_set = train_test_split(df, test_size=0.2, random_state=42)
X = train_set.drop("lable", axis=1)
y = train_set["lable"].copy()

scaler = StandardScaler()
scaler.fit_transform(X)

linear_svc = LinearSVC(C=5, loss="hinge", random_state=42)
linear_svc.fit(X, y)



# evaluation
scores = cross_val_score(linear_svc, X, y, scoring="neg_mean_squared_error", cv=10)
rmse_scores = np.sqrt(-scores)
print("Mean:", rmse_scores.mean())

输出:

平均值:0.0

/usr/local/lib/python3.7/dist packages/sklearn/svm/_base.py:947:ConvergenceWarning:Liblinear无法收敛,请增加迭代次数。 “迭代次数。”,收敛警告)


这不是一个错误,而是一个警告,它已经包含了一些建议:

增加迭代次数

默认值为1000()

此外,
LinearSVC
是一个分类器,因此在
交叉值评分中使用
评分=“负均方误差”(即回归度量)毫无意义;有关每种问题的相关指标的粗略列表,请参见

因此,有以下变化:

linear_svc = LinearSVC(C=5, loss="hinge", random_state=42, max_iter=100000)
scores = cross_val_score(linear_svc, X, y, scoring="accuracy", cv=10)
您的代码运行正常,没有任何错误或警告