FUNDAMENTA RED NEURONAL MAXIMA SENSIBILIDAD

UNIVERSIDAD AUTÓNOMA DE NUEVO LEÓN FACULTAD DE INGENIERÍA MECÁNICA Y ELECTRÍCA PERCEPCION FUNDAMENTAL 2 MAXIMA SENCIBI

Views 60 Downloads 0 File size 1MB

Report DMCA / Copyright

DOWNLOAD FILE

Recommend stories

Citation preview

UNIVERSIDAD AUTÓNOMA DE NUEVO LEÓN

FACULTAD DE INGENIERÍA MECÁNICA Y ELECTRÍCA PERCEPCION

FUNDAMENTAL 2 MAXIMA SENCIBILIDAD

Semestre: ENERO- AGOSTO 2020

Nombre del alumno: Alexis Nael Briseño Galván Matrícula: 1838172 Carrera: Mecatrónica Semestre: 8°

Mayo del 2020 San Nicolás de los Garza, Nuevo León

INTRODUCCIÓN La RNMS Esta RN tiene características importantes que la hacen ser de aprendizaje en tiempo real, con capacidad de reutilizar neuronas generando analogías de la respuesta y hacer todo ello con operaciones “ligeras” para la CPU. En esta RN las neuronas cuentan con un peso por cada entrada, una estimulación, previa a la generación de la salida llamada , un factor AC por cada entrada que se multiplica por la estimulación SN para obtener la respuesta de cada neurona. En la explicación siguiente para la RNMS se utilizan los nombres: 1. YD es la salida deseada para cada patrón de entradas. 2. Y es la respuesta obtenida por la RN para un patrón de entradas. 3. U es el vector de uso de cada neurona: a. Si es menor o igual a 0 significa que la neurona no usada. b. Si es igual a 1 significa que la neurona es muy usada. c. Si el valor está entre 0 y 1 significa que la neurona está usándose de forma normal. 4. CN es el conteo de las neuronas que se han usado a un momento dado. Se divide la explicación en cada modo de operación de la RN: funcionamiento y entrenamiento.

El primer cálculo, correspondiente al estímulo de cada neurona es:

Como se ve en la ecuación, SN se hace para la cada m neurona en uso. La función de activación es una gaussiana con cierto ancho de campana que en este reporte se maneja igual para todas las neuronas y centro de masa en 0. Si algún SN supera un umbral MS (margen de sensibilidad) entonces esa m neurona será quien genere la salida de la forma:

de lo contrario la respuesta se genera de la forma:

Las operaciones que se deben ejecutar para ajustar los pesos y factores en función de los patrones siguen el orden presentado en el diagrama de la figura 3.

CONTENIDO En esta práctica lo que se tiene como objetivo controlar un servomotor con 4 sensores de luminosidad utilizando una red neuronal de máxima sensibilidad. Como entradas se tienen sensores de luminosidad y un potenciometro. Como salida se tiene un servomotor.

MATERIAL A UTILIZAR

Sensor de iluminación (fotoresistencia) Celda fotoresistiva (Fotoresistencia) de 2 MOhms en la oscuridad y 50 KOhms máximos bajo la luz. Soporta 100 Vca.

|

Diodos emisores de luz (LED)  Voltaje: 2,1 Vcc  Potencia: 31,5 mW  Luminosidad: 80 mcd  Corriente: 15 mA Diámetro: 5 mm

Micro servomotor con torque de 2.2 kgf/cm  Torque de 1,8 kgf*cm @ 4,8 Vcc  Torque de 2,2 kgf*cm @ 6 Vcc  Rotación de 180°  Temperatura de operación: -30° a 60°  Velocidad de operación: < 0,1 s  Conector tipo S compatible con receptores Futaba y JR  Engranaje metálico de larga vida Alimentación: 3,5 - 6 Vcc 40 mA

Micro switch, de push, con 4 terminales  Micro interruptor (Switch) de presión (Push), de 12 Vcc, 50 mA, 4 terminales, normalmente abierto (NA). Esta fabricado en plástico color negro, su vida útil es de 200,000 operaciones eléctricas y 100,000 mecánicas.

Potenciómetro miniatura sin switch, de 10 kohms  Potenciómetro miniatura de 10 kOhms, 0,2 Watts y 150 Volts, con caña estriada de 2,54 cm, sin interruptor (Switch).

