#include <stdio.h>
#include <stdlib.h>
#include <math.h>
# define INPUTNO 2/*Cell num of input*/
# define ALPHA 1/*learning rate*/
# define MAXNO 100/*maximum of training data*/
# define BIGNUM 100/*initialize the error*/
# define LIMIT 0.001/*limit of the random_error*/
# define SEED 63553/*random seed*/
# define _CRT_SECURE_NO_WARNINGS
void initwo(double wo[INPUTNO + 1]);/*randomly initialize the weighten of input*/
int getdata(double e[][INPUTNO + 1]); /*input the learning data*/
double forward(double wo[INPUTNO + 1], double e[INPUTNO + 1]);/*compute in turn*/
void olearn(double wo[INPUTNO + 1], double e[INPUTNO + 1], double o);/*output the weighten*/
void printweight(double wo[INPUTNO + 1]);/*output the result*/
double s(double u); /*sigmoid function*/
double drand(void);/*generate number from -1 to 1*/
int main() {
double wo[INPUTNO + 1];/*w of output*/
double e[MAXNO][INPUTNO + 1];/*learning data*/
double o;/*output*/
double err = BIGNUM;/*evaluate the error*/
int i, j;/*for cycle*/
int n_of_e;/*size of learning data*/
int count = 0;
srand(SEED);/*initialize the random seed*/
/*initialize and print the weight*/
initwo(wo);
printweight(wo);
/*input the learning data*/
n_of_e = getdata(e);
printf("学习的个数:%d\n", n_of_e);
while (err > LIMIT) {
err = 0.0;
for (j = 0; j < n_of_e; ++j) {
/*compute in turn*/
o = forward(wo, e[j]);/*positively forward*/
olearn(wo, e[j], o);/*neg forward*/
err += (o - e[j][INPUTNO])*(o - e[j][INPUTNO]);/*compute the error which need to be minimize*/
}
++count;
printf("%d\t%lf\n", count, err);
}
printweight(wo);
for (i = 0; i < n_of_e; ++i) {
printf("%d\n", i);
for (j = 0; j < INPUTNO + 1; ++j)
printf("%lf", e[i][j]);
o = forward(wo, e[i]);
printf("%lf\n", o);
}
return 0;
}
void initwo(double wo[INPUTNO + 1]) {
int i;
for (i = 0; i < INPUTNO + 1; ++i)
wo[i] = drand();
}
//输入数据
int getdata(double e[][INPUTNO + 1]) {
int n_of_e = 4;
e[0][0] = 0;
e[0][1] = 0;
e[0][2] = 0;
e[1][0] = 0;
e[1][1] = 1;
e[1][2] = 0;
e[2][0] = 1;
e[2][1] = 0;
e[2][2] = 0;
e[3][0] = 1;
e[3][1] = 1;
e[3][2] = 1;
return n_of_e;
}
/*forward function*/
double forward(double wo[INPUTNO + 1], double e[INPUTNO + 1]) {
int i;
double o;
o = 0;
for (i = 0; i < INPUTNO; ++i)
o += e[i] * wo[i];/*consider wo as both weights and bias*/
o -= wo[i];/*consider wo as both weights and bias*/
/*s represent the sigmoid function*/
return s(o);
}
void olearn(double wo[INPUTNO + 1], double e[INPUTNO + 1], double o) {
int i;
double d;
d = (e[INPUTNO] - o)*o*(1 - o);
for (i = 0; i < INPUTNO; i++) {
wo[i] += ALPHA * e[i] * d;/*function from deriving the sigmoid function*/
}
wo[i] += ALPHA * (-1.0)*d;
}
void printweight(double wo[INPUTNO + 1]) {
int i;
for (i = 0; i < INPUTNO + 1; ++i)
printf("%lf ", wo[i]);
printf("\n");
}
//sigmoid函数
double s(double u) {
return 1.0 / (1.0 + exp(-u));
}
double drand(void) {
double rndno;
while ((rndno = (double)rand() / RAND_MAX) == 1.0);
rndno = rndno * 2 - 1;
return rndno;
}
神经网络 信息处理作业2
于 2023-03-16 11:36:51 首次发布