C语言简单单层BP神经网络

//主函数

/*
 * 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]
 */

有问题欢迎留言
 

 


 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值