CIRCUITO

FUNCIONAMIENTO DE LA PRÁCTICA

CÓDIGO #include //Definitions of board pins //Convention note: for analog inputs use pins: 0,1,... until last inpux X, then the desired output yd //(example: for two inputs use pin 0 for x1, pin 1 for x2, and then pin 2 for the desired output yd) #define inputYd A3 // analog input for potentiometer #1 - yd (pot 1) #define outputYr 5 // analog output for real response of neural network (servo 1) #define learnButton 3 // digital input for pushButton #1 - learn pattern #define modeButton 2 // digital input for pushButton #2 - mode #define ledLearning 9 // digital output for red led - learning pattern process #define ledTraining 10 // digital output for yellow led - training mode #define ledRunning 11 // digital output for green led - run mode #define ledBuiltIn 13 // built-in led for indications of sytem mode (on = autonomous training, off = pc training) //Definitions for tags in serial communications #define START 83 //ascii of 'S' will be used as START DATA tag #define END 69 //ascii of 'E' will be used as END DATA tag #define SEPARATOR 30 //ascii of RS (register separator) will be used as DATA BYTES SEPARATOR #define RFPT 84 //ascii of 'T' will be used as ID TAG in the data reception from a computer //Definitions of interrupts #define modeRequest 0 #define learnRequest 1 //Global variables //System operation boolean pcMode; char inputBuffer[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; byte inputData[5] = {0, 0, 0, 0, 0}; //Inputs and Outputs float X[2] = {0.0, 0.0}; //system inputs byte XN[2] = {0, 0,}; float yd = 0.0; //desired output byte ydN = 0; float yr = 0.0; //real output (NN response) byte yrN = 0; //Pointers in operations with arrays int i = 0, j = 0; //Constants and other variables for the system int CN; boolean trainMode; boolean MaxSens; int posMaxSens; const int NTI = 2; const int NTN = 32; const float MS = 0.6; const float lambda = 0.1; const float FU = 0.001; //Matrix and vectors float W[NTN][NTI]; float SN[NTN]; float AC[NTN]; float U[NTN]; Servo servo;

int servoAng = 0; //Setup function void setup() { //Pin configurations for digital signals pinMode(ledLearning, OUTPUT); pinMode(ledTraining, OUTPUT); pinMode(ledRunning, OUTPUT); pinMode(outputYr, OUTPUT); pinMode(ledBuiltIn, OUTPUT); pinMode(learnButton, INPUT); pinMode(modeButton, INPUT); servo.attach(outputYr); //Serial configurations Serial.begin(9600); //Interrupt configurations attachInterrupt(learnRequest, learnPatternInterruptFunction, RISING); attachInterrupt(modeRequest, changeNNModeInterruptFunction, RISING); interrupts(); //enable all interrupts //System startup nnStartUp(); } //StartUp function void nnStartUp() { CN = 1; MaxSens = false; posMaxSens = -1; trainMode = false; setMode(trainMode); for (i = 0; i < NTN; i++) { AC[i] = 0.0; SN[i] = 0.0; U[i] = 1.0; for (j = 0; j < NTI; j++) { W[i][j] = 0.0; } } } //Main function void loop() { if (!pcMode) { readData(); } if (trainMode) { ydN = analogRead(inputYd) >> 2; yd = ydN / 255.0; servoAng = map (ydN, 0, 255, 10, 170); servo.write(servoAng); } else { nnRun(); printData(); delay(10);

} } //Function to execute what's needed to change the mode (between Training and Running) void setMode(boolean mode) { if (mode == true) { //1=training, 0=running digitalWrite(ledTraining, HIGH); digitalWrite(ledRunning, LOW); digitalWrite(ledLearning, LOW); } else if (mode == false) { ////0=training, 1=running digitalWrite(ledTraining, LOW); digitalWrite(ledRunning, HIGH); digitalWrite(ledLearning, LOW); } } //Function to execute what's needed to change the mode (between PcMode and ArduinoMode) void setPcMode(boolean mode) { if (mode == true) { digitalWrite(ledBuiltIn, HIGH); pcMode = true; } else { digitalWrite(ledBuiltIn, LOW); pcMode = false; } } //Activation function float activationFunction(float x, float l, float cm) { float y; if (l > 0) { y = exp( ( -1 * pow((x - cm), 2 ) ) / l); } else { y = 1; } y = constrain(y, 0, 1); return y; } //Update the U vector (the usage of each neuron is decreased through time) void updateU() { for (i = 0; i < NTN; i++) { U[i] = U[i] - FU; } } //Blink led void blinkLed(int led, int tHigh, int tLow, int cycles) { for (int cy = 1; cy > 2; X[i] = XN[i] / 255.0; Serial.print(i); Serial.print(" "); Serial.println(X[i]); } } //Function to print the resulting data: inputs and outputs (through serial port and analog output) void printData() { servoAng = map (yrN, 0, 255, 10, 170); servo.write(servoAng); delay(300); } //Function that is used when the system is working with a computer (pcMode=true) void serialEvent() { if (Serial.available() == 9) { for (int i = 8; i >= 0; i--) { inputBuffer[i] = Serial.read(); } if (pcMode == true & inputBuffer[0] == RFPT & inputBuffer[1] == RFPT & inputBuffer[7] == RFPT & inputBuffer[8] == RFPT) { XN[0] = byte(inputBuffer[2]); //x1 XN[1] = byte(inputBuffer[3]); //x2 ydN = byte(inputBuffer[4]); //yd X[0] = XN[0] / 255.0; X[1] = XN[1] / 255.0; yd = ydN / 255.0; inputData[3] = byte(inputBuffer[5]); //modeButton inputData[4] = byte(inputBuffer[6]); //learnButton if (inputData[3] == 1) { changeNNMode(); } if (inputData[4] == 1) { learnPattern(); } } } } //Interruption for learnButton - learn a pattern when pressed if the system is at Learning Mode void learnPatternInterruptFunction() { if (!pcMode) { learnPattern(); } else { setPcMode(false); } } void learnPattern() { noInterrupts(); if (trainMode == true) {

