Using SVM in matlab for data classification prediction

The sample code for data classification prediction using support vector machine (SVM) in MATLAB is as follows:

% 准备数据集,假设有一个矩阵X用于存储特征,一个向量Y用于存储标签
% X的每一行是一个样本的特征向量,Y的每个元素对应X对应样本的标签

% 假设特征矩阵X为 1000x3 的数据,标签向量Y为 1000x1 的数据
X = rand(1000, 3);
Y = randi([0, 1], 1000, 1);

% 拆分数据集为训练集和测试集,这里按照 70% 的比例划分数据
trainRatio = 0.7;
[trainInd, ~, testInd] = dividerand(size(X, 1), trainRatio, 0, 1);
XTrain = X(trainInd, :);
YTrain = Y(trainInd, :);
XTest = X(testInd, :);
YTest = Y(testInd, :);

% 建立支持向量机(SVM)模型并设置参数
svmModel = fitcsvm(XTrain, YTrain, 'KernelFunction', 'linear');

% 使用模型进行预测
YTestPredicted = predict(svmModel, XTest);

% 评估模型性能
accuracy = sum(YTestPredicted == YTest) / length(YTest);
disp(['Accuracy: ', num2str(accuracy)]);

% 可以根据需要进行模型调参和优化,例如选择其他核函数、调整参数C等

The example code assumes that you already have the feature matrix X and the corresponding label vector Y. First, the dataset is divided into training and testing sets. Then, use fitcsvmthe function to build a support vector machine (SVM) model, and set related parameters, such as kernel functions. Next, use the trained model to make predictions on the test set, and calculate the prediction accuracy as a performance evaluation indicator.

According to your data set and problem, you can adjust and optimize the model parameters as needed, such as trying different kernel functions, adjusting the regularization parameter C, etc. to improve model performance and prediction accuracy.

Guess you like

Origin blog.csdn.net/weixin_44463965/article/details/131674552