ClassificationSVM的例子 matlab
时间: 2024-05-16 19:16:40 浏览: 16
以下是使用MATLAB中的ClassificationSVM函数进行分类的例子:
1. 准备数据集
我们首先需要准备一个数据集,例如一个由两个类别组成的二元分类问题。这里我们使用MATLAB内置的鸢尾花数据集。
```matlab
load fisheriris
X = meas(:, 3:4); %选取花瓣长度和花瓣宽度两个特征
Y = (strcmpi('versicolor', species) | strcmpi('virginica', species)) + 1; %将两个类别合并为一类
```
2. 划分训练集和测试集
为了评估分类器的性能,我们需要将数据集划分为训练集和测试集。这里我们将70%的数据用于训练,并将其余的30%用于测试。
```matlab
cv = cvpartition(Y, 'HoldOut', 0.3); %创建一个hold-out交叉验证对象
idxTrain = training(cv); %获取训练集索引
idxTest = test(cv); %获取测试集索引
XTrain = X(idxTrain, :); %获取训练集数据
YTrain = Y(idxTrain); %获取训练集标签
XTest = X(idxTest, :); %获取测试集数据
YTest = Y(idxTest); %获取测试集标签
```
3. 训练分类器
现在我们可以使用ClassificationSVM函数训练一个分类器。这里我们使用线性核函数,并设置正则化参数C为1。
```matlab
mdl = fitcsvm(XTrain, YTrain, 'KernelFunction', 'linear', 'BoxConstraint', 1);
```
4. 预测
训练完成后,我们可以使用训练好的分类器对测试集进行预测,并计算预测精度。
```matlab
YTestPred = predict(mdl, XTest); %对测试集进行预测
accuracy = sum(YTestPred == YTest) / numel(YTest); %计算预测精度
disp(['Accuracy: ' num2str(accuracy)]);
```
完整代码如下:
```matlab
load fisheriris
X = meas(:, 3:4); %选取花瓣长度和花瓣宽度两个特征
Y = (strcmpi('versicolor', species) | strcmpi('virginica', species)) + 1; %将两个类别合并为一类
cv = cvpartition(Y, 'HoldOut', 0.3); %创建一个hold-out交叉验证对象
idxTrain = training(cv); %获取训练集索引
idxTest = test(cv); %获取测试集索引
XTrain = X(idxTrain, :); %获取训练集数据
YTrain = Y(idxTrain); %获取训练集标签
XTest = X(idxTest, :); %获取测试集数据
YTest = Y(idxTest); %获取测试集标签
mdl = fitcsvm(XTrain, YTrain, 'KernelFunction', 'linear', 'BoxConstraint', 1); %使用线性核函数训练分类器
YTestPred = predict(mdl, XTest); %对测试集进行预测
accuracy = sum(YTestPred == YTest) / numel(YTest); %计算预测精度
disp(['Accuracy: ' num2str(accuracy)]);
```
这个例子演示了如何使用ClassificationSVM函数进行二元分类。如果你想进行多元分类,可以使用fitcecoc函数。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)