手写数字识别matlab
时间: 2023-09-15 17:18:12 浏览: 65
【手写数字识别】基于支持向量机SVM实现手写数字识别matlab源码含GUI.md
5星 · 资源好评率100%
手写数字识别在Matlab中是一个非常常见的问题,可以使用机器学习算法来解决。下面是一个简单的手写数字识别的Matlab代码示例:
1. 加载数据集
```matlab
load('ex3data1.mat');
```
2. 显示数据集中的图像
```matlab
m = size(X, 1);
rand_indices = randperm(m);
sel = X(rand_indices(1:100), :);
displayData(sel);
```
3. 定义神经网络模型
```matlab
input_layer_size = 400; % 20x20 输入图像
hidden_layer_size = 25; % 隐藏层25个单元
num_labels = 10; % 10 个输出标签,即数字 0 到 9
% 随机初始化权重参数
initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size);
initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels);
% 将权重参数展开成一维向量
initial_nn_params = [initial_Theta1(:) ; initial_Theta2(:)];
```
4. 定义代价函数和梯度函数
```matlab
% 代价函数
[J, grad] = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda);
% 梯度函数
function [J grad] = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lambda)
Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), hidden_layer_size, (input_layer_size + 1));
Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), num_labels, (hidden_layer_size + 1));
m = size(X, 1);
J = 0;
Theta1_grad = zeros(size(Theta1));
Theta2_grad = zeros(size(Theta2));
X = [ones(m, 1) X];
z2 = X * Theta1';
a2 = sigmoid(z2);
a2 = [ones(m, 1) a2];
z3 = a2 * Theta2';
h = sigmoid(z3);
yk = zeros(m, num_labels);
for i=1:m
yk(i,y(i)) = 1;
end
J = (-1/m) * sum(sum(yk.*log(h) + (1-yk).*log(1-h))) + (lambda/(2*m)) * (sum(sum(Theta1(:,2:end).^2)) + sum(sum(Theta2(:,2:end).^2)));
delta3 = h - yk;
delta2 = delta3 * Theta2 .* sigmoidGradient([ones(m, 1) z2]);
delta2 = delta2(:, 2:end);
Delta1 = delta2' * X;
Delta2 = delta3' * a2;
Theta1_grad = (1/m) * Delta1 + (lambda/m) * [zeros(size(Theta1, 1), 1) Theta1(:, 2:end)];
Theta2_grad = (1/m) * Delta2 + (lambda/m) * [zeros(size(Theta2, 1), 1) Theta2(:, 2:end)];
grad = [Theta1_grad(:) ; Theta2_grad(:)];
end
```
5. 训练模型
```matlab
options = optimset('MaxIter', 50);
lambda = 1;
costFunction = @(p) nnCostFunction(p, input_layer_size, hidden_layer_size, num_labels, X, y, lambda);
[nn_params, cost] = fmincg(costFunction, initial_nn_params, options);
Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), hidden_layer_size, (input_layer_size + 1));
Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), num_labels, (hidden_layer_size + 1));
```
6. 测试模型
```matlab
pred = predict(Theta1, Theta2, X);
fprintf('\nTraining Set Accuracy: %f\n', mean(double(pred == y)) * 100);
```
7. 预测新的数字图像
```matlab
% 加载新的数字图像
img = imread('new_digit.png');
% 转换成灰度图像
img = rgb2gray(img);
% 转换成二值图像
img = im2bw(img, 0.5);
% 调整图像大小
img = imresize(img, [20 20]);
% 将图像转换成向量
X_new = img(:)';
% 预测数字
pred_new = predict(Theta1, Theta2, X_new);
fprintf('\nPredicted Number: %d\n', mod(pred_new, 10));
```
以上是一个简单的手写数字识别的Matlab代码示例,其中包括数据加载、神经网络模型定义、代价函数和梯度函数、模型训练、模型测试和预测新的数字图像等步骤。
阅读全文