C++ 简单神经网络实现 - 前向传播、反向传播和训练
该程序实现了一个简单的神经网络,包括前向传播、反向传播和训练过程。
程序中的 Network 类包含了以下功能:
- 构造函数:接受 epoches 和 learning_rate 作为参数,并初始化网络参数。
- sigmoid 函数:计算 sigmoid 激活函数的值。
- deriv_sigmoid 函数:计算 sigmoid 函数的导数值。
- forward 函数:根据输入的 x 和 y 值,计算网络的输出值。
- train 函数:接受一个训练数据集,通过反向传播算法更新网络参数,训练网络。
- predict 函数:预测输入 x 和 y 的输出值。
下面是程序的执行情况说明和测试截图:
-
初始化网络参数: 程序中的构造函数会初始化网络参数 w1, w2, w3, w4, w5, w6, b1, b2, b3 为固定的值。
-
训练网络: 程序中的 train 函数会根据输入的训练数据集进行训练,通过反向传播算法更新网络参数。
-
输出训练过程中的损失值: 程序中的 train 函数在每个 epoch 结束时会输出当前的 epoch 和总损失。
-
预测输入数据的输出值: 程序中的 predict 函数可以根据输入的 x 和 y 值预测网络的输出值。
下面是程序的测试截图:

测试截图展示了训练过程中的 epoch 和总损失值。

测试截图展示了输入为 (0.5, 0.5) 时的预测输出值。

测试截图展示了输入为 (-0.5, -0.5) 时的预测输出值。
#include <iostream>
#include <cmath>
#include <vector>
class Network {
private:
int epoches;
double learning_rate;
double w1, w2, w3, w4, w5, w6, b1, b2, b3;
public:
Network(int epoches, double learning_rate) {
this->epoches = epoches;
this->learning_rate = learning_rate;
// 初始化网络参数
w1 = 0.2;
w2 = 0.3;
w3 = 0.4;
w4 = 0.5;
w5 = 0.6;
w6 = 0.7;
b1 = 0.1;
b2 = 0.2;
b3 = 0.3;
}
double sigmoid(double x) {
return 1 / (1 + exp(-x));
}
double deriv_sigmoid(double x) {
double sig = sigmoid(x);
return sig * (1 - sig);
}
double forward(double x, double y) {
double h1 = sigmoid(w1 * x + w2 * y + b1);
double h2 = sigmoid(w3 * x + w4 * y + b2);
double output = sigmoid(w5 * h1 + w6 * h2 + b3);
return output;
}
void train(std::vector<double>& train_data) {
for (int epoch = 0; epoch < epoches; epoch++) {
double total_loss = 0;
for (int i = 0; i < train_data.size(); i += 3) {
double x = train_data[i];
double y = train_data[i + 1];
int label = train_data[i + 2];
double h1 = sigmoid(w1 * x + w2 * y + b1);
double h2 = sigmoid(w3 * x + w4 * y + b2);
double output = sigmoid(w5 * h1 + w6 * h2 + b3);
double loss = pow(output - label, 2);
total_loss += loss;
double delta_output = (output - label) * deriv_sigmoid(output);
double delta_h1 = delta_output * w5 * deriv_sigmoid(h1);
double delta_h2 = delta_output * w6 * deriv_sigmoid(h2);
w1 -= learning_rate * delta_h1 * x;
w2 -= learning_rate * delta_h1 * y;
b1 -= learning_rate * delta_h1;
w3 -= learning_rate * delta_h2 * x;
w4 -= learning_rate * delta_h2 * y;
b2 -= learning_rate * delta_h2;
w5 -= learning_rate * delta_output * h1;
w6 -= learning_rate * delta_output * h2;
b3 -= learning_rate * delta_output;
}
std::cout << "Epoch: " << epoch + 1 << ", Loss: " << total_loss << std::endl;
}
}
int predict(double x, double y) {
double output = forward(x, y);
return round(output);
}
};
int main() {
std::vector<double> train_data = {1, 1, 0, -1, -1, 1, 1, -1, 1, 0, -1, 0, 0, 1, 0, -1, 0, 0, 0, 1};
Network network(1000, 0.1);
network.train(train_data);
std::cout << "Prediction for (0.5, 0.5): " << network.predict(0.5, 0.5) << std::endl;
std::cout << "Prediction for (-0.5, -0.5): " << network.predict(-0.5, -0.5) << std::endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/qjL7 著作权归作者所有。请勿转载和采集!