重写这段代码,但完成相同的功能,尽量让人看不出来重写的代码和原先代码是一样的
时间: 2023-07-10 16:33:34 浏览: 117
重构 refacting the existing code
好,以下是重写后的代码,仍然针对 MNIST 手写数字数据集进行朴素贝叶斯分类器的训练和测试,但实现方式有所不同。新代码将训练和测试数据加载进来,以及将图像转换为向量的功能合并为一个函数,使用 fitcnb 函数训练朴素贝叶斯分类器并进行测试,最后输出测试结果的准确率和可视化结果。
```matlab
function [acc] = nb_classification()
% 加载 MNIST 数据
mnist = loadMNIST();
train_images = mnist.train_images;
train_labels = mnist.train_labels;
test_images = mnist.test_images;
test_labels = mnist.test_labels;
% 训练数据和测试数据的数量
train_num = 600;
test_num = 200;
% 将图像转换为向量
data_train = reshape(train_images(:,:,1:train_num),[],train_num)';
data_test = reshape(test_images(:,:,1:test_num),[],test_num)';
% 训练朴素贝叶斯分类器
Mdl = fitcnb(data_train,train_labels(1:train_num));
% 测试结果
result = predict(Mdl,data_test);
acc = sum(result==test_labels(1:test_num))/test_num;
% 可视化结果
xlabel = [0:9];
resultbar = histcounts(result,xlabel+0.5);
testbar = histcounts(test_labels(1:test_num),xlabel+0.5);
bar(xlabel, [resultbar' testbar']);
title(['精确度为:',num2str(acc*100),'%']);
end
function [mnist] = loadMNIST()
% 加载 MNIST 数据
mnist = struct();
mnist.train_images = loadMNISTImages('train-images-idx3-ubyte');
mnist.train_labels = loadMNISTLabels('train-labels-idx1-ubyte');
mnist.test_images = loadMNISTImages('t10k-images-idx3-ubyte');
mnist.test_labels = loadMNISTLabels('t10k-labels-idx1-ubyte');
end
function [images] = loadMNISTImages(filename)
% 读取 MNIST 图像数据
fp = fopen(filename, 'rb');
assert(fp ~= -1, ['Could not open ', filename, '']);
magic = fread(fp, 1, 'int32', 0, 'ieee-be');
assert(magic == 2051, ['Bad magic number in ', filename, '']);
num_images = fread(fp, 1, 'int32', 0, 'ieee-be');
num_rows = fread(fp, 1, 'int32', 0, 'ieee-be');
num_cols = fread(fp, 1, 'int32', 0, 'ieee-be');
images = fread(fp, inf, 'unsigned char');
fclose(fp);
images = reshape(images, num_cols, num_rows, num_images);
images = permute(images,[2 1 3]);
images = double(images)/255;
end
function [labels] = loadMNISTLabels(filename)
% 读取 MNIST 标签数据
fp = fopen(filename, 'rb');
assert(fp ~= -1, ['Could not open ', filename, '']);
magic = fread(fp, 1, 'int32', 0, 'ieee-be');
assert(magic == 2049, ['Bad magic number in ', filename, '']);
num_labels = fread(fp, 1, 'int32', 0, 'ieee-be');
labels = fread(fp, inf, 'unsigned char');
fclose(fp);
end
```
阅读全文