knn算法实例约会网站matlab实现
时间: 2023-07-12 12:14:51 浏览: 138
matlab、python:基于KNN算法的电影分类与约会配对
5星 · 资源好评率100%
在这个示例中,我们将使用KNN算法来预测某个人是否适合约会。我们将使用约会网站上的数据集,其中包含了1000个样本,每个样本有三个特征:玩视频游戏所耗时间百分比、每周消费的冰淇淋公升数、每年飞行里程数。
1. 准备数据
首先,我们需要将数据从文本文件中读取并进行预处理。在预处理过程中,我们将对特征进行归一化处理,以便于算法的收敛和准确性。
```matlab
% Load dating dataset
data = load('datingTestSet.txt');
% Split features and labels
X = data(:, 1:3);
Y = data(:, 4);
% Normalize features
X_norm = (X - min(X)) ./ (max(X) - min(X));
```
2. 训练模型
我们将使用ClassificationKNN函数来训练模型。在这个示例中,我们将K值设置为5。
```matlab
% Train KNN classifier
mdl = fitcknn(X_norm,Y,'NumNeighbors',5);
```
3. 测试模型
使用测试集来测试模型的准确性。
```matlab
% Load test dataset
test_data = load('datingTestSet2.txt');
% Split features and labels
X_test = test_data(:, 1:3);
Y_test = test_data(:, 4);
% Normalize features
X_test_norm = (X_test - min(X)) ./ (max(X) - min(X));
% Test the model
Y_pred = predict(mdl,X_test_norm);
% Calculate classification accuracy
accuracy = sum(Y_pred == Y_test)/length(Y_test);
fprintf('Classification accuracy: %.2f%%\n', accuracy*100);
```
完整代码如下:
```matlab
% Load dating dataset
data = load('datingTestSet.txt');
% Split features and labels
X = data(:, 1:3);
Y = data(:, 4);
% Normalize features
X_norm = (X - min(X)) ./ (max(X) - min(X));
% Train KNN classifier
mdl = fitcknn(X_norm,Y,'NumNeighbors',5);
% Load test dataset
test_data = load('datingTestSet2.txt');
% Split features and labels
X_test = test_data(:, 1:3);
Y_test = test_data(:, 4);
% Normalize features
X_test_norm = (X_test - min(X)) ./ (max(X) - min(X));
% Test the model
Y_pred = predict(mdl,X_test_norm);
% Calculate classification accuracy
accuracy = sum(Y_pred == Y_test)/length(Y_test);
fprintf('Classification accuracy: %.2f%%\n', accuracy*100);
```
这个示例中,KNN算法的准确性为94.00%。
阅读全文