基于MATLAB实现支持向量机(SVM)分类

一、基础SVM分类代码示例

1. 使用fitcsvm函数(推荐新版MATLAB)
matlab 复制代码
% 加载数据集(以鸢尾花为例)
load fisheriris;
X = meas(:,1:2); % 选取前两个特征
Y = species;

% 划分训练集和测试集(70%训练,30%测试)
cv = cvpartition(Y, 'HoldOut', 0.3);
X_train = X(cv.training,:);
Y_train = Y(cv.training);
X_test = X(cv.test,:);
Y_test = Y(cv.test);

% 训练SVM模型(使用RBF核)
svmModel = fitcsvm(X_train, Y_train, ...
    'KernelFunction', 'rbf', ...  % 核函数类型
    'KernelScale', 'auto', ...    % 自动调整核参数
    'Standardize', true, ...      % 数据标准化
    'BoxConstraint', 1);        % 正则化参数C

% 预测与评估
Y_pred = predict(svmModel, X_test);
accuracy = sum(Y_pred == Y_test) / numel(Y_test);
disp(['分类准确率: ', num2str(accuracy*100), '%']);
2. 传统svmtrain/svmclassify函数(旧版MATLAB)
matlab 复制代码
% 数据准备(示例为二维线性可分数据)
X = [1 2; 2 3; 3 3; 6 8; 7 8; 8 9]; % 特征矩阵
Y = [1 1 1 -1 -1 -1]; % 类别标签

% 训练SVM模型
model = svmtrain(X, Y, 'Kernel_Function', 'linear', 'ShowPlot', true);

% 预测新样本
newData = [4,5; 5,6];
predictedLabels = svmclassify(model, newData);
disp('预测结果:');
disp(predictedLabels);

二、关键参数与优化方法

  1. 核函数选择

    • 线性核:适用于线性可分数据,计算效率高。
    • RBF核(高斯核) :适用于非线性问题,需调整KernelScale参数。
    • 多项式核 :需设置PolynomialOrder参数,适合特定非线性分布。
  2. 参数调优

    • 正则化参数C:控制分类间隔与误分类惩罚的平衡,可通过交叉验证选择。
    • 核参数(如gamma) :RBF核中gamma越大,模型越关注局部数据。
    • 标准化 :建议启用Standardize选项,避免特征尺度差异影响结果。
  3. 交叉验证与网格搜索

    matlab 复制代码
    % 使用交叉验证优化参数
    SVMModel = fitcsvm(X_train, Y_train, ...
        'OptimizeHyperparameters', 'auto', ...
        'HyperparameterOptimizationOptions', ...
        struct('AcquisitionFunctionName', 'expected-improvement-plus'));

SVM支持向量机分类matlab代码,SVM解决分类问题 youwenfan.com/contentcsb/101445.html

三、数据预处理与评估

  1. 数据归一化

    matlab 复制代码
    [X_scaled, ps_input] = mapminmax(X', 0, 1); % 归一化到[0,1]
    X_scaled = X_scaled';
  2. 性能评估指标

    matlab 复制代码
    % 混淆矩阵
    C = confusionchart(Y_test, Y_pred);
    % 分类报告
    classificationReport = classificationReport(Y_test, Y_pred);

四、多分类问题扩展

MATLAB支持通过以下方式扩展SVM至多分类:

  1. 一对多(One-vs-All)

    matlab 复制代码
    SVMModel = fitcecoc(X_train, Y_train, 'Learners', 'svm', 'Coding', 'onevsall');
  2. 一对一(One-vs-One)

    matlab 复制代码
    SVMModel = fitcecoc(X_train, Y_train, 'Learners', 'svm', 'Coding', 'onevsone');

五、注意事项

  1. 样本平衡 :若类别不平衡,可通过ClassNames参数调整权重或使用fitcsvmPrior选项。
  2. 大规模数据:SVM对内存敏感,建议使用线性核或降维(如PCA)处理高维数据。
  3. 模型解释性 :线性核模型可通过coef0SVMModel.SupportVectors分析支持向量。