我需要BP神经网络的C++代码
时间: 2023-05-20 09:06:51 浏览: 121
以下是一个简单的BP神经网络的C代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define INPUTS 2
#define HIDDEN 3
#define OUTPUTS 1
#define LEARNING_RATE 0.5
double sigmoid(double x) {
return 1.0 / (1.0 + exp(-x));
}
int main() {
double inputs[INPUTS] = {0.1, 0.2};
double hidden[HIDDEN];
double outputs[OUTPUTS];
double weights_ih[INPUTS][HIDDEN];
double weights_ho[HIDDEN][OUTPUTS];
double bias_h[HIDDEN];
double bias_o[OUTPUTS];
double error[OUTPUTS];
double hidden_error[HIDDEN];
double hidden_gradient[HIDDEN];
double output_gradient[OUTPUTS];
// Initialize weights and biases
for (int i = 0; i < INPUTS; i++) {
for (int j = 0; j < HIDDEN; j++) {
weights_ih[i][j] = (double) rand() / RAND_MAX - 0.5;
}
}
for (int i = 0; i < HIDDEN; i++) {
for (int j = 0; j < OUTPUTS; j++) {
weights_ho[i][j] = (double) rand() / RAND_MAX - 0.5;
}
bias_h[i] = (double) rand() / RAND_MAX - 0.5;
}
for (int i = 0; i < OUTPUTS; i++) {
bias_o[i] = (double) rand() / RAND_MAX - 0.5;
}
// Forward pass
for (int i = 0; i < HIDDEN; i++) {
double sum = 0.0;
for (int j = 0; j < INPUTS; j++) {
sum += inputs[j] * weights_ih[j][i];
}
hidden[i] = sigmoid(sum + bias_h[i]);
}
for (int i = 0; i < OUTPUTS; i++) {
double sum = 0.0;
for (int j = 0; j < HIDDEN; j++) {
sum += hidden[j] * weights_ho[j][i];
}
outputs[i] = sigmoid(sum + bias_o[i]);
}
// Backward pass
error[0] = 0.9 - outputs[0];
for (int i = 0; i < HIDDEN; i++) {
double sum = 0.0;
for (int j = 0; j < OUTPUTS; j++) {
sum += error[j] * weights_ho[i][j];
}
hidden_error[i] = sum;
hidden_gradient[i] = hidden[i] * (1 - hidden[i]) * hidden_error[i];
}
for (int i = 0; i < OUTPUTS; i++) {
output_gradient[i] = outputs[i] * (1 - outputs[i]) * error[i];
}
for (int i = 0; i < HIDDEN; i++) {
for (int j = 0; j < OUTPUTS; j++) {
weights_ho[i][j] += LEARNING_RATE * hidden[i] * output_gradient[j];
}
for (int j = 0; j < INPUTS; j++) {
weights_ih[j][i] += LEARNING_RATE * inputs[j] * hidden_gradient[i];
}
bias_h[i] += LEARNING_RATE * hidden_gradient[i];
}
for (int i = 0; i < OUTPUTS; i++) {
bias_o[i] += LEARNING_RATE * output_gradient[i];
}
// Print results
printf("Inputs: %f %f\n", inputs[0], inputs[1]);
printf("Outputs: %f\n", outputs[0]);
return 0;
}
阅读全文