用matlab实现的svdd算法
基于MATLAB实现的支持向量数据描述(Support Vector Data Description, SVDD)算法
1. SVDD算法核心实现
function [model, decision] = mySVDD(X, kernelType, gamma, C, tol)
% X: 训练数据 (N x D)
% kernelType: 核函数类型 ('linear', 'poly', 'rbf')
% gamma: RBF核参数 (仅对'rbf'有效)
% C: 正则化参数
% tol: 支持向量容忍度[N, D] = size(X);
K = computeKernel(X, X, kernelType, gamma);% 构建二次规划参数
H = (1/C) * K + eye(N);
f = -ones(N, 1);
Aeq = ones(1, N);
beq = 1;
lb = zeros(N, 1);
ub = inf(N, 1);% 求解二次规划
options = optimoptions('quadprog', 'Display', 'off');
alpha = quadprog(H, f, [], [], Aeq, beq, lb, ub, [], options);% 提取支持向量
svIdx = alpha > tol & alpha < 1 - tol;
supportVectors = X(svIdx, :);
alpha_sv = alpha(svIdx);% 计算偏置项b
b = mean(1 - sum((alpha_sv .* (1 - alpha_sv)) .* K(svIdx, svIdx), 1));% 构建决策函数
model.alpha = alpha_sv;
model.supportVectors = supportVectors;
model.kernelType = kernelType;
model.gamma = gamma;
model.b = b;% 生成决策网格
[x1Grid, x2Grid] = meshgrid(linspace(min(X(:,1))-1, max(X(:,1))+1, 100), ...linspace(min(X(:,2))-1, max(X(:,2))+1, 100));
decision = zeros(size(x1Grid));for i = 1:numel(x1Grid)x = [x1Grid(i), x2Grid(i)]';decision(i) = predictSVDD(x, model);
end
endfunction K = computeKernel(X1, X2, type, gamma)
% 计算核矩阵
switch typecase 'linear'K = X1 * X2';case 'poly'K = (X1 * X2' + 1).^2;case 'rbf'dist = pdist2(X1, X2).^2;K = exp(-gamma * dist);
end
endfunction y = predictSVDD(x, model)
% 预测新样本类别
y = 0;
for i = 1:length(model.alpha)y = y + model.alpha(i) * kernelFunc(x, model.supportVectors(i,:), ...model.kernelType, model.gamma);
end
y = y + model.b;
endfunction K = kernelFunc(x1, x2, type, gamma)
% 单样本核函数计算
switch typecase 'linear'K = x1 * x2';case 'poly'K = (x1 * x2' + 1).^2;case 'rbf'K = exp(-gamma * norm(x1 - x2)^2);
end
end
2. 示例使用与可视化
%% 生成示例数据(半圆形分布)
theta = linspace(0, 2*pi, 100)';
X = [cos(theta), sin(theta)]; % 外圆边界
X = [X; 0.5*ones(50,1), 0.5*ones(50,1)]; % 内圆异常点%% 训练SVDD模型
kernelType = 'rbf'; % 核函数类型
gamma = 10; % RBF核参数
C = 1; % 正则化参数
tol = 1e-3; % 支持向量容忍度[model, decision] = mySVDD(X, kernelType, gamma, C, tol);%% 可视化结果
figure;
hold on;
scatter(X(:,1), X(:,2), 'b.'); % 原始数据
scatter(model.supportVectors(:,1), model.supportVectors(:,2), 'ro', 'LineWidth', 2); % 支持向量
contour(squeeze(x1Grid), squeeze(x2Grid), reshape(decision, size(x1Grid)), [0 0], 'k', 'LineWidth', 2); % 决策边界
title('SVDD分类结果');
legend('正常点', '支持向量', '决策边界');
axis equal;
hold off;
3. 关键参数说明
参数 | 说明 |
---|---|
kernelType | 核函数类型:linear (线性)、poly (多项式)、rbf (高斯核) |
gamma | RBF核参数(值越大模型越复杂,易过拟合) |
C | 正则化参数(值越大对误分类惩罚越重,可能过拟合) |
tol | 支持向量判定阈值(小于该值的α被视为非支持向量) |
参考代码 svdd分类 用matlab实现的svdd算法 www.youwenfan.com/contentcsc/63615.html
4. 扩展与优化建议
- 多类扩展:通过"one-class vs one-class"或"one-class vs rest"策略扩展至多类
- 参数调优:使用网格搜索优化
C
和gamma
- 核改进:实现混合核函数(如线性+RBF)
- 增量学习:添加数据更新机制处理流式数据
- 异常评分:输出样本到决策边界的距离作为异常分数
5. 算法性能分析
- 时间复杂度:主要取决于二次规划求解,约O(N³)
- 空间复杂度:存储核矩阵需要O(N²)空间
- 适用场景:小到中等规模数据(N < 10,000),高维非线性数据