DevioLab CRYPTO TRADING AUTOMATION
LIVE
AUTOMATED CRYPTO TRADING • BINANCE
Автоматизуйте свій криптопортфель
Торгові боти DevioLab аналізують крипторинок, автоматично відкривають і закривають позиції та керують вашим портфелем на Binance 24/7.
CRYPTO 80 Bots
BINANCE Spot Trading
TRADING 24 / 7
Спробувати DevioLab
deviolab.com

Адаптивне управління

Інформація про навчальний заклад

ВУЗ:
Національний університет Львівська політехніка
Інститут:
Не вказано
Факультет:
КН
Кафедра:
Кафедра електронних обчислювальних машин

Інформація про роботу

Рік:
2013
Тип роботи:
Звіт про виконання лабораторної роботи
Предмет:
Інші

Частина тексту файла (без зображень, графіків і формул):

Міністерство освіти і науки України Національний університет „Львівська політехніка” Кафедра електронних обчислювальних машин Звіт про виконання лабораторної роботи № 5 з курсу „ Теорія колективної поведінки інтелектуальних систем ” Тема: Адаптивне управління Мета: Ознайомитись з принципами адаптивного управління з механізмом наслідування. Загальні відомості Розглянемо N агентів, які розміщенні в середовищі E і одночасно в дискретні моменти часу реалізують кожний по одній дії з набору D={d1,d2,…} усіх доступних дій в цьому середовищі. Після цього кожний агент отримує відгук середовища (значення функції оцінки) ut,i, i=1,…,N і пов’язує його з дією dkt,i. (dkt,i, ut,i) При цьому значення {ut,i} можуть бути різними, в залежності від того яку дію реалізував агент та (можливо) в якій точці середовища він знаходиться. Модель інформаційної зв’язності. В кожному такті агенти випадковим чином розбиваються на пари, в яких відбувається обмін значеннями (dkt,i, ut,i). Цільова функція колективу дорівнює сумі індивідуальних виграшів агентів.   Схема адаптивного управління з механізмом наслідування (варіант): Кожний агент (Ai) виконує наступні два правила: 1)    Якщо ut,i > ut,j, i(j, то повторити успішну дію (dkt+1,i = dkt,i) 2)    Якщо ut,i < ut,j, i(j, то з ймовірністю p1 повторити дію "опонента" (dkt+1,i = dkt,j) і з ймовірністю p2 випадково обрати будь-яку дію з набору доступних дій D.  При цьому p1 + p2 = 1. Тобто кожний агент з ймовірністю p1 наслідує інших агентів, а з ймовірністю p2 діє "самостійно". Т.ч. "успішні" агенти будуть зберігати свою дію на довгий час, а "невдахи" будуть змінювати дії, наслідуючи "успішних" агентів. В такий спосіб відбувається пристосування (адаптація) колективу до середовища. Текст програми /* Copyright (c) 2005 alb. All Rights Reserved. * Multiagent systems Lab * Computer Engineering Department * Lviv Polytechnic National University * =============================================== * Multiagent Systems. Lab work 05. Multiagent design I: Adaptive Control. * Here two types of multiagent systems (collectives) are implemented: * - collective of casual agents, * - collective of agents with adaptive control. * With given * set of available actions D={1,2} and * set of possible responses R={0,1} * 1 -> reward (win) * 0 -> punishment (loss) * you must investigate behaviour of these two colletives * over T interaction in specified environments. */ #include "stdafx.h" #define NACTION 2 // number of actions, avalaible for agents #define NAGENT 10 // number of agents in collective (MAS) int t; // current time step int T = 100; // maximum number of time steps (interactions with environment) int N = NAGENT; // number of agents int neighbor[NAGENT]; // neighbor's array double p1 = 0.9; // imitation rate int env_model; // environmetn code: // 1 - envoronment with static response // 2 - envoronment with predetermined dynamic response // 3 - envoronment with stationary random response: // binary bandit task (n-armed bandit, n=2) // variables for environment's parameters int env1; // winning action code (env_model = 1) int env2_action1; // first winning action code (env_model = 2) int env2_action2; // second winning action code (env_model = 2) int max_period=6; // max period of action repetitions (env_model = 2) int cd1 = 0; // counter for first action (env_model = 2) int cd2 = 0; // counter for second action (env_model = 2) int env2[2]; // periods of action repetitions (env_model = 2) double env3[2]; // probabilities of rewards for each action (env_model = 3) // file for saving results char * res_file_name = "test.dat"; FILE * res_file; int action[NAGENT]; // RL-agent current action int response[NAGENT]; // current response of environment (can be 0 or 1) // agent results int R[NAGENT]; // current reward over time R(t) int sumR[NAGENT]; // total reward over time sumR(t) float prcR[NAGENT]; // success percent(rate) over time prcR(t) // MAS results int Rmas; // current reward over time int sumRmas = 0; // total reward over time float prcNRmas; // current success percent(rate) over agents float prcRmas; // success percent(rate) over time int ag_type = 1; int actNumber = NACTION; // action number of agent int randomChoice (int _n) { int r; r = (int) ((float)_n * (float)rand() / (float)RAND_MAX); return r + 1; } // automatic initialization of environment void env_init (int env_id) { int i; int tmp; switch (env_id) { case 1: // envoronment with static response env1 = randomChoice(actNumber); break; case 2: // envoronment with predetermined dynamic response // random choice of first winning action (1 or 2) if (actNumber == 2) { env2_action1 = randomChoice(2); if (env2_action1 == 1) env2_action2 = 2; else env2_action2 = 1; // random choice of repitition number for first action tmp = (int) ((float)(max_period - 1) * (float)rand() / (float)RAND_MAX); env2[0] = tmp + 1; // random choice of repitition number for second action tmp = (int) ((float)(max_period - 1) * (float)rand() / (float)RAND_MAX); env2[1] = tmp + 1; } break; case 3: // envoronment with stationary random response for(i = 0; i < actNumber; i++) env3[i] = (float)rand() / (float)RAND_MAX; break; default: printf("lab4 error: wrong env model code specified\n"); } } // response generation int env_response (int env_id, int ag_id) { int win_action, _response; float ftmp; switch (env_id) { case 1: // envoronment with static response if (action[ag_id] == env1) _response = 1; else _response = 0; break; case 2: // envoronment with predetermined dynamic response if (cd1 < env2[0]) { cd1 ++; win_action = env2_action1; } else { if (cd2 < (env2[1] - 1)) { cd2 ++; win_action = env2_action2; } else { cd1 = 0; cd2 = 0; win_action = env2_action2; } } if (action[ag_id] == win_action) _response = 1; else _response = 0; break; case 3: // envoronment with stationary random response ftmp = (float)rand() / (float)RAND_MAX; if (ftmp < env3[action[ag_id]-1]) _response = 1; else _response = 0; break; default: printf("lab5 error: wrong env model code specified\n"); } return _response; } // print environment parameters void env_info (void) { int j; printf("\nenvironment = %d", env_model); switch (env_model) { case 1: // envoronment with static response printf("\n (%d)\n",env1); break; case 2: // envoronment with predetermined dynamic response printf("\n(%d) -> %d, (%d) -> %d\n",env2_action1,env2[0],env2_action2,env2[1]); break; case 3: // envoronment with stationary random response printf("\naction number = %d\n", actNumber); for(j=0; j<actNumber; j++) printf("(%d) -> %f\n", j + 1, env3[j]); printf("\n"); break; default: printf("lab5 error: wrong env model code specified\n"); } } void res_open_file (void) { if ((res_file = fopen(res_file_name,"w")) == NULL) { fprintf(stderr, "Cannot open file <%s> for experimental results.\n", res_file_name); } } void res_close_file (void) { fclose(res_file); } void res_store_next_string (void) { fprintf(res_file,"%d,%d,%f,%f\n",Rmas,sumRmas,prcNRmas,prcRmas); } int casual_agent (void) { return randomChoice(actNumber); } void get_pairs (void) { int tmp[NAGENT][2]; int j, h, a, b, skip = 0; int _i, _j, c, r, _tmp1, _tmp2; // initialize array by static indexes for(j=0;j<N;j++) tmp[j][0] = j; // generate array of random numbers j = 0; while (j < N) { tmp[j][1] = randomChoice(N*10); h = 0; skip = 0; while (h < j) {if (tmp[j][1] == tmp[h][1]) skip = 1; h++;} if (skip == 0) j++; } // sort array in ascending order (bubble sort) c = 0; r = N - 1; for (_i = c; _i < r; _i++) { for (_j = r; _j > _i; _j--) if (tmp[_j][1] < tmp[_j-1][1]) { _tmp1 = tmp[_j][1]; _tmp2 = tmp[_j][0]; tmp[_j][1] = tmp[_j-1][1]; tmp[_j][0] = tmp[_j-1][0]; tmp[_j-1][1] = _tmp1; tmp[_j-1][0] = _tmp2; } } // form pairs for(j=0;j<N;j=j+2) { a = tmp[j][0]; b = tmp[j+1][0]; neighbor[a] = b; neighbor[b] = a; } } // adaptive agent int adaptive_agent (int ag_id) { int nbr_id = neighbor[ag_id]; float rand_num; if(t==0) action[ag_id] = randomChoice(actNumber); else { // repeat own action if (response[ag_id] > response[nbr_id]) action[ag_id] = action[ag_id]; else { rand_num = (float)rand() / (float)RAND_MAX; if (rand_num < p1) action[ag_id] = action[nbr_id]; // repeat neighbor action else action[ag_id] = randomChoice(actNumber); // choose action randomly } } return action[ag_id]; } // print information about agent void ag_info (void) { printf("agent --> "); switch (ag_type) { case 1: printf("casual agent"); break; case 2: printf("adaptive agent with imitation rate %f", p1); break; default: printf("lab5 error: wrong <ag_type> value specified\n"); } printf("\n\n"); } int main (int argc, char* argv[]) { int i; // init random-number generator srand((unsigned)time(NULL)); env_model = 3; ag_type = 2; // set parameters of chosen environment env3[0] = 0.3; env3[1] = 0.8; res_open_file(); // open file for results printf("starting...\n\n"); for (i=0; i < N; i++) sumR[i] = 0; // main cycle of program (over interactions with environment) for (t=0; t < T; t++) { if (ag_type == 2) get_pairs(); for (i=0; i < N; i++) { switch (ag_type) { case 1: action[i] = casual_agent(); break; // casual MAS case 2: action[i] = adaptive_agent(i); break; // MAS with adaptive control default: printf("lab5 error: wrong <ag_type> value specified\n"); } } for (i=0; i < N; i++) { // get response of environment response[i] = env_response(env_model, i); // calculate agent results R[i] = response[i]; sumR[i] = sumR[i] + R[i]; prcR[i] = (float)sumR[i] / ((float)t + 1); } // calculate MAS results Rmas = 0; for (i=0; i < N; i++) Rmas = Rmas + R[i]; prcNRmas = (float)Rmas / (float)N; sumRmas = sumRmas + Rmas; prcRmas = (float)sumRmas / ((float)t + 1); // print current results printf("curren succes rate: %f --> total MAS reward: %d\n",prcNRmas, sumRmas); // save current results in file res_store_next_string(); } printf("\n%d interactions performed\n", t); env_info(); // print information about environment printf("number of agents: %d\n", N); ag_info(); // print information about agent // close file with results res_close_file(); return 0; } Результати Часові залежності для обох колективів для стаціонарного випадкового середовища у графічному вигляді із зазначенням чисельних характеристик алгоритму адаптивного управління та середовища, для яких отримано результати. Залежності загальної суми виграшних дій від часу R((t) = (Rt для обох колективів:  Залежності біжучого проценту виграшних дій від часу (середнє значення виграшу, що припадає на одну дію): Ps(t) = (Rt / t для обох колективів:  Чисельні характеристики алгоритму адаптивного управління та середовища, для яких отримано результати: environment = 3 action number = 2 (1) -> 0.300000 (2) -> 0.800000 number of agents: 10 agent --> adaptive agent with imitation rate 0.900000   Висновки: виконуючи дану лабораторну роботу я досліджував принципи адаптивного управління з механізмом наслідування. Отримані результати показують, що обмін інформацією між парами агентів у колективі з алгоритмом адаптивного управління дає виграш у продуктивності приблизно на 15..20 % відносно колективу агентів, які обирають свої дії випадковим чином.
Антиботан аватар за замовчуванням

31.03.2013 15:49

Коментарі

Ви не можете залишити коментар. Для цього, будь ласка, увійдіть або зареєструйтесь.

Ділись своїми роботами та отримуй миттєві бонуси!

Нічого не вибрано
0%

Оголошення від адміністратора

Антиботан аватар за замовчуванням

Подякувати Студентському архіву довільною сумою

Admin

26.02.2023 12:38

Дякуємо, що користуєтесь нашим архівом!