神经网络: 计算简单的加法

神经网络: 计算简单的加法
下面是完整的代码:
  1. //
  2. // fann_test.c : 
  3. // FANN 测试
  4. //
  5. // 到下面的网站下载FANN库:
  6. //   Fast Artificial Neural Network Library (fann)
  7. //     http://leenissen.dk/fann/
  8. //   下载链接: Download FANN --->  C Source Code and Windows DLL files 
  9. //
  10. #include "../fann-2.0.0/src/include/doublefann.h"
  11. #ifdef _DEBUG
  12.   #pragma comment(lib, "../fann-2.0.0/MicrosoftWindowsDll/bin/fanndoubleMTd.lib")
  13. #else
  14.   #pragma comment(lib, "../fann-2.0.0/MicrosoftWindowsDll/bin/fanndoubleMT.lib")
  15. #endif
  16. // 训练:
  17. // 加法神经网络
  18. // c = a+b;
  19. void train()
  20. {
  21.     const unsigned int num_input = 2;       // 输入项个数
  22.     const unsigned int num_output = 1;      // 输出项个数
  23.     const unsigned int num_layers = 3;
  24.     const unsigned int num_neurons_hidden = 3;    
  25.     const float desired_error = (const float) 0.00000001;
  26.     const unsigned int max_epochs = 500000; // 最多执行次数   
  27.     const unsigned int epochs_between_reports = 10000;   // 报告频率
  28.     
  29.     struct fann *ann;
  30.     
  31.     int     Num = 200;
  32.     float   Mf = Num*3.f;
  33.     int     i;
  34.     double  a, b, c;
  35.     FILE   *fp;
  36.     fopen_s(&fp, "add.fann""w");
  37.     fprintf_s(fp, "%d 2 1/n", Num);
  38.     // 生成训练文件
  39.     for(i=1; i<=Num; i++){
  40.         // 生成2个数, 要求在(0,1)之间
  41.         a = i/Mf;
  42.         b = (i+1)/Mf;
  43.         c = a+b;    // 要求在(0,1)之间
  44.         
  45.         // 输入内容写到训练文件
  46.         fprintf_s(fp, "%lf %lf/n%lf/n", a, b, c);
  47.     }
  48.     fclose(fp);
  49.     // 样本训练
  50.     ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_output);
  51.     
  52.     fann_set_activation_function_hidden(ann, FANN_LINEAR  );
  53.     fann_set_activation_function_output(ann, FANN_LINEAR  );  
  54.     fann_train_on_file(ann, "add.fann", max_epochs, epochs_between_reports, desired_error); 
  55.     fann_save(ann, "add.fann.net");  
  56.     fann_destroy(ann);
  57. }
  58. // 执行:
  59. // 测试
  60. void exec(double a, double b)
  61. {
  62.     struct fann *ann;
  63.     
  64.     fann_type *calc_out;
  65.     fann_type input[2];
  66.     ann = fann_create_from_file("add.fann.net");    
  67.     
  68.     input[0] = a;
  69.     input[1] = b;
  70.             
  71.     calc_out = fann_run(ann, input);
  72.     fann_destroy(ann);
  73.     printf("a=%f/nb=%f/nc=%f/n期望值c=%f/n/n", input[0], input[1], calc_out[0], input[0]+input[1]);    
  74. }
  75. //
  76. // 主程序
  77. //
  78. int main()
  79. {
  80.     // 下面的方法只需调用一次, 然后注释掉
  81.     // train();
  82.     exec(0.354,0.58934);
  83.     exec(0.21469,0.3914968);
  84.     exec(0.130,0.44);
  85.     exec(-0.3654,0.58455);
  86.     exec(0.365420,-0.95);
  87.     return 0;
  88. }

你可能感兴趣的:(function,网络,File,input,FP,output)