高光谱数据分类支持向量机的matlab代码
时间: 2023-11-15 21:10:11 浏览: 228
以下是使用支持向量机(SVM)对高光谱数据进行分类的MATLAB代码示例:
首先,我们需要导入高光谱数据和标签:
```matlab
load('Indian_pines_corrected.mat'); % 高光谱数据
load('Indian_pines_gt.mat'); % 标签
data = indian_pines_corrected;
labels = indian_pines_gt;
```
然后,我们需要将数据准备好,将其转换为2D数组,以便用于SVM:
```matlab
data = reshape(data, [], size(data, 3));
labels = reshape(labels, [], 1);
```
接下来,我们将数据拆分为训练集和测试集:
```matlab
% 设置训练集和测试集的比例
train_ratio = 0.7;
% 随机拆分数据集
idx = randperm(size(data, 1));
train_idx = idx(1:round(train_ratio*size(data, 1)));
test_idx = idx(round(train_ratio*size(data, 1))+1:end);
% 拆分数据
train_data = data(train_idx, :);
train_labels = labels(train_idx);
test_data = data(test_idx, :);
test_labels = labels(test_idx);
```
现在,我们可以使用SVM进行分类。在这个例子中,我们将使用libsvm库(需要先安装),并使用径向基函数(RBF)作为内核:
```matlab
% 安装libsvm库
addpath('libsvm-3.24/matlab');
% 训练SVM模型
model = svmtrain(train_labels, train_data, '-t 2 -g 0.05');
% 使用训练好的模型进行测试
[predicted_labels, accuracy, decision_values] = svmpredict(test_labels, test_data, model);
```
最后,我们可以计算分类的准确率:
```matlab
% 计算准确率
correct = sum(predicted_labels == test_labels);
total = numel(test_labels);
accuracy = correct/total;
disp(['Accuracy: ', num2str(accuracy)]);
```
完整的代码示例如下:
```matlab
% 导入数据
load('Indian_pines_corrected.mat');
load('Indian_pines_gt.mat');
data = indian_pines_corrected;
labels = indian_pines_gt;
% 将数据转换为2D数组
data = reshape(data, [], size(data, 3));
labels = reshape(labels, [], 1);
% 拆分数据集
train_ratio = 0.7;
idx = randperm(size(data, 1));
train_idx = idx(1:round(train_ratio*size(data, 1)));
test_idx = idx(round(train_ratio*size(data, 1))+1:end);
train_data = data(train_idx, :);
train_labels = labels(train_idx);
test_data = data(test_idx, :);
test_labels = labels(test_idx);
% 训练SVM模型
addpath('libsvm-3.24/matlab');
model = svmtrain(train_labels, train_data, '-t 2 -g 0.05');
% 使用训练好的模型进行测试
[predicted_labels, accuracy, decision_values] = svmpredict(test_labels, test_data, model);
% 计算准确率
correct = sum(predicted_labels == test_labels);
total = numel(test_labels);
accuracy = correct/total;
disp(['Accuracy: ', num2str(accuracy)]);
```
阅读全文