LabP-L-N2-04-P4
LabP-L-N2-04-P4
LAB. Percepción
*Número de equipo: 4
#Nombre #Matricula
Angel David Flores Román 1945755
Raúl Delgado Saucedo 1796823
P á g i n a 1 | 21
Contenido
Objetivo ............................................................................................................................................... 3
Tabla de datos (100 registros mínimo). ............................................................................................... 3
Arquitectura de la red neuronal utilizada y parámetros de entrenamiento. ...................................... 4
Diagrama electrónico de componentes utilizados. ............................................................................. 5
Resultado del entrenamiento (Gráficas de error). .............................................................................. 6
Reportar con dos casos que generen respuestas bajas y altas. .......................................................... 7
Código fuente de la red neuronal implementada con lectura de sensores y escritura de actuadores
en Arduino IDE .................................................................................................................................... 9
Conclusión personal por cada integrante............................................. ¡Error! Marcador no definido.
Referencias Bibliográficas en formato APA. ...................................................................................... 21
P á g i n a 2 | 21
Objetivo
Implementar una red neuronal de Percepción multicapas para relacionar las
señales de diferentes sensores con una respuesta que es interpretada para activar
diferentes tipos de actuadores como leds, servos y un buzzer. En esta práctica se
reutilizan los pesos generados durante la etapa de entrenamiento de la práctica
anterior.
C. M. DE T.
TEMPERATURA LUZ HUMEDAD CALIDAD DE SUEÑO
AIRE CARBONO CORPORAL
37 25 382 32 4 98 5
36 100 1766 16 2 23 4
34 63 1603 87 30 82 4
33 5 1437 63 4 20 5
13 94 206 45 27 48 2
27 33 62 15 31 45 3
24 25 259 38 14 17 1
7 8 263 30 15 29 5
-1 85 840 78 4 61 4
0 10 1436 69 13 0 5
1 45 222 97 0 96 4
29 6 991 52 10 53 5
35 41 653 12 0 55 5
8 50 1400 23 12 58 3
2 62 789 3 35 95 4
13 97 657 68 32 36 1
10 98 1631 93 30 30 2
26 69 287 80 20 96 2
22 74 652 47 31 9 1
4 22 463 76 29 2 5
-1 86 1819 84 27 71 4
6 14 1453 81 33 33 5
-2 14 1902 83 7 54 5
31 76 1612 0 31 12 3
15 57 1693 63 30 44 3
24 3 914 94 35 93 5
3 23 949 21 14 87 4
P á g i n a 3 | 21
32 90 1968 29 35 77 3
-1 82 1915 6 38 92 4
16 41 1558 8 12 49 4
36 62 758 19 29 2 4
14 6 1782 62 34 8 3
-2 24 1808 78 25 21 5
5 11 1955 99 11 10 5
30 2 58 75 19 36 5
38 71 437 93 24 17 4
-2 44 1139 94 30 22 5
5 67 1927 69 39 51 3
23 32 1540 27 21 61 5
2 31 1998 38 39 70 5
Se entrenó por 25000 épocas para obtener un error menor error en el entrenamiento.
P á g i n a 4 | 21
Diagrama electrónico de componentes utilizados.
P á g i n a 5 | 21
Resultado del entrenamiento (Gráficas de error).
P á g i n a 6 | 21
Reportar con dos casos que generen respuestas bajas y altas.
Respuesta Mala
En este se obtuvo 4.46 por lo tanto nuestro servo estará a 180 grados y con 4 leds
encendidos y el buzzer apagado.
P á g i n a 7 | 21
Respuesta buena
En este caso se obtuvo 1 y nuestro primer led permanece encendido mientras que el servomotor
se sitúa a 0 grados.
Para obtener estos casos fue necesario modificar el circuito provocando un falso contacto en el
sensor de temperatura para hacer variar nuestras respuestas.
P á g i n a 8 | 21
Código fuente de la red neuronal
CODIGO Phyton:
from random import *
from math import *
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
from matplotlib.pyplot import plot,show
def normalizar(r,lb,ub):
return (r-lb)/(ub-lb);
def desnormalizar(n,lb,ub):
return n*(ub-lb)+lb;
def maxp(V):
#(val,pos)=maxp(V)
n=len(V);
pos=0;
val=V[pos];
for e in range(n):
if V[e]>val:
val=V[e];
pos=e;
return val,pos
def minp(V):
#(val,pos)=minp(V)
n=len(V);
pos=0;
val=V[pos];
for e in range(n):
if V[e]<val:
val=V[e];
pos=e;
return val,pos
def calcD(V1,V2):
n=len(V1);
s=0;
for e in range(n):
s = s + (V1[e]-V2[e])**2;
d=sqrt(s);
return d
def fa(x):
if (x > 20):
x=20;
if (x < -20):
x=-20;
x = exp(-x);
return 1 / ( 1 + x );
def fad(x):
return fa(x)*(1-fa(x))
P á g i n a 9 | 21
def RandomWeights(TINP, TMID, TOUT):
#LMTT2006 Derechos reservados 2006
#LMTT2020 Derechos reservados 2020
# (m, ma, o, oa) = RandomWeights(TINP, TMID, TOUT)
m=[[random()-0.5 for i in range(TINP)] for j in range(TMID)]
o=[[random()-0.5 for i in range(TMID)] for j in range(TOUT)]
ma=[[random()-0.5 for i in range(TINP)] for j in range(TMID)]
oa=[[random()-0.5 for i in range(TMID)] for j in range(TOUT)]
return m, ma, o, oa
def ForwardBKG(VI,m,o):
#LMTT2006 Derechos reservados 2006
#LMTT2020 Derechos reservados 2020
# (sm,so,neto,netm)=ForwardBKG(VI,m,o)
TMID=len(m);
TINP=len(m[0]);
TOUT=len(o);
for y in range(TMID):
for x in range(TINP):
netm[y] = netm[y] + m[y][x] * VI[x];
sm[y] = fa(netm[y]);
for z in range(TOUT):
for y in range(TMID):
neto[z] = neto[z] + o[z][y] * sm[y];
so[z] = fa(neto[z]);
return sm,so,neto,netm
for y in range(TMID):
sum1=0;
for z in range(TOUT):
sum1 = sum1 + eo[z]*o[z][y];
em[y] = fad(netm[y])*sum1;
return em,eo
def LearningBKG(VI, m, ma, sm, em, o, oa, eo, ETA, ALPHA):
#LMTT2006 Derechos reservados 2006
#LMTT2020 Derechos reservados 2020
# (m, ma, o, oa) = LearningBKG(VI, m, ma, sm, em, o, oa, eo, ETA, ALPHA)
TMID=len(m);
TINP=len(m[0]);
TOUT=len(o);
for z in range(TOUT):
for y in range(TMID):
o[z][y] = o[z][y] + ETA*eo[z]*sm[y] + ALPHA*oa[z][y];
oa[z][y] = ETA*eo[z]*sm[y];
for y in range(TMID):
for x in range(TINP):
m[y][x] = m[y][x] + ETA*em[y] * VI[x] + ALPHA*ma[y][x];
ma[y][x] = ETA*em[y]*VI[x];
return m, ma, o, oa
## import pandas as pd
## from pandas import ExcelWriter
## from pandas import ExcelFile
##
## df = pd.read_excel('Desktop/Projects2020/PythonCurse/Neuralnetworks/datasetNN.xls')
## Database made in excel format
## Columns of database:
## print(df.columns)
## Data Access:
## print(df['Sensor D'][0])
## print(df['Sensor I'][2])
## print(df['Servo angle'][2])
def DatabaseRead():
#Database or table
#DataBrute=DatabaseRead();
#Excel reading
#df =
pd.read_excel('Desktop/Projects2020/PythonCurse/Neuralnetworks/datasetNN.xls')
df = pd.read_excel('practica3.xlsx')
Nrows=len(df);
Ncols=len(df.columns);
P á g i n a 11 | 21
DataBrute = [[0 for i in range(Ncols)] for j in range(Nrows)];
for r in range(Nrows):
for c in range(Ncols):
DataBrute[r][c]=df[df.columns[c]][r];
return DataBrute
def NormalData(DataExp):
###LMTT092018
### (DataNorm,MRange)=NormalData(DataExp)
##
Trows=len(DataExp);
Tcols=len(DataExp[0]);
V = [0 for i in range(Trows)];
MRange = [[0 for i in range(2)] for j in range(Tcols)];
DataNorm = [[0 for i in range(Tcols)] for j in range(Trows)];
for c in range(Tcols):
for r in range(Trows):
V[r]=DataExp[r][c];
(valmax,posmax)=maxp(V);
(valmin,posmin)=minp(V)
for r in range(Trows):
DataNorm[r][c] = normalizar(DataExp[r][c],valmin,valmax);
MRange[c][0]=valmin;
MRange[c][1]=valmax;
return DataNorm, MRange
def scrambling(DataBase):
#LMTT2006 Derechos reservados 2006
#LMTT2020 Derechos reservados 2020
# DataBaseS=scrambling(DataBase)
Trows=len(DataBase);
DataBaseS=DataBase;
for i in range(Trows*10):
pos1 = floor(random()*Trows);
pos2 = floor(random()*Trows);
temp = DataBaseS[pos1];
DataBaseS[pos1] = DataBaseS[pos2];
DataBaseS[pos2] = temp;
return DataBaseS
def GenTrainVal(DataExp,percent):
#LMTT2006 Derechos reservados 2006
#LMTT2020 Derechos reservados 2020
# (DataTrain,DataVal) = GenTrainVal(DataExp,percent);
#percent for validation (0.1 to 0.4)
DataBaseS=scrambling(DataExp);
Trows=len(DataBaseS);
Tcols=len(DataBaseS[0]);
DataTrain = [[0 for i in range(Tcols)] for j in range(Trows-floor(Trows*percent))];
DataVal = [[0 for i in range(Tcols)] for j in range(floor(Trows*percent))];
for dd in range(Trows-floor(Trows*percent)):
DataTrain[dd]=DataBaseS[dd];
P á g i n a 12 | 21
for dd in range(Trows-floor(Trows*percent),Trows):
DataVal[dd-(Trows-floor(Trows*percent))]=DataBaseS[dd];
return DataTrain,DataVal
def TrainingNNBKni10(NTEpochs,DataTrain):
#LMTT2006 Derechos reservados 2006
#LMTT2020 Derechos reservados 2020
# (Errg,m,o)=TrainingNNBKni10(NTEpochs,DataTrain);
TData=len(DataTrain);
Tcols=len(DataTrain[0]); #inputs plus output
TINP =Tcols; #bias included Input neurons
TMID =7; #Middle neurons (middle layer)
TOUT = 1; #External neurons
ETA = 1; #Learning constant in [0.25, 1]
ALPHA = 0.5; #momentum in (0,1] ALPHA could be ETA / 2
#Random weights
(m, ma, o, oa) = RandomWeights(TINP, TMID, TOUT);
(sm,so,neto,netm)=ForwardBKG(VI,m,o);
(em,eo) = BackwardBKG(DO, netm, m, o, so, neto);
(m, ma, o, oa) = LearningBKG(VI, m, ma, sm, em, o, oa, eo, ETA, ALPHA);
#error gradient calculation
etotal = eo[0]*eo[0] + etotal; #only one output
errcm = 0.5*sqrt(etotal);
if errcm<emin:
emin=errcm;
Errg[epochs] = emin;
return Errg,m,o;
def SetDatabases():
#Read Database to establish file to read
#(DataTrain, DataVal)=SetDatabases()
DataBrute=DatabaseRead();
(DataNorm,MRange)=NormalData(DataBrute);
(DataTrain,DataVal) = GenTrainVal(DataNorm,0.2);
P á g i n a 13 | 21
return DataTrain,DataVal;
def ValidationNNBKni10(DataVal,m,o):
#LMTT2006 Derechos reservados 2006
#LMTT2020 Derechos reservados 2020
# Ynn=ValidationNNBKni10(DataVal,m,o);
TData=len(DataVal);
Tcols=len(DataVal[0]); #inputs plus output
VI = [0 for i in range(TINP)];
etotal=0;
for data in range(TData):
#take input data
for ii in range(TINP):
VI[ii]=DataVal[data][ii];
VI[TINP-1]=1; #Bias
DO=[DataVal[data][Tcols-1]];#output
(sm,so,neto,netm)=ForwardBKG(VI,m,o);
Ynn[data][0] = DO[0];
Ynn[data][1] = so[0];
#error calculation
# for oo in range(TOUT):
# err = (DO[oo]-so[oo])**2;
# etotal = err + etotal;
return Ynn
#
# ++++++++++++++++++++++++++++++++++++++
#
#
def usennbk(X,MRange,m,o):
# R=usennbk(X,MRange,m,o);
TINP = len(X); #bias included Input neurons
Xn = [0 for i in range(TINP+1)];#plus bias
Trows = len(MRange);
for i in range(TINP):
Xn[i] = normalizar(X[i],MRange[i][0],MRange[i][1]);
Xn[TINP]=1;
(sm,so,neto,netm)=ForwardBKG(Xn,m,o);
#Desnormalization
R = desnormalizar(so[0],MRange[Trows-1][0],MRange[Trows-1][1]);
return R
P á g i n a 14 | 21
CODIGO DE ARDUINO:
#include <WiFi.h>
#include <DHT.h>
#include <ESP32Servo.h>
Servo servo1;
#define DHTPIN 23
#define DHTTYPE DHT22 // DHT 22
DHT dht(DHTPIN, DHTTYPE);
float h = 0; float t = 0; // dht22
float ilum = 0; // el resultado de ldr
float calidad = 0; //el resultado de mq135
int lm35 = 0 ; //lm35
float mq7 = 0; //mq7
const int PatternCount = 1;
const int InputNodes = 6; //numero de entradas
const int HiddenNodes = 13; //numero total de nodos E&S
const int OutputNodes = 1; //resultantes
float Input[PatternCount][InputNodes] = {
{0, 0, 0, 0, 0, 0}, // 0
};
float NormInput[PatternCount][InputNodes];
float Min[PatternCount][InputNodes] = {
{ 2, 3, 1, 22, 261, 20}, // 0
};
float Max[PatternCount][InputNodes] = {
{ 50, 100, 100, 2000, 9884, 40}, // 0
};
int MinTarget = 1;
P á g i n a 15 | 21
int MaxTarget = 5;
int i, j, p;
float Accum = 0;
float predict = 0;
float Hidden[HiddenNodes];
float Output[OutputNodes];
float HiddenWeights[(InputNodes*2)+1][HiddenNodes]={{2.505102028908383, -
24.669037737972825, 3.990526246175281, 4.876909177185453, 11.919311684242716, -
5.319695452053054, -0.041440772405717766},
{-8.436139501296077, -1.3767013492613498, -0.04465045306105808, -
6.662560569295351, 0.12270792712527283, -2.572077904113546, 3.6406644732649287},
{16.559977731519798, 14.395611754217878, 0.6597684424596669, -
3.0578746552840754, -10.421685343424764, -0.7465137031250615, -12.145160347440344},
{-14.254822695114663, -1.0969119415295234, -0.521697709835493, -
13.126088386306737, -9.738254454291429, 10.797422664149597, 13.49854806488437},
{3.5408004687314905, 0.043501296966265646, -17.341501195595956, -
7.48819599822394, -5.634368546007835, -5.933785806109487, 6.0532106155372025},
{8.938915622770665, 2.7046008023016164, 0.7601781542844418, -
7.704789449684582, -4.26726620051262, 9.434899786878413, -0.41675585261562426},
{-0.9976249837737452, 2.0432151187495737, -15.407935482355018, -
3.1900948131674127, -1.0971721078591392, 1.162914623861703, 1.6070968310431175}};
float OutputWeights[1][13]={{12.842921773354636, 4.642766295364108,
8.99161063823903, 8.54947925546894, -11.004779507338325, -9.057720891201127,
5.476448263331136}};
void setup() {
Serial.begin(115200);
dht.begin();// Initialize the output variables as outputs
pinMode(led_1, OUTPUT);
pinMode(led_2, OUTPUT);
pinMode(led_3, OUTPUT);
pinMode(led_4, OUTPUT);
pinMode(led_5, OUTPUT);
pinMode(buzzer, OUTPUT);
servo1.attach(33);
pinMode(DHTPIN, INPUT);//pin DHT y Sensor iluminación
pinMode(36, INPUT);// Set outputs to LOW
digitalWrite(led_1, LOW);
digitalWrite(led_2, LOW);
digitalWrite(led_3, LOW);
digitalWrite(led_4, LOW);
digitalWrite(led_5, LOW);
digitalWrite(buzzer, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
P á g i n a 16 | 21
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
void loop() {
lm35 = analogRead(34);
float tempc=(((lm35*500.0)/4095.0)/10.0)-5;
Input[0][5] = tempc;
delay(100);
calidad = analogRead(35);
calidad = (100 * calidad) / 4096;
calidad = 100 - calidad;
ilum = analogRead(36); ilum = (100 * ilum) / 4096;
delay(1000);
Input[0][2] = ilum;
Serial.println(ilum);
predict = FeedForward();
String s = String(predict);//condiciones para las predicciones
if (predict >= 4.5 && predict <= 5){
digitalWrite(led_1, HIGH);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, HIGH);
digitalWrite(led_5, HIGH);
digitalWrite(buzzer, HIGH);
servo1.write(180);}
else if (predict >= 3.5 && predict < 4.5){
digitalWrite(led_1, HIGH);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, HIGH);
digitalWrite(led_5, LOW);
digitalWrite(buzzer, LOW);
servo1.write(0);}
else if (predict >= 2.5 && predict < 3.5){
digitalWrite(led_1, HIGH);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, HIGH);
digitalWrite(led_4, LOW);
digitalWrite(led_5, LOW);
digitalWrite(buzzer, LOW);
servo1.write(90);}
else if (predict >= 2 && predict < 2.5){
digitalWrite(led_1, HIGH);
digitalWrite(led_2, HIGH);
digitalWrite(led_3, LOW);
digitalWrite(led_4, LOW);
digitalWrite(led_5, LOW);
digitalWrite(buzzer, LOW);
servo1.write(0);}
else if (predict >= 1 && predict < 2){
digitalWrite(led_1, HIGH);
P á g i n a 18 | 21
digitalWrite(led_2, LOW);
digitalWrite(led_3, LOW);
digitalWrite(led_4, LOW);
digitalWrite(led_5, LOW);
digitalWrite(buzzer, LOW);
servo1.write(0);}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=devicewidth, initialscale=1\">");
client.println("<meta http-equiv=\"refresh\" content=\"3\">");
client.println("<linkrel=\"icon\" href=\"data:,\">");
client.println("</head>");// Web Page Heading
client.println("<title>Practica-2</title>");
client.println("<body>");
client.println("<br />"); // Salto de línea
client.println("<div style='text-align:center;'>");
client.println("<h1 align='center'>Sensores</h1>");
client.println("Temperatura = ");client.println(t);
client.println("*C");
client.println("<br />");
client.println("Humedad = ");
client.println(h);
client.println("%");
client.println("<br />");
client.println("Luminosidad = ");
client.println(ilum);
client.println("%");
client.println("<br />");
client.println("Monoxido de carbono = ");
client.println(ppmq7);
client.println("ppm");
client.println("<br />");
client.println("Calidad del aire = ");
client.println(calidad); //sensor Mq-135
client.println("%");
client.println("<br />");
client.println("Temperatura Corporal = ");
client.println(tempc);
client.println("*C");
client.println("<br />");
client.println("<div style='text-align:center;'>");
client.println("<h1 align='center'>Calidad del sueno</h1>");
client.println("Resultado = ");
client.println(predict);
client.println("<br />");
client.println("(Donde 1 es BUENO y 5 es MALO)");
client.println("<br />");
client.println("</div>");
client.println("</body>");
client.println("</html>");// The HTTP response ends with another blank line
client.println();// Break out of the while loop
break;}
P á g i n a 19 | 21
else { // if you got a newline, then clear currentLine
currentLine = "";}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}}}// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");}}
float FeedForward(){
for( p= 0 ; p < PatternCount ; p++ ) {
for( i = 0 ; i < InputNodes ; i++ ) {
NormInput[p][i] = (Input[p][i] -Min[p][i]) / (Max[p][i] -Min[p][i]);
if (NormInput[p][i] > 1){
NormInput[p][i] = 1;}
else if (NormInput[p][i] < 0){
NormInput[p][i] = 0;}}/***********************
Compute hidden layer activations
**********************/
for( i = 0 ; i < HiddenNodes ; i++ ) {
Accum = HiddenWeights[InputNodes][i];
for( j = 0 ; j < InputNodes ; j++ ) {
Accum += NormInput[p][j] * HiddenWeights[i][j] ;}
Hidden[i] = 1.0/(1.0 + exp(-Accum)) ;}
/*********************** Compute output layer activations and calculate
errors**********************/
for( i = 0 ; i < OutputNodes ; i++ ) {
Accum = OutputWeights[HiddenNodes][i];
for( j = 0 ; j < HiddenNodes ; j++) {
Accum += Hidden[j] * OutputWeights[i][j] ;}
Output[i] = 1.0/(1.0 + exp(-Accum)) ;}
for( i = 0 ; i < OutputNodes ; i++ ) {
//Output[i] = (Output[i] * (MaxTarget -MinTarget)) + (MinTarget);
Output[i] = Output[i] * MaxTarget + MinTarget * (1-Output[i]);
if (Output[i] > 5){Output[i] = 5;}
else if (Output[i] < 1){
Output[i] = 1;}}}return Output[0]; }
P á g i n a 20 | 21
Referencias Bibliográficas en formato APA.
Dr. Erick de Jesús Ordaz Rivas, “Practica 2 Componentes de un sistema de
percepción”, https://erickordazr.notion.site/Percepci-n-
cbec50d92fa749fd98fc3e16082fb0db
Dr. Erick de Jesús Ordaz Rivas, “Práctica 3.- Red neuronal como mecanismo de
percepción”, https://erickordazr.notion.site/Pr-ctica-3-Red-neuronal-como-
mecanismo-de-percepci-n-9df6ee5b79554b59b68f9619e35b0331
P á g i n a 21 | 21