function untitled() load('D:\mat格式的MNIST数据\test_labels.mat') load('D:\mat格式的MNIST数据\train_images.mat') load('D:\mat格式的MNIST数据\train_labels.mat') load('D:\mat格式的MNIST数据\test_images.mat') train_num = 6000; test_num = 200; %训练数据,图像转向量 data_train = mat2vector(train_images(:,:,1:train_num),train_num); data_test = mat2vector(test_images(:,:,1:test_num),test_num); % 处理训练数据,防止后验概率为0 [data_train,position] = fun(data_train,train_labels1(1:train_num)'); % 处理测试数据 for rows = 1:10 data_test(:,position{1,rows})=[]; end %模型部分 % 超参数全部取了默认值,比较重要的,如类别的先验概率,如果不进行修改,则计算输入数据中类别的频率 % 查看nb_model即可确认所使用的超参数 Mdl = fitcnb(data_train,train_labels1(1:train_num)); %训练模型 %测试结果 result = predict(Mdl,data_test); result = result.'; xlabel=[0,1,2,3,4,5,6,7,8,9]; resultbar = [0,0,0,0,0,0,0,0,0,0]; testbar = [0,0,0,0,0,0,0,0,0,0]; for i = 1:test_num temp1=result(i); temp1=temp1+1; resultbar(temp1)=resultbar(temp1)+1; temp2=test_labels1(i); temp2=temp2+1; testbar(temp2)=testbar(temp2)+1; end bar(xlabel, [resultbar' testbar']); % 整体正确率 acc = 0.; for i = 1:test_num if result(i)==test_labels1(i) acc = acc+1; end end title('精确度为:',(acc/test_num)*100) end function [output,position] = fun(data,label) position = cell(1,10); %创建cell存储每类中删除的列标 for i = 0:9 temp = []; pos = []; for rows = 1:size(data,1) if label(rows)==i temp = [temp;data(rows,:)]; end end for cols = 1:size(temp,2) var_data = var(temp(:,cols)); if var_data==0 pos = [pos,cols]; end end position{i+1} = pos; data(:,pos)=[]; end output = data; end function [data_]= mat2vector(data,num) [row,col,~] = size(data); data_ = zeros(num,row*col); for page = 1:num for rows = 1:row for cols = 1:col data_(page,((rows-1)*col+cols)) = im2double(data(rows,cols,page)); end end end end
时间: 2024-03-08 20:45:26 浏览: 159
Attachments_2015423.zip_Attachments
这段代码是用来进行朴素贝叶斯分类器在MNIST数据集上的训练和测试的。其中,load函数用来读取MNIST数据集中的图像和标签数据。然后将训练数据和测试数据转换成向量的形式,并且处理训练数据,防止后验概率为0。接着,使用fitcnb函数训练模型,并且使用predict函数测试模型的效果。最后,计算整体的正确率,并且绘制分类结果的直方图。
阅读全文