Está en la página 1de 11

Abstract Este documento tiene como finalidad el explicar el

funcionamiento de la neurona artificial llamada Perceptron, para


ello se lo ha codificado en el lenguaje de programacin JAVA.
Proveer un resultado, previo a un entrenamiento, a partir de dos
entradas.


I. OBJETIVOS
L objetivo principal del laboratorio a ms de reforzar el
conocimiento del funcionamiento y mtodo de
aprendizaje del Perceptron, es comprender que el
Perceptron es un separador Lineal.
II. INTRODUCTION
STE documento va demostrar lo propuesto en el objetivo
reforzar el conocimiento del funcionamiento de un
Perceptron para lo cual se empezara con una breve
introduccin.
El Perceptrn dentro del campo de las redes neuronales tiene
dos acepciones. Puede referirse a un tipo de red neuronal
artificialdesarrollado por Frank Rosenblatt.Y dentro de la
misma teora de Frank Rosenblatt. Tambin puede entenderse
como la neurona artificial y unidad bsica de inferencia en
forma de discriminador lineal, es decir, un algoritmo capaz de
generar un criterio para seleccionar un sub-grupo, de un grupo
de componentes ms grande. La limitacin de este algoritmo es
que si dibujamos en un plot estos elementos, se deben poder
separar con un hiperplano los elementos "deseados" de los "no
deseados". El perceptrn puede utilizarse con otros
perceptrones u otro tipo de neurona artificial, para formar redes
neuronales ms complicadas.

III. PROCEDIMIENTO
Para el desarrollo del laboratorio se utilizo el Perceptron
codificado en los anteriores laboratorios, con una diferencia que
son dos Perceptrones para poder saber la localizacion de puntos
en un plano cartesiano.
El presente laboratorio esta codificado para una aplicacin de
escritorio en JAVA con la tecnologa Swing.
Consta de tres clases:
Clase Perceptron.java: Consta del metodo de aprendizaje


desarrollado en clases con modelos matemticos.
Se realizaron modificaciones y adaptaciones al cdigo inicial
las cuales son:
1. Para todo el aprendizaje con respecto al cdigo
inicial se aument el bas, concepto explicado en
clases.
2. Se modific el mtodo entrenar donde de igual
manera se aadi el bas.
3. El mtodo que realiza los ajustes de las variaciones
tanto de los pesos como del bas, se lo implemento.
4. Las adaptaciones que se realizo fue en cuanto al
entrenamiento, puesto que las tablas de
entrenamiento lo tenemos en un archivo de
extensin .txt
5. Tambin se implement un mtodo que de la
misma forma utiliza archivos con la extensin .txt
este mtodo nos sirve para realizar el guardado
tanto los pesos como el bas final resultantes del
entrenamiento.
Clase Grafico.java: Consta de la interfaz grfica y la llamada
a los mtodos de la clase Perceptron.java para luego mostrar
en pantalla de una manera amigable para el usuario.
Clase PesosBiasCargar.java: Esta clase es una clase de
ayuda para la implementacin de los metodos de lectura de
archivos, transparente , al igual que Perceptron.java, al
usuario.
Clase Perceptron.java

















