-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_svm_poly.m
50 lines (42 loc) · 1.48 KB
/
train_svm_poly.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
%% load data
% loadData
clear;
load('data/W2Vtrain2000-300.mat');
load('data/W2Vtest2000-300.mat');
disp('SVM Polynomial Kernel');
trainLabel = double(trainLabel);
testLabel = double(testLabel);
trainMatrix = double(trainMatrix);
testMatrix = double(testMatrix);
numOfClass = 8;
numTrain = size(trainMatrix, 1);
numTest = size(testMatrix, 1);
results = ones(numTest, 1);
% Normalize
for i = 1:numTrain
trainMatrix(i,:) = trainMatrix(i,:) / norm(trainMatrix(i,:));
end
for i = 1:numTest
testMatrix(i,:) = testMatrix(i,:) / norm(testMatrix(i,:));
end
%% Algorithm
t = templateSVM('KernelFunction','polynomial','KernelScale','auto');
% t = templateSVM('KernelFunction','linear','KernelScale','auto');
model = fitcecoc(trainMatrix, trainLabel, 'Learners', t);
prediction = predict(model, trainMatrix);
fprintf('train accuracy: %f\n',sum(abs(prediction - trainLabel)==0)/size(trainLabel, 1));
test_prediction = predict(model, testMatrix);
disp('prediction result');
disp([testLabel test_prediction])
fprintf('test accuracy: %f\n', sum(abs(int16(test_prediction) - int16(testLabel))<=1)/size(testLabel,1));
corr = corrcoef(double(testLabel), double(test_prediction));
fprintf('correlation: %f\n', corr(2,1));
% plot graph
plot(testLabel,test_prediction, 'bo')
coeffs = polyfit(testLabel, test_prediction, 1);
% Get fitted values
fittedX = linspace(min(testLabel), max(test_prediction), 200);
fittedY = polyval(coeffs, fittedX);
% Plot the fitted line
hold on;
plot(fittedX, fittedY, 'r-', 'LineWidth', 3);