C++ 神经网络实现二维点分类
C++ 神经网络实现二维点分类
本代码实现了一个简单的神经网络,用于对二维点进行分类。神经网络结构包含输入层、隐藏层和输出层,并使用 sigmoid 激活函数。
代码实现
#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;
}
代码解析
-
Network 类
- 属性: 包含训练次数
epoches、学习率learning_rate和网络参数w1、w2、w3、w4、w5、w6、b1、b2、b3。 - 构造函数: 初始化
epoches、learning_rate和网络参数。 - sigmoid 函数: 计算 sigmoid 激活函数。
- deriv_sigmoid 函数: 计算 sigmoid 激活函数的导数。
- forward 函数: 实现前向传播,计算网络输出。
- train 函数: 使用梯度下降算法训练网络,更新网络参数。
- predict 函数: 使用
forward函数预测给定输入的标签。
- 属性: 包含训练次数
-
main 函数: 创建
Network对象,使用训练数据进行训练,并进行两次预测。
总结
本代码实现了一个简单的 C++ 神经网络,用于对二维点进行分类。您可以通过修改代码来调整网络结构、训练参数以及输入数据,以适应不同的任务。
注意: 本代码仅用于演示目的,实际应用中可能需要更复杂的结构和训练算法。
原文地址: https://www.cveoy.top/t/topic/qfEN 著作权归作者所有。请勿转载和采集!