matlab mnist 代码,MNIST手写数字体分类–KNN matlab实现 | 学步园

这里直接给出KNN matlab的实现

trainImages = loadMNISTImages('train-images.idx3-ubyte');

trainLabels = loadMNISTLabels('train-labels.idx1-ubyte');

N = 784;

K = 100;% can be any other value

testImages = loadMNISTImages('t10k-images.idx3-ubyte');

testLabels = loadMNISTLabels('t10k-labels.idx1-ubyte');

trainLength = length(trainImages);

testLength = length(testImages);

testResults = linspace(0,0,length(testImages));

compLabel = linspace(0,0,K);

tic;

for i=1:testLength

curImage = repmat(testImages(:,i),1,trainLength);

curImage = abs(trainImages-curImage);

comp=sum(curImage);

[sortedComp,ind] = sort(comp);

for j = 1:K

compLabel(j) = trainLabels(ind(j));

end

table = tabulate(compLabel);

[maxCount,idx] = max(table(:,2));

testResults(i) = table(idx);

disp(testResults(i));

disp(testLabels(i));

end

% Compute the error on the test set

error=0;

for i=1:testLength

if (testResults(i) ~= testLabels(i))

error=error+1;

end

end

%Print out the classification error on the test set

error/testLength

toc;

disp(toc-tic);

其中训练数据60000条,测试数据10000条

98f77da906c1c622340e7ec5dd20650c.png

运行时间慢的原因分析:

没有进行主成分分析,用所有的维度在进行比较,这一点是可以改进的地方:)

附上其他次要代码:

function images = loadMNISTImages(filename)

%loadMNISTImages returns a 28x28x[number of MNIST images] matrix containing

%the raw MNIST images

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, '']);

numImages = fread(fp, 1, 'int32', 0, 'ieee-be');

numRows = fread(fp, 1, 'int32', 0, 'ieee-be');

numCols = fread(fp, 1, 'int32', 0, 'ieee-be');

images = fread(fp, inf, 'unsigned char');

images = reshape(images, numCols, numRows, numImages);

images = permute(images,[2 1 3]);

fclose(fp);

% Reshape to #pixels x #examples

images = reshape(images, size(images, 1) * size(images, 2), size(images, 3));

% Convert to double and rescale to [0,1]

images = double(images) / 255;

end

function labels = loadMNISTLabels(filename)

%loadMNISTLabels returns a [number of MNIST images]x1 matrix containing

%the labels for the MNIST images

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, '']);

numLabels = fread(fp, 1, 'int32', 0, 'ieee-be');

labels = fread(fp, inf, 'unsigned char');

assert(size(labels,1) == numLabels, 'Mismatch in label count');

fclose(fp);

end

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是三层BP神经网络的MATLAB代码实现,用于分类MNIST数字集: ``` % 加载MNIST数据集 load mnist.mat % 将训练数据和测试数据分别存储在X_train, Y_train, X_test, Y_test中 X_train = double(train_X') / 255; Y_train = double(train_labels'); X_test = double(test_X') / 255; Y_test = double(test_labels'); % 设定网络参数 input_size = size(X_train, 2); hidden_size = 100; output_size = 10; learning_rate = 0.1; num_epochs = 50; batch_size = 100; % 初始化权重和偏置 W1 = randn(input_size, hidden_size) * 0.01; b1 = zeros(1, hidden_size); W2 = randn(hidden_size, output_size) * 0.01; b2 = zeros(1, output_size); % 开始训练 for epoch = 1:num_epochs % 将训练数据随机打乱 idx = randperm(size(X_train, 1)); X_train = X_train(idx, :); Y_train = Y_train(idx, :); % 按照batch_size进行训练 for i = 1:batch_size:size(X_train, 1) % 获取一个batch的数据 X_batch = X_train(i:i+batch_size-1, :); Y_batch = Y_train(i:i+batch_size-1, :); % 前向传播 Z1 = X_batch * W1 + b1; A1 = sigmoid(Z1); Z2 = A1 * W2 + b2; A2 = softmax(Z2); % 计算损失和梯度 loss = cross_entropy(A2, Y_batch); dZ2 = A2 - Y_batch; dW2 = A1' * dZ2 / batch_size; db2 = sum(dZ2, 1) / batch_size; dA1 = dZ2 * W2'; dZ1 = dA1 .* sigmoid_grad(A1); dW1 = X_batch' * dZ1 / batch_size; db1 = sum(dZ1, 1) / batch_size; % 更新权重和偏置 W1 = W1 - learning_rate * dW1; b1 = b1 - learning_rate * db1; W2 = W2 - learning_rate * dW2; b2 = b2 - learning_rate * db2; end % 计算训练集和测试集的准确率 train_acc = compute_accuracy(X_train, Y_train, W1, b1, W2, b2); test_acc = compute_accuracy(X_test, Y_test, W1, b1, W2, b2); fprintf('Epoch %d: loss = %f, train_acc = %f, test_acc = %f\n', epoch, loss, train_acc, test_acc); end % 定义sigmoid函数 function y = sigmoid(x) y = 1 ./ (1 + exp(-x)); end % 定义sigmoid函数的导数 function y = sigmoid_grad(x) y = sigmoid(x) .* (1 - sigmoid(x)); end % 定义softmax函数 function y = softmax(x) exp_scores = exp(x); y = exp_scores ./ sum(exp_scores, 2); end % 定义交叉熵损失函数 function loss = cross_entropy(y_pred, y_true) N = size(y_pred, 1); loss = -sum(log(y_pred(sub2ind(size(y_pred), 1:N, y_true')))) / N; end % 定义计算准确率的函数 function acc = compute_accuracy(X, Y, W1, b1, W2, b2) Z1 = X * W1 + b1; A1 = sigmoid(Z1); Z2 = A1 * W2 + b2; A2 = softmax(Z2); [~, pred] = max(A2, [], 2); acc = mean(pred == Y); end ``` 该代码实现了一个三层的BP神经网络,包括一个输入层、一个隐藏层和一个输出层。其中,输入层和输出层的大小分别为784和10,对应MNIST数据集中每张图片的像素数和标签数。隐藏层的大小为100,可以根据需要调整。习率、训练轮数和batch大小也可以根据需要进行调整。 在训练过程中,使用随机梯度下降法更新权重和偏置。每个epoch都对训练集进行一次遍历,将训练数据随机打乱,并按照batch_size进行训练。计算损失和梯度时使用交叉熵损失函数和softmax函数。在每个epoch结束后,计算训练集和测试集的准确率。 最后,定义了一些辅助函数,包括sigmoid函数、sigmoid函数的导数、softmax函数、交叉熵损失函数和计算准确率的函数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值