用c++手写神经网络训练识别mnist数据集
- User
用c++手写神经网络训练识别mnist数据集
- Assistant
用c++手写神经网络训练识别mnist数据集
Creating a neural network from scratch in C++ to train and recognize the MNIST dataset is an excellent way to understand the fundamentals of neural networks. Below is a comprehensive guide, including a complete C++ implementation, that walks you through the process.
Prerequisites:
C++ Compiler: Ensure you have a modern C++ compiler installed (e.g., g++).
MNIST Dataset: Download the MNIST dataset from Yann LeCun's website. You'll need the following four files:
train-images-idx3-ubytetrain-labels-idx1-ubytet10k-images-idx3-ubytet10k-labels-idx1-ubytePlace these files in a directory accessible to your C++ program.
Basic Understanding of Neural Networks: Familiarity with neural network concepts such as layers, activation functions, forward and backward propagation, and loss functions.
We'll build a simple feedforward neural network with one hidden layer. The network will consist of:
The network will be trained using Stochastic Gradient Descent (SGD) with backpropagation.
We'll use standard C++ libraries for this implementation.
#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
#include <cassert>
#include <random>
#include <algorithm>
// Sigmoid Activation Function
double sigmoid(double x) {
return 1.0 / (1.0 + exp(-x));
}
// Derivative of Sigmoid
double sigmoid_derivative(double x) {
return x * (1.0 - x);
}
// Softmax Activation Function for Output Layer
std::vector<double> softmax(const std::vector<double> &z) {
std::vector<double> result(z.size());
double max = *max_element(z.begin(), z.end());
double sum = 0.0;
for(auto &val : z){
val = exp(val - max); // for numerical stability
sum += val;
}
for(size_t i = 0; i < z.size(); ++i){
result[i] = z[i] / sum;
}
return result;
}
We'll use the cross-entropy loss function.
double cross_entropy_loss(const std::vector<double> &output, const std::vector<double> &target){
double loss = 0.0;
for(size_t i = 0; i < output.size(); ++i){
loss -= target[i] * log(output[i] + 1e-9); // Added epsilon to prevent log(0)
}
return loss;
}
The MNIST dataset is stored in IDX file format. We'll create functions to read these files.
// Function to reverse byte order (big endian to little endian)
int reverseInt(int i){
unsigned char c1, c2, c3, c4;
c1 = i & 255;
c2 = (i >> 8) & 255;
c3 = (i >> 16) & 255;
c4 = (i >> 24) & 255;
return ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4;
}
// Function to read MNIST images
std::vector<std::vector<double>> read_mnist_images(const std::string &filename){
std::ifstream file(filename, std::ios::binary);
if(file.is_open()){
int magic_number=0;
int number_of_images=0;
int n_rows=0;
int n_cols=0;
file.read((char*)&magic_number, sizeof(magic_number));
magic_number = reverseInt(magic_number);
file.read((char*)&number_of_images, sizeof(number_of_images));
number_of_images = reverseInt(number_of_images);
file.read((char*)&n_rows, sizeof(n_rows));
n_rows = reverseInt(n_rows);
file.read((char*)&n_cols, sizeof(n_cols));
n_cols = reverseInt(n_cols);
std::vector<std::vector<double>> images(number_of_images, std::vector<double>(n_rows * n_cols));
for(int i = 0; i < number_of_images; ++i){
for(int j = 0; j < n_rows * n_cols; ++j){
unsigned char pixel = 0;
file.read((char*)&pixel, sizeof(pixel));
images[i][j] = static_cast<double>(pixel) / 255.0; // Normalize pixel values
}
}
return images;
}
else{
throw std::runtime_error("Cannot open file `" + filename + "`!");
}
}
// Function to read MNIST labels
std::vector<int> read_mnist_labels(const std::string &filename){
std::ifstream file(filename, std::ios::binary);
if(file.is_open()){
int magic_number=0;
int number_of_labels=0;
file.read((char*)&magic_number, sizeof(magic_number));
magic_number = reverseInt(magic_number);
file.read((char*)&number_of_labels, sizeof(number_of_labels));
number_of_labels = reverseInt(number_of_labels);
std::vector<int> labels(number_of_labels);
for(int i = 0; i < number_of_labels; ++i){
unsigned char label = 0;
file.read((char*)&label, sizeof(label));
labels[i] = static_cast<int>(label);
}
return labels;
}
else{
throw std::runtime_error("Cannot open file `" + filename + "`!");
}
}
We'll create a simple neural network with one hidden layer.
Convert labels to one-hot encoded vectors.
std::vector<double> one_hot_encode(int label, int num_classes=10){
std::vector<double> encoded(num_classes, 0.0);
encoded[label] = 1.0;
return encoded;
}
double evaluate_accuracy(NeuralNetwork &nn, const std::vector<std::vector<double>> &images, const std::vector<int> &labels){
int correct = 0;
for(size_t i = 0; i < images.size(); ++i){
std::vector<double> output = nn.forward(images[i]);
int predicted = std::distance(output.begin(), std::max_element(output.begin(), output.end()));
if(predicted == labels[i]){
correct += 1;
}
}
return static_cast<double>(correct) / images.size();
}
Putting it all together.
int main(){
try{
// Load MNIST data
std::cout << "Loading MNIST dataset..." << std::endl;
std::vector<std::vector<double>> train_images = read_mnist_images("train-images-idx3-ubyte");
std::vector<int> train_labels = read_mnist_labels("train-labels-idx1-ubyte");
std::vector<std::vector<double>> test_images = read_mnist_images("t10k-images-idx3-ubyte");
std::vector<int> test_labels = read_mnist_labels("t10k-labels-idx1-ubyte");
std::cout << "Dataset loaded." << std::endl;
// Initialize neural network
int input_size = 784;
int hidden_size = 128;
int output_size = 10;
double learning_rate = 0.1;
NeuralNetwork nn(input_size, hidden_size, output_size, learning_rate);
// Training parameters
int epochs = 10;
int batch_size = 32;
// Training loop
for(int epoch = 1; epoch <= epochs; ++epoch){
double total_loss = 0.0;
// Shuffle the training data
std::vector<int> indices(train_images.size());
for(int i = 0; i < train_images.size(); ++i) indices[i] = i;
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(indices.begin(), indices.end(), g);
for(size_t i = 0; i < train_images.size(); ++i){
int idx = indices[i];
std::vector<double> input = train_images[idx];
std::vector<double> target = one_hot_encode(train_labels[idx]);
std::vector<double> output = nn.forward(input);
total_loss += cross_entropy_loss(output, target);
nn.train(input, target);
}
double avg_loss = total_loss / train_images.size();
double accuracy = evaluate_accuracy(nn, test_images, test_labels);
std::cout << "Epoch " << epoch << "/" << epochs << " - Loss: " << avg_loss << " - Test Accuracy: " << accuracy * 100 << "%" << std::endl;
}
}
catch(const std::exception &e){
std::cerr << e.what() << std::endl;
}
return 0;
}
Save the Code:
Save the above code in a file named mnist_nn.cpp.
Compile the Code:
Open your terminal or command prompt, navigate to the directory containing mnist_nn.cpp, and compile using g++:
g++ -o mnist_nn mnist_nn.cpp -O2
The -O2 flag enables optimization for faster execution.
Execute the Program:
Ensure that the MNIST data files are in the same directory as the executable or provide the correct path in the code. Then run:
./mnist_nn
The program will load the dataset, initialize the neural network, and start training. It will output the loss and test accuracy after each epoch.
Performance Optimizations:
Activation Functions:
Regularization:
Learning Rate Scheduling:
GPU Acceleration:
Error Handling:
Modular Design:
This implementation provides a foundational understanding of how neural networks operate under the hood. While it may not be optimized for performance, it's an excellent starting point for educational purposes and further enhancements.
Not yet included in a published release.
class NeuralNetwork {
public:
int input_size;
int hidden_size;
int output_size;
double learning_rate;
// Weights and biases
std::vector<std::vector<double>> weights_input_hidden;
std::vector<double> bias_hidden;
std::vector<std::vector<double>> weights_hidden_output;
std::vector<double> bias_output;
// Constructor
NeuralNetwork(int input, int hidden, int output, double lr){
input_size = input;
hidden_size = hidden;
output_size = output;
learning_rate = lr;
// Initialize weights with small random values
std::default_random_engine generator;
std::uniform_real_distribution<double> dist(-0.5, 0.5);
weights_input_hidden.resize(input_size, std::vector<double>(hidden_size));
for(auto &row : weights_input_hidden){
for(auto &val : row){
val = dist(generator);
}
}
bias_hidden.resize(hidden_size, 0.0);
for(auto &val : bias_hidden){
val = dist(generator);
}
weights_hidden_output.resize(hidden_size, std::vector<double>(output_size));
for(auto &row : weights_hidden_output){
for(auto &val : row){
val = dist(generator);
}
}
bias_output.resize(output_size, 0.0);
for(auto &val : bias_output){
val = dist(generator);
}
}
// Forward pass
std::vector<double> forward(const std::vector<double> &input){
// Hidden layer
hidden_layer_input = std::vector<double>(hidden_size, 0.0);
for(int i = 0; i < hidden_size; ++i){
for(int j = 0; j < input_size; ++j){
hidden_layer_input[i] += input[j] * weights_input_hidden[j][i];
}
hidden_layer_input[i] += bias_hidden[i];
hidden_layer_output[i] = sigmoid(hidden_layer_input[i]);
}
// Output layer
output_layer_input = std::vector<double>(output_size, 0.0);
for(int i = 0; i < output_size; ++i){
for(int j = 0; j < hidden_size; ++j){
output_layer_input[i] += hidden_layer_output[j] * weights_hidden_output[j][i];
}
output_layer_input[i] += bias_output[i];
// Do not apply activation here; we'll apply softmax later
}
output = softmax(output_layer_input);
return output;
}
// Backward pass and update weights
void backward(const std::vector<double> &input, const std::vector<double> &target){
// Calculate output layer error
std::vector<double> output_errors(output_size, 0.0);
for(int i = 0; i < output_size; ++i){
output_errors[i] = output[i] - target[i];
}
// Calculate gradients for weights_hidden_output and bias_output
std::vector<std::vector<double>> grad_weights_hidden_output(hidden_size, std::vector<double>(output_size, 0.0));
std::vector<double> grad_bias_output(output_size, 0.0);
for(int i = 0; i < hidden_size; ++i){
for(int j = 0; j < output_size; ++j){
grad_weights_hidden_output[i][j] = hidden_layer_output[i] * output_errors[j];
}
}
for(int i = 0; i < output_size; ++i){
grad_bias_output[i] = output_errors[i];
}
// Calculate hidden layer error
std::vector<double> hidden_errors(hidden_size, 0.0);
for(int i = 0; i < hidden_size; ++i){
for(int j = 0; j < output_size; ++j){
hidden_errors[i] += weights_hidden_output[i][j] * output_errors[j];
}
hidden_errors[i] *= sigmoid_derivative(hidden_layer_output[i]);
}
// Calculate gradients for weights_input_hidden and bias_hidden
std::vector<std::vector<double>> grad_weights_input_hidden(input_size, std::vector<double>(hidden_size, 0.0));
std::vector<double> grad_bias_hidden(hidden_size, 0.0);
for(int i = 0; i < input_size; ++i){
for(int j = 0; j < hidden_size; ++j){
grad_weights_input_hidden[i][j] = input[i] * hidden_errors[j];
}
}
for(int i = 0; i < hidden_size; ++i){
grad_bias_hidden[i] = hidden_errors[i];
}
// Update weights and biases
// Update weights_hidden_output
for(int i = 0; i < hidden_size; ++i){
for(int j = 0; j < output_size; ++j){
weights_hidden_output[i][j] -= learning_rate * grad_weights_hidden_output[i][j];
}
}
// Update bias_output
for(int i = 0; i < output_size; ++i){
bias_output[i] -= learning_rate * grad_bias_output[i];
}
// Update weights_input_hidden
for(int i = 0; i < input_size; ++i){
for(int j = 0; j < hidden_size; ++j){
weights_input_hidden[i][j] -= learning_rate * grad_weights_input_hidden[i][j];
}
}
// Update bias_hidden
for(int i = 0; i < hidden_size; ++i){
bias_hidden[i] -= learning_rate * grad_bias_hidden[i];
}
}
// Train the network with a single example
void train(const std::vector<double> &input, const std::vector<double> &target){
forward(input);
backward(input, target);
}
private:
// Variables to store forward pass results
std::vector<double> hidden_layer_input;
std::vector<double> hidden_layer_output;
std::vector<double> output_layer_input;
std::vector<double> output;
};