神經網路:計算簡單的加法

來源:互聯網
上載者:User

下面是完整的代碼:

//

// fann_test.c :

// FANN 測試

//

// 到下面的網站下載FANN庫:

// Fast Artificial Neural Network Library (fann)

// http://leenissen.dk/fann/

// 下載連結: Download FANN ---> C Source Code and Windows DLL files

//


#include "../fann-2.0.0/src/include/doublefann.h"


#ifdef _DEBUG

#pragma comment(lib, "../fann-2.0.0/MicrosoftWindowsDll/bin/fanndoubleMTd.lib")

#else

#pragma comment(lib, "../fann-2.0.0/MicrosoftWindowsDll/bin/fanndoubleMT.lib")

#endif


// 訓練:

// 加法神經網路

// c = a+b;

void train()

{

const unsigned int num_input = 2; // 輸入項個數

const unsigned int num_output = 1; // 輸出項個數

const unsigned int num_layers = 3;

const unsigned int num_neurons_hidden = 3;

const float desired_error = (const float) 0.00000001;

const unsigned int max_epochs = 500000; // 最多執行次數

const unsigned int epochs_between_reports = 10000; // 報告頻率


struct fann *ann;


int Num = 200;

float Mf = Num*3.f;

int i;

double a, b, c;


FILE *fp;

fopen_s(&fp, "add.fann", "w");

fprintf_s(fp, "%d 2 1\n", Num);


// 產生訓練檔案

for(i=1; i<=Num; i++){

// 產生2個數, 要求在(0,1)之間

a = i/Mf;

b = (i+1)/Mf;

c = a+b; // 要求在(0,1)之間


// 輸入內容寫到訓練檔案

fprintf_s(fp, "%lf %lf\n%lf\n", a, b, c);

}

fclose(fp);


// 樣本訓練

ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_output);


fann_set_activation_function_hidden(ann, FANN_LINEAR );

fann_set_activation_function_output(ann, FANN_LINEAR );


fann_train_on_file(ann, "add.fann", max_epochs, epochs_between_reports, desired_error);

fann_save(ann, "add.fann.net");

fann_destroy(ann);

}

// 執行:

// 測試

void exec(double a, double b)

{

struct fann *ann;


fann_type *calc_out;

fann_type input[2];

ann = fann_create_from_file("add.fann.net");


input[0] = a;

input[1] = b;


calc_out = fann_run(ann, input);

fann_destroy(ann);

printf("a=%f\nb=%f\nc=%f\n期望值c=%f\n\n", input[0], input[1], calc_out[0], input[0]+input[1]);

}


//

// 主程式

//

int main()

{

// 下面的方法只需調用一次, 然後注釋掉

// train();


exec(0.354,0.58934);

exec(0.21469,0.3914968);

exec(0.130,0.44);

exec(-0.3654,0.58455);

exec(0.365420,-0.95);


return 0;

}

相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。