Sklearn 支持向量机(SVM)
sklearn.svm 提供 SVC、SVR、NuSVC、NuSVR、OneClassSVM、LinearSVC、LinearSVR。
🏷️ 分类 SVM
1. SVC --- 支持向量分类器 ⭐
python
from sklearn.svm import SVC
model = SVC(
C=1.0, # 正则化参数(越大越拟合训练集)
kernel='rbf', # 'linear','poly','rbf','sigmoid','precomputed'
degree=3, # 多项式核的次数
gamma='scale', # 核系数
# 'scale'=1/(n_features*X.var())
# 'auto'=1/n_features
# float=自定义值(越大拟合越紧)
coef0=0.0, # 独立项(poly 和 sigmoid 核)
shrinking=True, # 启发式收缩加速
probability=False, # 是否启用概率估计(额外 5-fold CV,较慢)
tol=1e-3,
cache_size=200, # 核缓存(MB)
class_weight=None, # None 或 'balanced' 或 dict
verbose=False,
max_iter=-1, # -1=无限制
decision_function_shape='ovr', # 'ovr'(一对多) 或 'ovo'(一对一)
break_ties=False, # 决策函数平票时预测第一类
random_state=None
)
model.fit(X, y)
# 关键属性
print(model.support_) # 支持向量的索引
print(model.support_vectors_) # 支持向量(按索引顺序)
print(model.n_support_) # 每类的支持向量数量
print(model.dual_coef_) # 对偶空间中支持向量的系数
print(model.coef_) # 仅 linear 核时可用
print(model.intercept_) # 决策函数中的截距
print(model.classes_) # 类别标签
print(model.n_features_in_) # 特征数
print(model.fit_status_) # 0=正确拟合
print(model.shape_fit_) # 拟合的 (n_SV, n_features)
# 预测方法
y_pred = model.predict(X)
y_score = model.decision_function(X) # 到超平面的距离
# 概率(需 probability=True 训练)
y_prob = model.predict_proba(X)
y_log_prob = model.predict_log_proba(X)
2. LinearSVC --- 线性支持向量分类器
比 SVC(kernel='linear') 更快,尤其适合大数据和稀疏数据。
python
from sklearn.svm import LinearSVC
model = LinearSVC(
penalty='l2', # 'l1' 或 'l2'
loss='squared_hinge', # 'hinge' 或 'squared_hinge'
dual='auto', # True/False/'auto'(样本>特征时选False)
tol=1e-4,
C=1.0,
multi_class='ovr', # 'ovr' 或 'crammer_singer'
fit_intercept=True,
intercept_scaling=1,
class_weight=None,
verbose=0,
random_state=None,
max_iter=1000
)
model.fit(X, y)
print(model.coef_)
print(model.intercept_)
y_pred = model.predict(X)
y_score = model.decision_function(X)
3. NuSVC --- Nu-支持向量分类器
用参数 nu 替代 C 来控制支持向量的数量。
python
from sklearn.svm import NuSVC
model = NuSVC(
nu=0.5, # 支持向量比例上界 + 训练误差上界 (0 < nu ≤ 1)
kernel='rbf',
degree=3,
gamma='scale',
coef0=0.0,
shrinking=True,
probability=False,
tol=1e-3,
cache_size=200,
class_weight=None,
verbose=False,
max_iter=-1,
decision_function_shape='ovr',
break_ties=False,
random_state=None
)
model.fit(X, y)
📈 回归 SVM
1. SVR --- 支持向量回归器 ⭐
python
from sklearn.svm import SVR
model = SVR(
kernel='rbf',
degree=3,
gamma='scale',
coef0=0.0,
tol=1e-3,
C=1.0,
epsilon=0.1, # ε-不敏感带的宽度(管状回归)
shrinking=True,
cache_size=200,
verbose=False,
max_iter=-1
)
model.fit(X, y)
print(model.support_)
print(model.support_vectors_)
print(model.dual_coef_)
print(model.coef_) # 仅 linear 核
print(model.intercept_)
print(model.n_support_)
y_pred = model.predict(X)
2. LinearSVR --- 线性支持向量回归器
python
from sklearn.svm import LinearSVR
model = LinearSVR(
epsilon=0.0,
tol=1e-4,
C=1.0,
loss='epsilon_insensitive', # 'epsilon_insensitive' 或 'squared_epsilon_insensitive'
fit_intercept=True,
intercept_scaling=1.0,
dual='auto',
verbose=0,
random_state=None,
max_iter=1000
)
model.fit(X, y)
3. NuSVR --- Nu-支持向量回归器
python
from sklearn.svm import NuSVR
model = NuSVR(
nu=0.5,
C=1.0,
kernel='rbf',
degree=3,
gamma='scale',
coef0=0.0,
shrinking=True,
tol=1e-3,
cache_size=200,
verbose=False,
max_iter=-1
)
model.fit(X, y)
🕵️ 异常检测
OneClassSVM --- 单类 SVM
python
from sklearn.svm import OneClassSVM
model = OneClassSVM(
kernel='rbf',
degree=3,
gamma='scale',
coef0=0.0,
tol=1e-3,
nu=0.5, # 异常比例上界(训练误差下界)(0 < nu ≤ 1)
shrinking=True,
cache_size=200,
verbose=False,
max_iter=-1
)
model.fit(X)
# 预测: 1=正常, -1=异常
y_pred = model.predict(X)
scores = model.decision_function(X) # 到分离超平面的带符号距离
# 获取支持向量信息
print(model.support_)
print(model.support_vectors_)
print(model.n_support_)
print(model.dual_coef_)
print(model.intercept_)
🎛️ 核函数详解
python
# 线性核: K(x, y) = xᵀy
SVC(kernel='linear') # 最简单最快
LinearSVC() # 大规模线性分类更优
# 多项式核: K(x, y) = (γxᵀy + r)^d
SVC(kernel='poly', degree=3, gamma='scale', coef0=0)
# RBF 核(高斯核): K(x, y) = exp(-γ||x-y||²)
SVC(kernel='rbf', gamma='scale') # 默认,最通用
# Sigmoid 核: K(x, y) = tanh(γxᵀy + r)
SVC(kernel='sigmoid', gamma='scale', coef0=0)
# 自定义核(预计算核矩阵)
gram_matrix = compute_custom_kernel(X)
SVC(kernel='precomputed').fit(gram_matrix, y)
📊 Gamma 与 C 的影响
| 参数 | 过大 | 过小 |
|---|---|---|
| C | 过拟合(每个点都分类正确) | 欠拟合(允许大量错误) |
| gamma | 过拟合(高方差,复杂边界) | 欠拟合(高偏差,简单边界) |
调参模板
python
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
import numpy as np
param_grid = {
'C': np.logspace(-3, 3, 7), # 0.001 ... 1000
'gamma': np.logspace(-3, 3, 7), # 0.001 ... 1000
'kernel': ['rbf', 'linear']
}
svc = SVC(random_state=42)
grid = GridSearchCV(svc, param_grid, cv=5, scoring='accuracy', n_jobs=-1)
grid.fit(X_train, y_train)
print(f"Best: {grid.best_params_}, Score: {grid.best_score_:.3f}")
📝 实践指导
使用流程
python
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split, GridSearchCV
# 1. 分割数据
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# 2. 构建管道(SVM 必须标准化!)
pipeline = make_pipeline(
StandardScaler(),
SVC(random_state=42)
)
# 3. 调参
param_grid = {
'svc__C': [0.1, 1, 10, 100],
'svc__gamma': ['scale', 'auto', 0.01, 0.1, 1],
'svc__kernel': ['rbf', 'linear']
}
grid = GridSearchCV(pipeline, param_grid, cv=5, n_jobs=-1, verbose=1)
grid.fit(X_train, y_train)
# 4. 最终评估
print(f"Test score: {grid.score(X_test, y_test):.3f}")
print(f"Best params: {grid.best_params_}")
适用场景
| 场景 | 推荐 |
|---|---|
| 中小数据集 + 非线性 | SVC(kernel='rbf') |
| 大数据集 + 线性可分 | LinearSVC |
| 特征数 >> 样本数 | LinearSVC(或 LogisticRegression) |
| 需要概率输出 | SVC(probability=True) |
| 控制支持向量比例 | NuSVC |
| 异常检测/新颖检测 | OneClassSVM |
| 回归 + 非线性 | SVR(kernel='rbf') |
⚠️ 重要注意事项
- 必须标准化 : SVM 对特征尺度非常敏感,务必先
StandardScaler - 样本量大时慢 : RBF 核复杂度 O(n²)~O(n³),大样本用
LinearSVC或近似方法 - 概率估计额外开销 :
probability=True会执行 5 折交叉验证 - 不平衡数据 : 设置
class_weight='balanced'
\[sklearn-总览\|← 返回总览\]