blinkLed(ledRunning, 25, 25, 2); nnRun(); updateU(); blinkLed(ledRunning, 25, 25, 2); blinkLed(ledLearning, 25, 25, 2); nnLearn(); updateU(); blinkLed(ledLearning, 25, 25, 2); } else { setPcMode(true); } interrupts(); } //Interruption for modeButton - change the mode when pressed void changeNNModeInterruptFunction() { if (!pcMode) { changeNNMode(); } else { setPcMode(false); } } void changeNNMode() { noInterrupts(); trainMode = !trainMode; setMode(trainMode); interrupts(); } //Function that computes the response of the neural network according to the inputs at the moment of the called void nnRun() { //for each currently used neuron computes its response float s; for (i = 0; i < CN; i++) { s = 0; for (j = 0; j < NTI; j++) { s = s + pow(X[j] - W[i][j], 2); } SN[i] = activationFunction(sqrt(s), lambda, 0); } //check wich neuron has the highest response int pos = 0; float val = SN[0]; for (i = 1; i < NTN; i++) { if (SN[i] >= val) { val = SN[i]; pos = i; } } //if that value reaches the MS then computes the output using only the neuron response multiplied by its AC factor... if (val >= MS) { yr = AC[pos] * SN[pos]; float temp = yr * 255; yrN = constrain(temp, 0, 255); U[pos] = 1; //... and reset to 1 the usage of this neuron

MaxSens = true; posMaxSens = pos; } else { //if that value does not reach the MS then approximate the output using a ponderation of all neurons response float S1 = 0; float S2 = 0; for (i = 0; i < CN; i++) { S1 = SN[i] * AC[i] + S1; S2 = SN[i] + S2; } yr = S1 / S2; float temp = yr * 255; yrN = constrain(temp, 0, 255); MaxSens = false; posMaxSens = -1; } } //Function that adjust the W and AC when the learnButton is pressed void nnLearn() { if (MaxSens == true) { for (i = 0; i < NTI; i++) { W[posMaxSens][i] = (W[posMaxSens][i] + X[i]) / 2; } AC[posMaxSens] = (AC[posMaxSens] + yd) / 2; } else { float val2 = SN[0]; int pos2 = 0; //didn't occur maximum sensibility, so we must check if there's any avaliable neuron or it's going to be necesary reuse one. if (CN + 1 > NTN) { for (i = 1; i < NTN; i++) { if (SN[i]