朴素贝叶斯matlab源代码
matlab% 朴素贝叶斯分类器示例 % 生成一些示例数据 data = [randn(100,2); randn(100,2)+2]; labels = [zeros(100,1); ones(100,1)]; % 将数据随机排序 idx = randperm(length(labels)); data = data(idx,:); labels = labels(idx); % 将数据拆分为训练集和测试集 train_data = data(1:150,:); train_labels = labels(1:150,:); test_data = data(151:end,:); test_labels = labels(151:end,:); % 训练朴素贝叶斯分类器 nb = fitcnb(train_data, train_labels); % 对测试集进行预测 predicted_labels = predict(nb, test_data); % 计算分类准确率 accuracy = sum(predicted_labels == test_labels) / length(test_labels); disp(['准确率:', num2str(accuracy)]);
这个示例假设你有两个类别的数据,每个类别有 100 个样本。首先,它生成示例数据,然后将数据随机排序,并将其拆分为训练集和测试集。接下来,它使用 fitcnb
函数来训练朴素贝叶斯分类器,然后使用 predict
函数对测试集进行预测。最后,它计算分类准确率并将结果显示在命令窗口中。
matlab% 朴素贝叶斯分类器示例 % 生成一些示例数据 data = [randn(100,2); randn(100,2)+2]; labels = [zeros(100,1); ones(100,1)]; % 将数据随机排序 idx = randperm(length(labels)); data = data(idx,:); labels = labels(idx); % 将数据拆分为训练集和测试集 train_data = data(1:150,:); train_labels = labels(1:150,:); test_data = data(151:end,:); test_labels = labels(151:end,:); % 计算每个类别的先验概率 prior = [sum(train_labels == 0) / length(train_labels); sum(train_labels == 1) / length(train_labels)]; % 计算每个特征的均值和标准差 mu = zeros(2, size(train_data, 2)); sigma = zeros(2, size(train_data, 2)); for i = 1:2 mu(i, :) = mean(train_data(train_labels == (i-1), :)); sigma(i, :) = std(train_data(train_labels == (i-1), :)); end % 对测试集进行分类 predicted_labels = zeros(length(test_labels), 1); for i = 1:length(test_labels) likelihood = zeros(2, 1); for j = 1:2 likelihood(j) = prod(normpdf(test_data(i,:), mu(j,:), sigma(j,:))); end posterior = prior .* likelihood; [~, predicted_labels(i)] = max(posterior); end % 计算分类准确率 accuracy = sum(predicted_labels == test_labels) / length(test_labels); disp(['准确率:', num2str(accuracy)]);
这个示例首先生成示例数据,然后将其随机排序并拆分为训练集和测试集。接下来,它计算每个类别的先验概率、每个特征的均值和标准差,并在测试集上执行分类。最后,它计算分类准确率并将结果显示在命令窗口中。