def softmax(self, x): """:param x: 输入数据 :return:返回softmax激活函数值""" return 1/(1+np.exp(-x)) def forward_propagation(self, input_data, weight_matrix, b): """ :param input_data: 输入数据 :param weight_matrix: 权重矩阵 :return: 激活函数后输出的活性值 """ z = np.add(np.dot(weight_matrix, input_data), b) return z, self.softmax(z) def predict(self, input_data, label): print("Begin to predict") #precision = 0 #for i in range(number): z1, a1 = self.forward_propagation(input_data[:].reshape(-1, 1), w1, self.b1) z2, a2 = self.forward_propagation(a1, w2, b2) print("预测值为",np.argmax(a2))转换为c语言
时间: 2024-04-28 12:25:26 浏览: 102
以下是转换为 C 语言后的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ROWS 1
#define COLS 784
#define HIDDEN 256
#define LABELS 10
double sigmoid(double x) {
return 1 / (1 + exp(-x));
}
void softmax(double *x, int len) {
double max = x[0];
for (int i = 1; i < len; i++) {
if (x[i] > max) {
max = x[i];
}
}
double sum = 0.0;
for (int i = 0; i < len; i++) {
x[i] = exp(x[i] - max);
sum += x[i];
}
for (int i = 0; i < len; i++) {
x[i] /= sum;
}
}
void forward_propagation(double *input_data, double *weight_matrix1, double *b1, double *weight_matrix2, double *b2, double *a1, double *a2) {
double z1[HIDDEN];
for (int i = 0; i < HIDDEN; i++) {
z1[i] = 0.0;
for (int j = 0; j < COLS; j++) {
z1[i] += weight_matrix1[i * COLS + j] * input_data[j];
}
z1[i] += b1[i];
a1[i] = sigmoid(z1[i]);
}
for (int i = 0; i < LABELS; i++) {
a2[i] = 0.0;
for (int j = 0; j < HIDDEN; j++) {
a2[i] += weight_matrix2[i * HIDDEN + j] * a1[j];
}
a2[i] += b2[i];
}
softmax(a2, LABELS);
}
int predict(double *input_data, double *weight_matrix1, double *b1, double *weight_matrix2, double *b2) {
double a1[HIDDEN], a2[LABELS];
forward_propagation(input_data, weight_matrix1, b1, weight_matrix2, b2, a1, a2);
int prediction = 0;
double max = a2[0];
for (int i = 1; i < LABELS; i++) {
if (a2[i] > max) {
max = a2[i];
prediction = i;
}
}
return prediction;
}
int main() {
double input_data[ROWS * COLS];
double weight_matrix1[HIDDEN * COLS];
double b1[HIDDEN];
double weight_matrix2[LABELS * HIDDEN];
double b2[LABELS];
// 读取数据和模型参数
// ...
// 进行预测
int prediction = predict(input_data, weight_matrix1, b1, weight_matrix2, b2);
printf("预测值为 %d\n", prediction);
return 0;
}
阅读全文