Laboratorio Perceptron Uso como Separador
Lineal
Jonathan Bladimir Arana Mora, Tatiana Maribel Parreo Crdenas
jarana@est.ups.edu.ec, tparrenoc@est.ups.edu.ec
E
E
/**
*
*/
package neurona;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
* @author Jonathan Arana, Tatiana Parreno
*
*/
public class Perceptron {

public int entradas;
public Double[] w;
public Double[] x;
public Double umbral;


















































































































public Double[] x;
public Double umbral;
public boolean cambio, cambio1;
public double lr = 0.05;
public double bias;

static Double w1, w2;
static Double bias1;
public String resultado;

List<Double[]> entra = new
ArrayList<Double[]>();
int i = 0;
int[] v = new int[20];

public Perceptron(int numEntradas) {
this.entradas = numEntradas;
this.umbral = 0.0;
Random rnd01 = new Random(10);
w = new Double[numEntradas];
for (int i = 0; i < entradas; i++) {
w[i] = rnd01.nextDouble()
/ (rnd01.nextDouble() *
rnd01.nextDouble() * 1000);
}
bias = rnd01.nextDouble()
/ (rnd01.nextDouble() *
rnd01.nextDouble() * 1000);
}

private double sumatoria() {
double sum = 0;
for (int i = 0; i < entradas; i++) {
sum += x[i] * w[i];
}
return sum + bias;
}

private int activacion() {
if (sumatoria() > umbral) {
return 1;
} else {
return 0;
}
}

public void entrenamiento(String doc)
throws IOException {
i = 0;
entra = new ArrayList<Double[]>();

entrenaTabla(doc);
}

public int consultar(Double[] X) {

this.x = X;
return activacion();
}

public int consultar() {
this.x = X;
return activacion();
}

public int consultar() {
return activacion();
}

public boolean entrenar(Double[] X,
int d) {
double error;
double deltaW;
double deltaBias;
this.x = X;
error = d - activacion();
if (error != 0) {
for (int i = 0; i < entradas;
i++) {
deltaW = lr * error * x[i];
w[i] = w[i] + deltaW;
}

deltaBias = lr * error;
bias = bias + deltaBias;

return this.cambio = true;
} else {
return this.cambio = false;
}
}

public void entrenaTabla(String doc)
throws IOException {

String subtemp;
int index = 0;
int cont = 0;
int contesp = 0;

// StreamReader objReader = new
StreamReader(doc);
FileInputStream fstream = new
FileInputStream(doc);
// Creamos el objeto de entrada
DataInputStream entrada = new
DataInputStream(fstream);
// Creamos el Buffer de Lectura
BufferedReader buffer = new
BufferedReader(new InputStreamReader(
entrada));
String sLine = "";
while (sLine != null) {
sLine = buffer.readLine();
Double[] x1 = new Double[2];
if (sLine != null)

for (int i = 0; i <
sLine.length(); i++) {
if (sLine.charAt(i) == ',') {
subtemp =
sLine.substring(index, i);




























































Clase Grafico.java





















































for (int i = 0; i < sLine.length(); i++) {
if (sLine.charAt(i) == ',') {
subtemp =
sLine.substring(index, i);
index = i + 1;
x1[cont] =
Double.parseDouble(subtemp);
cont++;

} else if (i == (sLine.length() -
1)) {
if
(sLine.substring(i).equals("T"))
v[contesp] = 1;
else
v[contesp] = 0;
entra.add(x1);
index = 0;
cont = 0;
contesp++;
}
}
}
entrada.close();
ejecucion(entra);

}

void ejecucion(List<Double[]> entradas)
{

if (i < entra.size()) {
cambio1 = entrenar(entra.get(i),
v[i]);
i++;
resultado = "w1=" +
w[0].toString().substring(0, 6) + "w2="
+ w[1].toString().substring(0, 6)
+ "bias=" + bias + "\n";
if (cambio1 == true) {
if (i != 1) {
i = 0;
}
ejecucion(entra);
} else {
ejecucion(entra);
}
} else {
resultado = "w1=" +
w[0].toString().substring(0, 6) + "w2="
+ w[1].toString().substring(0, 6)
+ "bias=" + bias + "\n";
}

}
}

/*
* To change this license header, choose
License Headers in Project Properties.
* To change this template file, choose Tools
| Templates
* and open the template in the editor.
*/

package neurona;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;

/**
*
* @author Jonathan Arana, Tatiana Parreno
*/
public class Grafico extends
javax.swing.JFrame {

/**
*
*/
private static final long serialVersionUID =
1L;

/**
* Creates new form Grafico
*/
public Grafico() {
initComponents();
setLocationRelativeTo(null);
setResizable(false);
}

/**
* This method is called from within the
constructor to initialize the form.
* WARNING: Do NOT modify this code. The
content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed"
desc="Generated Code">
private void initComponents() {

jLabel4 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();


















































































































// <editor-fold defaultstate="collapsed"
desc="Generated Code">
private void initComponents() {

jLabel4 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jTextField1 = new
javax.swing.JTextField();
jTextField2 = new
javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();

jLabel4.setText("jLabel4");


setDefaultCloseOperation(javax.swing.Window
Constants.EXIT_ON_CLOSE);

jLabel1.setText("X");

jLabel2.setText("Y");

jLabel3.setText("Conjunto");

jTextField2.addActionListener(new
java.awt.event.ActionListener() {
public void
actionPerformed(java.awt.event.ActionEvent
evt) {
jTextField2ActionPerformed(evt);
}
});

jButton1.setText("Consultar");
jButton1.addActionListener(new
java.awt.event.ActionListener() {
public void
actionPerformed(java.awt.event.ActionEvent
evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setText("Entrenar");
jButton2.addActionListener(new
java.awt.event.ActionListener() {
public void
actionPerformed(java.awt.event.ActionEvent
evt) {
jButton2ActionPerformed(evt);
}
});

jButton3.setText("Cargar");
jButton3.addActionListener(new
java.awt.event.ActionListener() {
public void
actionPerformed(java.awt.event.ActionEvent
evt) {
jButton3ActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout

.createParallelGroup(javax.swing.GroupLayou
t.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(

layout.createParallelGroup(

javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(

layout.createSequentialGroup()
.addGroup(

layout.createParallelGroup(

javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(

layout.createSequentialGroup()

.addComponent(

jLabel2)

.addGap(24,

24,

24)

.addComponent(

jTextField2,

javax.swing.GroupLayout.PREFERRED_SIZE,

50,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(

layout.createSequentialGroup()


















































































































.addGroup(

layout.createSequentialGroup()

.addComponent(

jLabel1)

.addGap(24,

24,

24)

.addComponent(

jTextField1,


javax.swing.GroupLayout.PREFERRED_SIZE,

50,


javax.swing.GroupLayout.PREFERRED_SIZE))
)
.addGap(61,
61,
61)

.addComponent(
jButton1,

javax.swing.GroupLayout.PREFERRED_SIZE,
110,

javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(

layout.createSequentialGroup()

.addComponent(
jLabel3)
.addGap(42,
42,
42)

.addComponent(
jLabel5,

javax.swing.GroupLayout.PREFERRED_SIZE,
50,

javax.swing.GroupLayout.PREFERRED_SIZE))
)
.addContainerGap(72,
Short.MAX_VALUE))
.addGroup(

javax.swing.GroupLayout.Alignment.TRAILI
NG,
layout.createSequentialGroup()
.addGap(0, 0,
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(
layout.createParallelGroup(

javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(
jButton3,

javax.swing.GroupLayout.Alignment.TRAILING,

javax.swing.GroupLayout.PREFERRED_SIZE,
110,

javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(
jButton2,

javax.swing.GroupLayout.Alignment.TRAILING,

javax.swing.GroupLayout.PREFERRED_SIZE,
110,

javax.swing.GroupLayout.PREFERRED_SIZE))));
layout.setVerticalGroup(layout

.createParallelGroup(javax.swing.GroupLayout
.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addComponent(jButton3)
.addPreferredGap(

javax.swing.LayoutStyle.ComponentPlacement.R
ELATED)
.addComponent(jButton2)
.addGap(8, 8, 8)
.addGroup(
layout.createParallelGroup(

javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(
jTextField1,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(
layout.createParallelGroup(

javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(

layout.createParallelGroup(

javax.swing.GroupLayout.Alignment.BASELINE)



















































































































layout.createParallelGroup(

javax.swing.GroupLayout.Alignment.BASEL
INE)

.addComponent(

jTextField2,

javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(

jButton1)))
.addGap(36, 36, 36)
.addGroup(

layout.createParallelGroup(

javax.swing.GroupLayout.Alignment.LEADI
NG)

.addComponent(jLabel3)
.addComponent(
jLabel5,

javax.swing.GroupLayout.PREFERRED_SIZE,
20,

javax.swing.GroupLayout.PREFERRED_SIZE)
)
.addGap(22, 22, 22)));

pack();
}// </editor-fold>

private void
jTextField2ActionPerformed(java.awt.event
.ActionEvent evt) {
// TODO add your handling code here:
}

int p1, p2;

private void
jButton1ActionPerformed(java.awt.event.Ac
tionEvent evt) {
Double[] x = {
Double.parseDouble(jTextField1.getText())
,

Double.parseDouble(jTextField2.getText(
)) };
cargarPesosBias();
perceptron.w[0] =
pesosBiasCargars.get(0).getPeso1();
perceptron.w[1] =
pesosBiasCargars.get(0).getPeso2();
perceptron.bias =
cargarPesosBias();
perceptron.w[0] =
pesosBiasCargars.get(0).getPeso1();
perceptron.w[1] =
pesosBiasCargars.get(0).getPeso2();
perceptron.bias =
pesosBiasCargars.get(0).getBias();
p1 = perceptron.consultar(x);
perceptron.w[0] =
pesosBiasCargars.get(1).getPeso1();
perceptron.w[1] =
pesosBiasCargars.get(1).getPeso2();
perceptron.bias =
pesosBiasCargars.get(1).getBias();
p2 = perceptron.consultar(x);
if (p1 == 0 && p2 == 1)
jLabel5.setText("A");
else if (p1 == 1 && p2 == 0)
jLabel5.setText("B");
else if (p1 == 0 && p2 == 0)
jLabel5.setText("C");
}

private void
jButton2ActionPerformed(java.awt.event.Actio
nEvent evt) {
try {
perceptron

.entrenamiento("C:\\\\Users\\\\Jonathan\\\\
Documents\\\\tablas\\\\perceptron1.txt");
String string1GuardarArchivo =
perceptron.w[0] + ","
+ perceptron.w[1] + "," +
perceptron.bias + ",";
FileWriter fichero = null;
PrintWriter pw = null;
try {
fichero = new FileWriter(

"C:\\\\Users\\\\Jonathan\\\\Documents\\\\ta
blas\\\\pesosBias.txt");
pw = new PrintWriter(fichero);

pw.println(string1GuardarArchivo);

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Nuevamente aprovechamos el
finally para
// asegurarnos que se cierra el
fichero.
if (null != fichero)
fichero.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
perceptron

.entrenamiento("C:\\\\Users\\\\Jonathan\\\\


















































































































e2.printStackTrace();
}
}
perceptron

.entrenamiento("C:\\\\Users\\\\Jonathan\\
\\Documents\\\\tablas\\\\perceptron2.txt");
String string2GuardarArchivo =
perceptron.w[0] + ","
+ perceptron.w[1] + "," +
perceptron.bias + ",";
FileWriter fichero2 = null;
PrintWriter pw2 = null;
try {
fichero2 = new FileWriter(

"C:\\\\Users\\\\Jonathan\\\\Documents\\\\
tablas\\\\pesosBias.txt",
true);
pw2 = new PrintWriter(fichero2);

pw2.println(string2GuardarArchivo);

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Nuevamente aprovechamos el
finally para
// asegurarnos que se cierra el
fichero.
if (null != fichero2)
fichero2.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
} catch (IOException ex) {

Logger.getLogger(Grafico.class.getName())
.log(Level.SEVERE, null,
ex);
}
}

private void
jButton3ActionPerformed(java.awt.event.Acti
onEvent evt) {
// TODO add your handling code here:
// AQUI
// cargarDatosArchivo();
try {
cargarPesosBias();

JOptionPane.showMessageDialog(null,
"Se han cargado los datos");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"error al cargar los datos");
}

}

List<String> datosPesosBias = new
ArrayList<>();

private void cargarDatosArchivo() {
try {
// Abrimos el archivo
FileInputStream fstream = new
FileInputStream(

"C:\\\\Users\\\\Jonathan\\\\Documents\\\
\tablas\\\\pesosBias.txt");
// Creamos el objeto de entrada
DataInputStream entrada = new
DataInputStream(fstream);
// Creamos el Buffer de Lectura
BufferedReader buffer = new
BufferedReader(new InputStreamReader(
entrada));
String strLinea;
// Leer el archivo linea por linea
while ((strLinea = buffer.readLine())
!= null) {
// Imprimimos la lnea por pantalla
// System.out.println (strLinea);
datosPesosBias.add(strLinea);
}
// Cerramos el archivo
entrada.close();

} catch (Exception e) {
System.err.println("Ocurrio un error:
" + e.getMessage());
e.printStackTrace();
}
}

List<PesosBiasCargar> pesosBiasCargars =
new ArrayList<PesosBiasCargar>();
Perceptron perceptron = new
Perceptron(2);

public void cargarPesosBias() {
try {
cargarDatosArchivo();
String subtemp;
int index = 0;
int cont = 0;



















































































































int cont = 0;
PesosBiasCargar cargar = new
PesosBiasCargar();
for (int i = 0; i <
datosPesosBias.size(); i++) {
if (i > 0) {
cont = 0;
cargar = new PesosBiasCargar();
index = 0;
}
for (int j = 0; j <
datosPesosBias.get(i).length(); j++) {
if (datosPesosBias.get(i).charAt(j)
== ',') {
cont++;
subtemp =
datosPesosBias.get(i).substring(index, j);
index = j + 1;
if (cont == 1) {

cargar.setPeso1(Double.parseDouble(subtemp
));
} else if (cont == 2) {

cargar.setPeso2(Double.parseDouble(subtemp
));
} else if (cont == 3) {

cargar.setBias(Double.parseDouble(subtemp)
);
}

}
if (cargar.getPeso1() != null &&
cargar.getPeso2() != null
&& cargar.getBias() != null) {
pesosBiasCargars.add(cargar);
}

}

}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* @param args
* the command line arguments
*/

public static void main(String args[]) {

try {
for
(javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.ge
tClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Grafico.c
lass.getName()).log(
java.util.logging.Level.SEVERE, null,
ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Grafico.c
lass.getName()).log(
java.util.logging.Level.SEVERE, null,
ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(Grafico.c
lass.getName()).log(
java.util.logging.Level.SEVERE, null,
ex);
} catch
(javax.swing.UnsupportedLookAndFeelException
ex) {
java.util.logging.Logger.getLogger(Grafico.c
lass.getName()).log(
java.util.logging.Level.SEVERE, null,
ex);
}
java.awt.EventQueue.invokeLater(new
Runnable() {
public void run() {
new Grafico().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}


Clase PsosBiasCargar.java






































Se realizo una grafica donde se representan los Perceptrones
usuados para realizar el laboratorio.

Figura 1: Grafica representative de los Perceptrones como
separadores lineales.
Para entrenar los perceptrones se utiliz la siguiente tabla.

Figura 2: Tabla entrenamiento Perceptrones

IV. RESULTADOS
Los resultados obtenidos son los siquientes:
/**
*
*/
package neurona;

/**
* @author Jonathan Arana, Tatiana Parreno
*
*/
public class PesosBiasCargar {

private Double peso1;
private Double peso2;
private Double bias;
public Double getPeso1() {
return peso1;
}
public void setPeso1(Double peso1) {
this.peso1 = peso1;
}
public Double getPeso2() {
return peso2;
}
public void setPeso2(Double peso2) {
this.peso2 = peso2;
}
public Double getBias() {
return bias;
}
public void setBias(Double bias) {
this.bias = bias;
}



}
A

C
B

Figura 3: Interfaz de Usuario sencilla


Figura 4: Carga de datos de los pesos y el bas.


Figura 5: Prueba conjunto C


Figura 6:Prueba Conjunto A.


Figura 7: Prueba Conjunto B.


Figura 8: Prueba 2 Conjunto B.


Figura 9:Prueba 2 Conjunto A.


Figura 10: Prueba 2 Conjunto C.

V. CONCLUSIONES
Para este laboratorio se utiliz un plano cartesiano y de
acuerdo con los requerimientos se realiz la interfaz de
usuario.
Se realiz un guardado de los pesos y el bas en un archivo de
extensin .txt para poder realizar con mayor rapidez las
consultas.
De acuerdo al aprendizaje el Perceptron responder a las
necesidades del usuario.


REFERENCES
[1]PERCEPTRN. WIKIPEDIA, LA ENCICLOPEDIA LIBRE,
APRIL 19, 2014.
HTTP://ES.WIKIPEDIA.ORG/W/INDEX.PHP?TITLE=PERCEP
TR% C3%B3N&OLDID=73895041.
[2] CARABALLO, GISSELL. ELECTRNICARADICAL:
COMPUERTAS LGICAS. ELECTRNICARADICAL,
SBADO, DE ENERO DE 2011.

También podría gustarte