matlab做SVM分类 ,数据样本为csv文件(被试的时间序列),提取相关矩阵作为特征并用SVM进行二分类
程序员文章站
2022-05-26 19:10:02
...
clc
clear
diagnose = csvread('labels.csv');%读取标签文件
mydir = 'F:\fmri\fmri\AD_NC\ts\';%数据所在路径
dList = dir([mydir ,'*.csv']);%数据列表
n = length(dList);
for i=1:n
filename = load(dList(i).name);%读取数据
filename1 = filename(1:170,:);%截取1-170行(也可以截取任意自己需要的)
for k = 1:263 %做皮尔逊列相关
for t = 1:263
x = filename1(:,k);
y = filename1(:,t);
corr_per(k,t) =corr(x,y,'type','Pearson');
end
end
corr_abs = abs(corr_per);%对相关矩阵取绝对值
shangsanjiao = tril(corr_abs);%取上三角
gen = double((shangsanjiao(:,:) >= 0.5) == 1);
gen = double((shangsanjiao(:,:) < 0.5) == 0);%二值化(这里要用double强制转换类型,否则为逻辑型)
[heng, zong] = size(gen);
file_name = reshape(gen,1,heng*zong);%拉成一行
data(i,:) = file_name;%把所有被试的相关阵放到一起,每一行代表一个样本
end
将读入的数据和标签存为.mat格式,并送入SVM
load('data.mat')
load('diagnose.mat')
X = data;
Y = diagnose;
testRatio = 0.2;% 测试数据占全部数据的比例
trainIndices = crossvalind('HoldOut', size(X, 1), testRatio);% 训练集索引
testIndices = ~trainIndices;% 测试集索引
train_data = X(trainIndices, :);% 训练集和训练标签
train_label = Y(trainIndices, :);
test_data = X(testIndices, :);% 测试集和测试标签
test_label = Y(testIndices, :);
SVMModel = fitcsvm(train_data,train_label,...
'BoxConstraint',0.1,...
'CacheSize','maximal',...
'ClipAlphas',true,...
'DeltaGradientTolerance',1e-4,...
'KernelFunction','linear') %训练分类器
CVSVMModel = crossval(SVMModel); %分类器的交叉验证
classLoss = kfoldLoss(CVSVMModel) % 样本内错误率
[asd,score] = predict(SVMModel,test_data); %样本外的数据进行分类预测
[label,scorePred] = kfoldPredict(CVSVMModel); %样本外的数据进行分类预测结果,
fprintf('accuracy:%f\n' ,sum(asd==test_label)/size(test_label,1));