构造一个三层的BP神经网络,包含输入层,隐层,输出层,用c++实现
时间: 2024-05-08 15:20:16 浏览: 194
可以的,以下是一个简单的三层BP神经网络的c代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define INPUT_SIZE 2
#define HIDDEN_SIZE 3
#define OUTPUT_SIZE 1
typedef struct NeuralNetwork {
double wih[INPUT_SIZE][HIDDEN_SIZE];
double who[HIDDEN_SIZE][OUTPUT_SIZE];
double hidden[HIDDEN_SIZE];
double output[OUTPUT_SIZE];
} NeuralNetwork;
double sigmoid(double x) {
return 1.0 / (1.0 + exp(-x));
}
void initNetwork(NeuralNetwork *network) {
// 初始化输入层到隐层的权重
for (int i = 0; i < INPUT_SIZE; i++) {
for (int j = 0; j < HIDDEN_SIZE; j++) {
network->wih[i][j] = (double)rand() / RAND_MAX - 0.5;
}
}
// 初始化隐层到输出层的权重
for (int i = 0; i < HIDDEN_SIZE; i++) {
for (int j = 0; j < OUTPUT_SIZE; j++) {
network->who[i][j] = (double)rand() / RAND_MAX - 0.5;
}
}
}
void forward(NeuralNetwork *network, double *input) {
// 隐层的计算
for (int i = 0; i < HIDDEN_SIZE; i++) {
double sum = 0;
for (int j = 0; j < INPUT_SIZE; j++) {
sum += input[j] * network->wih[j][i];
}
network->hidden[i] = sigmoid(sum);
}
// 输出层的计算
for (int i = 0; i < OUTPUT_SIZE; i++) {
double sum = 0;
for (int j = 0; j < HIDDEN_SIZE; j++) {
sum += network->hidden[j] * network->who[j][i];
}
network->output[i] = sigmoid(sum);
}
}
int main() {
srand(0);
// 输入样本
double input[][INPUT_SIZE] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};
double target[][OUTPUT_SIZE] = {{0}, {1}, {1}, {0}};
NeuralNetwork network;
initNetwork(&network);
// 训练
int epochs = 10000;
double learning_rate = 0.1;
for (int i = 0; i < epochs; i++) {
for (int j = 0; j < 4; j++) {
forward(&network, input[j]);
double err = 0;
for (int k = 0; k < OUTPUT_SIZE; k++) {
double delta = target[j][k] - network.output[k];
err += delta * delta;
}
// 反向传播
for (int k = 0; k < OUTPUT_SIZE; k++) {
double delta = target[j][k] - network.output[k];
for (int l = 0; l < HIDDEN_SIZE; l++) {
network.who[l][k] += learning_rate * delta * network.hidden[l] * (1 - network.hidden[l]) * network.output[k] * (1 - network.output[k]);
}
}
for (int k = 0; k < HIDDEN_SIZE; k++) {
double delta = 0;
for (int l = 0; l < OUTPUT_SIZE; l++) {
delta += target[j][l] - network.output[l] * network.who[k][l];
}
for (int l = 0; l < INPUT_SIZE; l++) {
network.wih[l][k] += learning_rate * delta * input[j][l] * (1 - network.hidden[k]) * network.hidden[k];
}
}
}
if (i % 1000 == 0) {
printf("Epoch %d, Error: %f\n", i, err);
}
}
// 预测
for (int j = 0; j < 4; j++) {
forward(&network, input[j]);
printf("%d XOR %d = %f\n", (int)input[j][0], (int)input[j][1], network.output[0]);
}
return 0;
}
```
以上代码是一个简单的三层BP神经网络,包含输入层,隐层和输出层。其中,initNetwork函数用于初始化神经网络的权重;forward函数用于前向计算网络的输出结果;在训练时,通过反向传播来更新网络的权重。最后,通过输入样本预测网络的输出结果。
阅读全文