//主函数
/*
* main.c
*
* Created on: 2018年9月17日
* Author: hsy
*/
#include "stdlib.h"
#include "stdio.h"
#include "head.h"
int main()
{
float X[4][3] = { {0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}};
//float D[4] = { 0, 0, 1, 1 };
float D[4] = { 0, 0, 0, 1 };
//float D[4] = { 0, 1, 1, 1 };
//float D[4] = { 0, 1, 1, 0 };
float W[3];
//随机产生权重值 ,由于是单层所以不会很复杂
for (int i = 0; i < 3; i++) {
W[i] = rand()%2 - 1.0; //得到一个-1 ~ 1之间的数
}
/* train */
for (int epoch = 0; epoch < 100000; epoch++) { //训练10w次
DeltaSGD(W, X, D);
}
/* inference */
float y[4] = {0, 0, 0, 0};//初始化
for (int k = 0; k < 4; k++) {
float sum = 0;
for (int i = 0; i < 3; i++) {
sum += W[i] * X[k][i];
}
y[k] = activation(sum);
printf("%f\n", y[k]);
}
return 0;
}
/*
* File trailer for main.c
*
* [EOF]
*/
//激活函数
/*
* activation.c
*
* Created on: 2018年9月17日
* Author: hsy
*/
/* Function Definitions
* Arguments : float x
* Return Type : float
*/
#include "math.h"
float activation(float x)
{
//两种不同的训练函数
return 1/(1 + exp(-2*x)); //
// return atan(x); //arctanx函数
}
/*
* File trailer for activation.c
*
* [EOF]
*/
/*
* DeltaSGD.c
*
* Created on: 2018年9月17日
* Author: hsy
*
* Function Definitions
* Arguments : float W[3]
* float X[12]
* float D[4]
* Return Type : void
*/
#include "head.h"
#include "math.h"
void DeltaSGD(float W[3], float X[4][3], float D[4])
{
for (int k = 0; k < 4; k++) {
float sum = 0;
for (int i = 0; i < 3; i++) {
sum += W[i] * X[k][i];
}
float y = activation(sum);
// float Delta = step * (1/(1+pow(sum, 2))) * (D[k] - y); //delta rule
float Delta = step * (y*(1-y)) * (D[k] - y); //delta rule
float dW[3];
for (i = 0; i < 3; i++) {
dW[i] = Delta * X[k][i];
}
/*
* head.h
*
* Created on: 2018年9月17日
* Author: hsy
*/
#ifndef HEAD_H_
#define HEAD_H_
#define step 0.9 //步值 0~1 之间,越小精度越高
void DeltaSGD(float W[3], float X[4][3], float D[4]);
float activation(float x); //激活函数
#endif /* HEAD_H_ */
W[0] += dW[0];
W[1] += dW[1];
W[2] += dW[2];
}
}
/*
* File trailer for DeltaSGD.c
*
* [EOF]
*/
有问题欢迎留言