viernes, 26 de junio de 2009

Hopfield Asociativo


/*********************************************************/
/* HOPFIELD ASOCIATIVO */
/*********************************************************/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Hopfield extends JFrame implements ActionListener {
public static final int NETWORK_SIZE = 8;
JTextField matrix[][] =
new JTextField[NETWORK_SIZE][NETWORK_SIZE];
JComboBox input[] = new JComboBox[NETWORK_SIZE];
JTextField output[] = new JTextField[NETWORK_SIZE];
JButton btnClear = new JButton("Clear");
JButton btnTrain = new JButton("Train");
JButton btnRun = new JButton("Run");
public Hopfield()
{
setTitle("Hopfield Neural Network");
JPanel connections = new JPanel();
connections.setLayout(
new GridLayout(NETWORK_SIZE,NETWORK_SIZE) );
for ( int row=0;row
for ( int col=0;col
matrix[row][col] = new JTextField(3);
matrix[row][col].setText("0");
connections.add(matrix[row][col]);
}
}
Container content = getContentPane();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
content.setLayout(gridbag);
c.fill = GridBagConstraints.NONE;
c.weightx = 1.0;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.NORTHWEST;
content.add(
new JLabel(
"Weight Matrix for the Hopfield Neural Network:"),c);
c.anchor = GridBagConstraints.CENTER;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(connections,c);
c.gridwidth = 1;
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel(
"Click \"Train\" to train the following pattern:"),c);
String options[] = { "0","1"};
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
for ( int i=0;i
input[i] = new JComboBox(options);
inputPanel.add(input[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(inputPanel,c);
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel("Click \"Run\" to see output pattern:"),c);
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new FlowLayout());
for ( int i=0;i
output[i] = new JTextField(3);
output[i].setEditable(false);
outputPanel.add(output[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(outputPanel,c);
JPanel buttonPanel = new JPanel();
btnClear = new JButton("Clear");
btnTrain = new JButton("Train");
btnRun = new JButton("Run");
btnClear.addActionListener(this);
btnTrain.addActionListener(this);
btnRun.addActionListener(this);
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(btnClear);
buttonPanel.add(btnTrain);
buttonPanel.add(btnRun);
content.add(buttonPanel,c);
pack();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension d = toolkit.getScreenSize();
setLocation(
(int)(d.width-this.getSize().getWidth())/2,
(int)(d.height-this.getSize().getHeight())/2 );
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if ( e.getSource()==btnRun )
run();
else if ( e.getSource()==btnClear )
clear();
else if ( e.getSource()==btnTrain )
train();
}
protected void run()
{
boolean pattern[] = new boolean[NETWORK_SIZE];
int wt[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
for ( int row=0;row
for ( int col=0;col
wt[row][col]=Integer.parseInt(matrix[row][col].getText());
for ( int row=0;row
int i = input[row].getSelectedIndex();
if ( i==0 )
pattern[row] = false;
else
pattern[row] = true;
}
Layer net = new Layer(wt);
net.activation(pattern);
for ( int row=0;row
if ( net.output[row] )
output[row].setText("1");
else
output[row].setText("0");
if ( net.output[row]==pattern[row] )
output[row].setBackground(java.awt.Color.green);
else
output[row].setBackground(java.awt.Color.red);
}
}
protected void clear()
{
for ( int row=0;row
for ( int col=0;col
matrix[row][col].setText("0");
}
protected void train()
{
int work[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
int bi[] = new int[NETWORK_SIZE];

for ( int x=0;x
if ( input[x].getSelectedIndex()==0 )
bi[x] = -1;
else
bi[x] = 1;
}
for ( int row=0;row
for ( int col=0;col
work[row][col] = bi[row]*bi[col];
}
for ( int x=0;x
work[x][x] =-1;
for ( int row=0;row
for ( int col=0;col
int i = Integer.parseInt(matrix[row][col].getText());
matrix[row][col].setText( "" + (i+work[row][col]));
}
}
static public void main(String args[])
{
JFrame f = new Hopfield();
f.show();
}
}
public class Layer {
protected Neuron neuron[] = new Neuron[8];
protected boolean output[] = new boolean[8];
protected int neurons;
public static final double lambda = 1.0;
Layer(int weights[][])
{
neurons = weights[0].length;
neuron = new Neuron[neurons];
output = new boolean[neurons];
for ( int i=0;i
neuron[i]=new Neuron(weights[i]);
}

public boolean threshold(int k)
{
double kk = k * lambda;
double a = Math.exp( kk );
double b = Math.exp( -kk );
double tanh = (a-b)/(a+b);
return(tanh>=0);
}
void activation(boolean pattern[])
{
int i,j;
for ( i=0;i<8;i++ ) {
neuron[i].activation = neuron[i].act(pattern);
output[i] = threshold(neuron[i].activation);
}
}
}
public class Neuron {
public int weightv[];
public int activation;
public Neuron(int in[])
{
weightv = in;
}

lunes, 1 de junio de 2009

Aprendizaje Competitivo A B C

public class Main {
public static void main(String[] args) {
int[][] mata = new int[10][10];
int[][] matb = new int[10][10];
int[][] matc = new int[10][10];
int i=0,j=0, jc=0;
/* MATRIZ A */
mata[0][0]=0;
mata[0][1]=1;
mata[0][2]=1;
mata[0][3]=1;
mata[0][4]=0;

mata[1][0]=0;
mata[1][1]=1;
mata[1][2]=0;
mata[1][3]=1;
mata[1][4]=0;

mata[2][0]=0;
mata[2][1]=1;
mata[2][2]=1;
mata[2][3]=1;
mata[2][4]=0;

mata[3][0]=0;
mata[3][1]=1;
mata[3][2]=0;
mata[3][3]=1;
mata[3][4]=0;

mata[4][0]=0;
mata[4][1]=1;
mata[4][2]=0;
mata[4][3]=1;
mata[4][4]=0;

/* MATRIZ B */

matb[0][0]=1;
matb[0][1]=1;
matb[0][2]=1;
matb[0][3]=1;
matb[0][4]=0;

matb[1][0]=0;
matb[1][1]=1;
matb[1][2]=0;
matb[1][3]=1;
matb[1][4]=0;

matb[2][0]=0;
matb[2][1]=1;
matb[2][2]=1;
matb[2][3]=1;
matb[2][4]=0;

matb[3][0]=0;
matb[3][1]=1;
matb[3][2]=0;
matb[3][3]=1;
matb[3][4]=0;

matb[4][0]=1;
matb[4][1]=1;
matb[4][2]=1;
matb[4][3]=1;
matb[4][4]=0;

/* MATRIZ C */
matc[0][0]=0;
matc[0][1]=1;
matc[0][2]=1;
matc[0][3]=1;
matc[0][4]=0;

matc[1][0]=0;
matc[1][1]=1;
matc[1][2]=0;
matc[1][3]=0;
matc[1][4]=0;

matc[2][0]=0;
matc[2][1]=1;
matc[2][2]=0;
matc[2][3]=0;
matc[2][4]=0;

matc[3][0]=0;
matc[3][1]=1;
matc[3][2]=0;
matc[3][3]=0;
matc[3][4]=0;

matc[4][0]=0;
matc[4][1]=1;
matc[4][2]=1;
matc[4][3]=1;
matc[4][4]=0;


for(i=0; i<=4 ; i++){
for (j=0; j<=4; j++){
System.out.print("\t"+mata[i][j]);
}
System.out.println("");
}

/* CARGA POR FILAS EN EL VECTOR */
int [] vector = new int[25];
jc=0;
while (jc < 25)
{
for(i=0; i<5 ; i++){
for (j=0; j<5; j++){
vector[jc]= mata[i][j];
jc=jc+1;
}
}
}
System.out.println("");
for(i=0; i<=24 ; i++){
System.out.print("\t"+vector[i]);
}

/* CARGA POR FILAS EN EL VECTOR */
int [] vector1 = new int[5];
int cont=0;
for(i=0; i<5 ; i++){
cont=0;
for (j=0; j<5; j++){
if(mata[i][j]==1)
cont = cont+1;
}
vector1[i]=cont;
}

System.out.println("");
for(i=0; i<5 ; i++){
System.out.print("\t"+vector1[i]);
}
System.out.println("\n\ngracias");
}
}

Abc

public class Main {
public static void main(String[] args) {
int[][] mata = new int[10][10];
int[][] matb = new int[10][10];
int[][] matc = new int[10][10];
int i=0,j=0, jc=0;
/* MATRIZ A */
mata[0][0]=0;
mata[0][1]=1;
mata[0][2]=1;
mata[0][3]=1;
mata[0][4]=0;

mata[1][0]=0;
mata[1][1]=1;
mata[1][2]=0;
mata[1][3]=1;
mata[1][4]=0;

mata[2][0]=0;
mata[2][1]=1;
mata[2][2]=1;
mata[2][3]=1;
mata[2][4]=0;

mata[3][0]=0;
mata[3][1]=1;
mata[3][2]=0;
mata[3][3]=1;
mata[3][4]=0;

mata[4][0]=0;
mata[4][1]=1;
mata[4][2]=0;
mata[4][3]=1;
mata[4][4]=0;

/* MATRIZ B */

matb[0][0]=1;
matb[0][1]=1;
matb[0][2]=1;
matb[0][3]=1;
matb[0][4]=0;

matb[1][0]=0;
matb[1][1]=1;
matb[1][2]=0;
matb[1][3]=1;
matb[1][4]=0;

matb[2][0]=0;
matb[2][1]=1;
matb[2][2]=1;
matb[2][3]=1;
matb[2][4]=0;

matb[3][0]=0;
matb[3][1]=1;
matb[3][2]=0;
matb[3][3]=1;
matb[3][4]=0;

matb[4][0]=1;
matb[4][1]=1;
matb[4][2]=1;
matb[4][3]=1;
matb[4][4]=0;

/* MATRIZ C */
matc[0][0]=0;
matc[0][1]=1;
matc[0][2]=1;
matc[0][3]=1;
matc[0][4]=0;

matc[1][0]=0;
matc[1][1]=1;
matc[1][2]=0;
matc[1][3]=0;
matc[1][4]=0;

matc[2][0]=0;
matc[2][1]=1;
matc[2][2]=0;
matc[2][3]=0;
matc[2][4]=0;

matc[3][0]=0;
matc[3][1]=1;
matc[3][2]=0;
matc[3][3]=0;
matc[3][4]=0;

matc[4][0]=0;
matc[4][1]=1;
matc[4][2]=1;
matc[4][3]=1;
matc[4][4]=0;


for(i=0; i<=4 ; i++){
for (j=0; j<=4; j++){
System.out.print("\t"+mata[i][j]);
}
System.out.println("");
}

/* CARGA POR FILAS EN EL VECTOR */
int [] vector = new int[25];
jc=0;
while (jc < 25)
{
for(i=0; i<5 ; i++){
for (j=0; j<5; j++){
vector[jc]= mata[i][j];
jc=jc+1;
}
}
}
System.out.println("");
for(i=0; i<=24 ; i++){
System.out.print("\t"+vector[i]);
}

/* CARGA POR FILAS EN EL VECTOR */
int [] vector1 = new int[5];
int cont=0;
for(i=0; i<5 ; i++){
cont=0;
for (j=0; j<5; j++){
if(mata[i][j]==1)
cont = cont+1;
}
vector1[i]=cont;
}

System.out.println("");
for(i=0; i<5 ; i++){
System.out.print("\t"+vector1[i]);
}
System.out.println("\n\ngracias");
}
}

Aprendizaje competitivo (abecedario)

package vec;

public class Main {

public static void main(String[] args) {
// TODO code application logic here
int[][] mata = new int[10][10];
int[][] matb = new int[10][10];
int[][] matc = new int[10][10];
int i=0,j=0, jc=0;
/********************/
/* MATRIZ A */
/********************/
mata[0][0]=0;
mata[0][1]=1;
mata[0][2]=1;
mata[0][3]=1;
mata[0][4]=0;

mata[1][0]=0;
mata[1][1]=1;
mata[1][2]=0;
mata[1][3]=1;
mata[1][4]=0;

mata[2][0]=0;
mata[2][1]=1;
mata[2][2]=1;
mata[2][3]=1;
mata[2][4]=0;

mata[3][0]=0;
mata[3][1]=1;
mata[3][2]=0;
mata[3][3]=1;
mata[3][4]=0;

mata[4][0]=0;
mata[4][1]=1;
mata[4][2]=0;
mata[4][3]=1;
mata[4][4]=0;

/********************/
/* MATRIZ B */
/********************/

matb[0][0]=1;
matb[0][1]=1;
matb[0][2]=1;
matb[0][3]=1;
matb[0][4]=0;

matb[1][0]=0;
matb[1][1]=1;
matb[1][2]=0;
matb[1][3]=1;
matb[1][4]=0;

matb[2][0]=0;
matb[2][1]=1;
matb[2][2]=1;
matb[2][3]=1;
matb[2][4]=0;

matb[3][0]=0;
matb[3][1]=1;
matb[3][2]=0;
matb[3][3]=1;
matb[3][4]=0;

matb[4][0]=1;
matb[4][1]=1;
matb[4][2]=1;
matb[4][3]=1;
matb[4][4]=0;

/********************/
/* MATRIZ C */
/********************/
matc[0][0]=0;
matc[0][1]=1;
matc[0][2]=1;
matc[0][3]=1;
matc[0][4]=0;

matc[1][0]=0;
matc[1][1]=1;
matc[1][2]=0;
matc[1][3]=0;
matc[1][4]=0;

matc[2][0]=0;
matc[2][1]=1;
matc[2][2]=0;
matc[2][3]=0;
matc[2][4]=0;

matc[3][0]=0;
matc[3][1]=1;
matc[3][2]=0;
matc[3][3]=0;
matc[3][4]=0;

matc[4][0]=0;
matc[4][1]=1;
matc[4][2]=1;
matc[4][3]=1;
matc[4][4]=0;


for(i=0; i<=4 ; i++){
for (j=0; j<=4; j++){
System.out.print("\t"+mata[i][j]);
}
System.out.println("");
}

/*********************************************/
/* CARGA POR FILAS EN EL VECTOR */
/*********************************************/
int [] vector = new int[25];
jc=0;
while (jc < 25)
{
for(i=0; i<5 ; i++){
for (j=0; j<5; j++){
vector[jc]= mata[i][j];
jc=jc+1;
}
}
}
System.out.println("");
for(i=0; i<=24 ; i++){
System.out.print("\t"+vector[i]);
}

/*********************************************/
/* CARGA POR FILAS EN EL VECTOR */
/*********************************************/
int [] vector1 = new int[5];
int cont=0;
for(i=0; i<5 ; i++){
cont=0;
for (j=0; j<5; j++){
if(mata[i][j]==1)
cont = cont+1;
}
vector1[i]=cont;
}

System.out.println("");
for(i=0; i<5 ; i++){
System.out.print("\t"+vector1[i]);
}
System.out.println("\n\ngracias");
}
}

miércoles, 27 de mayo de 2009

Hopfield Asociativa



import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Hopfield extends JFrame implements ActionListener {
public static final int NETWORK_SIZE = 8;
JTextField matrix[][] =
new JTextField[NETWORK_SIZE][NETWORK_SIZE];
JComboBox input[] = new JComboBox[NETWORK_SIZE];
JTextField output[] = new JTextField[NETWORK_SIZE];
JButton btnClear = new JButton("Clear");
JButton btnTrain = new JButton("Train");
JButton btnRun = new JButton("Run");
public Hopfield()
{
setTitle("Hopfield Neural Network");
JPanel connections = new JPanel();
connections.setLayout(
new GridLayout(NETWORK_SIZE,NETWORK_SIZE) );
for ( int row=0;row
for ( int col=0;col
matrix[row][col] = new JTextField(3);
matrix[row][col].setText("0");
connections.add(matrix[row][col]);
}
}
Container content = getContentPane();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
content.setLayout(gridbag);
c.fill = GridBagConstraints.NONE;
c.weightx = 1.0;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.NORTHWEST;
content.add(
new JLabel(
"Weight Matrix for the Hopfield Neural Network:"),c);
c.anchor = GridBagConstraints.CENTER;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(connections,c);
c.gridwidth = 1;
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel(
"Click \"Train\" to train the following pattern:"),c);
String options[] = { "0","1"};
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
for ( int i=0;i
input[i] = new JComboBox(options);
inputPanel.add(input[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(inputPanel,c);
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel("Click \"Run\" to see output pattern:"),c);
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new FlowLayout());
for ( int i=0;i
output[i] = new JTextField(3);
output[i].setEditable(false);
outputPanel.add(output[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(outputPanel,c);
JPanel buttonPanel = new JPanel();
btnClear = new JButton("Clear");
btnTrain = new JButton("Train");
btnRun = new JButton("Run");
btnClear.addActionListener(this);
btnTrain.addActionListener(this);
btnRun.addActionListener(this);
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(btnClear);
buttonPanel.add(btnTrain);
buttonPanel.add(btnRun);
content.add(buttonPanel,c);
pack();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension d = toolkit.getScreenSize();
setLocation(
(int)(d.width-this.getSize().getWidth())/2,
(int)(d.height-this.getSize().getHeight())/2 );
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if ( e.getSource()==btnRun )
run();
else if ( e.getSource()==btnClear )
clear();
else if ( e.getSource()==btnTrain )
train();
}
protected void run()
{
boolean pattern[] = new boolean[NETWORK_SIZE];
int wt[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
for ( int row=0;row
for ( int col=0;col
wt[row][col]=Integer.parseInt(matrix[row][col].getText());
for ( int row=0;row
int i = input[row].getSelectedIndex();
if ( i==0 )
pattern[row] = false;
else
pattern[row] = true;
}
Layer net = new Layer(wt);
net.activation(pattern);
for ( int row=0;row
if ( net.output[row] )
output[row].setText("1");
else
output[row].setText("0");
if ( net.output[row]==pattern[row] )
output[row].setBackground(java.awt.Color.green);
else
output[row].setBackground(java.awt.Color.red);
}
}
protected void clear()
{
for ( int row=0;row
for ( int col=0;col
matrix[row][col].setText("0");
}
protected void train()
{
int work[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
int bi[] = new int[NETWORK_SIZE];

for ( int x=0;x
if ( input[x].getSelectedIndex()==0 )
bi[x] = -1;
else
bi[x] = 1;
}
for ( int row=0;row
for ( int col=0;col
work[row][col] = bi[row]*bi[col];
}
for ( int x=0;x
work[x][x] =-1;
for ( int row=0;row
for ( int col=0;col
int i = Integer.parseInt(matrix[row][col].getText());
matrix[row][col].setText( "" + (i+work[row][col]));
}
}
static public void main(String args[])
{
JFrame f = new Hopfield();
f.show();
}
}
public class Layer {
protected Neuron neuron[] = new Neuron[8];
protected boolean output[] = new boolean[8];
protected int neurons;
public static final double lambda = 1.0;
Layer(int weights[][])
{
neurons = weights[0].length;
neuron = new Neuron[neurons];
output = new boolean[neurons];
for ( int i=0;i
neuron[i]=new Neuron(weights[i]);
}

public boolean threshold(int k)
{
double kk = k * lambda;
double a = Math.exp( kk );
double b = Math.exp( -kk );
double tanh = (a-b)/(a+b);
return(tanh>=0);
}
void activation(boolean pattern[])
{
int i,j;
for ( i=0;i<8;i++ ) {
neuron[i].activation = neuron[i].act(pattern);
output[i] = threshold(neuron[i].activation);
}
}
}
public class Neuron {
public int weightv[];
public int activation;
public Neuron(int in[])
{
weightv = in;
}
public int act(boolean x[] )
{
int i;
int a=0;
for ( i=0;i
if ( x[i] )
a+=weightv[i];
return a;
}
}

lunes, 25 de mayo de 2009

Hopfield Asociativa



import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Hopfield extends JFrame implements ActionListener {
public static final int NETWORK_SIZE = 8;
JTextField matrix[][] =
new JTextField[NETWORK_SIZE][NETWORK_SIZE];
JComboBox input[] = new JComboBox[NETWORK_SIZE];
JTextField output[] = new JTextField[NETWORK_SIZE];
JButton btnClear = new JButton("Clear");
JButton btnTrain = new JButton("Train");
JButton btnRun = new JButton("Run");
public Hopfield()
{
setTitle("Hopfield Neural Network");
JPanel connections = new JPanel();
connections.setLayout(
new GridLayout(NETWORK_SIZE,NETWORK_SIZE) );
for ( int row=0;row
for ( int col=0;col
matrix[row][col] = new JTextField(3);
matrix[row][col].setText("0");
connections.add(matrix[row][col]);
}
}
Container content = getContentPane();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
content.setLayout(gridbag);
c.fill = GridBagConstraints.NONE;
c.weightx = 1.0;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.NORTHWEST;
content.add(
new JLabel(
"Weight Matrix for the Hopfield Neural Network:"),c);
c.anchor = GridBagConstraints.CENTER;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(connections,c);
c.gridwidth = 1;
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel(
"Click \"Train\" to train the following pattern:"),c);
String options[] = { "0","1"};
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
for ( int i=0;i
input[i] = new JComboBox(options);
inputPanel.add(input[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(inputPanel,c);
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel("Click \"Run\" to see output pattern:"),c);
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new FlowLayout());
for ( int i=0;i
output[i] = new JTextField(3);
output[i].setEditable(false);
outputPanel.add(output[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(outputPanel,c);
JPanel buttonPanel = new JPanel();
btnClear = new JButton("Clear");
btnTrain = new JButton("Train");
btnRun = new JButton("Run");
btnClear.addActionListener(this);
btnTrain.addActionListener(this);
btnRun.addActionListener(this);
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(btnClear);
buttonPanel.add(btnTrain);
buttonPanel.add(btnRun);
content.add(buttonPanel,c);
pack();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension d = toolkit.getScreenSize();
setLocation(
(int)(d.width-this.getSize().getWidth())/2,
(int)(d.height-this.getSize().getHeight())/2 );
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if ( e.getSource()==btnRun )
run();
else if ( e.getSource()==btnClear )
clear();
else if ( e.getSource()==btnTrain )
train();
}
protected void run()
{
boolean pattern[] = new boolean[NETWORK_SIZE];
int wt[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
for ( int row=0;row
for ( int col=0;col
wt[row][col]=Integer.parseInt(matrix[row][col].getText());
for ( int row=0;row
int i = input[row].getSelectedIndex();
if ( i==0 )
pattern[row] = false;
else
pattern[row] = true;
}
Layer net = new Layer(wt);
net.activation(pattern);
for ( int row=0;row
if ( net.output[row] )
output[row].setText("1");
else
output[row].setText("0");
if ( net.output[row]==pattern[row] )
output[row].setBackground(java.awt.Color.green);
else
output[row].setBackground(java.awt.Color.red);
}
}
protected void clear()
{
for ( int row=0;row
for ( int col=0;col
matrix[row][col].setText("0");
}
protected void train()
{
int work[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
int bi[] = new int[NETWORK_SIZE];

for ( int x=0;x
if ( input[x].getSelectedIndex()==0 )
bi[x] = -1;
else
bi[x] = 1;
}
for ( int row=0;row
for ( int col=0;col
work[row][col] = bi[row]*bi[col];
}
for ( int x=0;x
work[x][x] =-1;
for ( int row=0;row
for ( int col=0;col
int i = Integer.parseInt(matrix[row][col].getText());
matrix[row][col].setText( "" + (i+work[row][col]));
}
}
static public void main(String args[])
{
JFrame f = new Hopfield();
f.show();
}
}
public class Layer {
protected Neuron neuron[] = new Neuron[8];
protected boolean output[] = new boolean[8];
protected int neurons;
public static final double lambda = 1.0;
Layer(int weights[][])
{
neurons = weights[0].length;
neuron = new Neuron[neurons];
output = new boolean[neurons];
for ( int i=0;i
neuron[i]=new Neuron(weights[i]);
}

public boolean threshold(int k)
{
double kk = k * lambda;
double a = Math.exp( kk );
double b = Math.exp( -kk );
double tanh = (a-b)/(a+b);
return(tanh>=0);
}
void activation(boolean pattern[])
{
int i,j;
for ( i=0;i<8;i++ ) {
neuron[i].activation = neuron[i].act(pattern);
output[i] = threshold(neuron[i].activation);
}
}
}
public class Neuron {
public int weightv[];
public int activation;
public Neuron(int in[])
{
weightv = in;
}
public int act(boolean x[] )
{
int i;
int a=0;
for ( i=0;i
if ( x[i] )
a+=weightv[i];
return a;
}}

CODIGO BACKPROPAGATION



package redesneuronales;
//import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//import java.lang.String;
//import javax.vecmath.Matrix3d;

public class Backpropagation {

public int k=0;

//Numero de neuronas a la entrada y la saldida de la red
int numEntradas, numSalidas;

// Numero de capas en la red
int numCapas;

// Numero de neuronas por capa
int numNeuronas_Capas [];
Matriz coefCompen [];

Matriz mPesos [];

Matriz outCapa[] = new Matriz [numCapas+1];
Matriz delta_propa[] = new Matriz[numCapas+1];
JRadioButton jRadioButton1 = new JRadioButton();
JButton jButton1 = new JButton();

public Backpropagation(){
String aux = JOptionPane.showInputDialog(null,
"Ingrese el numero de elementos de entrada",
"",JOptionPane.DEFAULT_OPTION);


numEntradas = Integer.parseInt(aux);
aux = JOptionPane.showInputDialog(null,
"Ingrese el numero de capas de la red",
"",JOptionPane.DEFAULT_OPTION);

numCapas = Integer.parseInt(aux);

aux = JOptionPane.showInputDialog(null,
"Ingrese el numero de elementos a la salida",
"",JOptionPane.DEFAULT_OPTION);

numSalidas = Integer.parseInt(aux);


// Llena el vector con el nuemro de neuronas por capa
numNeuronas_Capas = new int[numCapas];
for (int i = 0 ; i < numCapas; i++){
aux = JOptionPane.showInputDialog(null,
"ingrese el nuemro de neuronas para la capa " + (i+1)
,"",
JOptionPane.DEFAULT_OPTION);
numNeuronas_Capas[i] = Integer.parseInt(aux);
}


// Matriz de coeficientes de activacion
coefCompen = new Matriz [numCapas+1];
for (int i= 0; i < numCapas; i++)
coefCompen[i] = new Matriz(numNeuronas_Capas[i],1,-1,1);
coefCompen[numCapas] = new Matriz(numSalidas,1,-1,1);

// Matriz de pesos aleatorios
mPesos = new Matriz [numCapas+1];
for (int i = 0; i < numCapas; i++){
if (i == 0)
mPesos[i] = new Matriz (numNeuronas_Capas[i],numEntradas,-3,3);
else
mPesos[i] = new Matriz(numNeuronas_Capas[i],numNeuronas_Capas[i-1],-3,3);
}
mPesos[numCapas] = new Matriz ( numSalidas, numNeuronas_Capas[numCapas-1],-3,3);

}

// Propagacion directa
public Matriz [] propagacionDirecta(Matriz entrada){
Matriz salidaCapa[] = new Matriz [numCapas+1];

int i;
salidaCapa[0] = ((mPesos[0].multiplica(entrada)).suma(coefCompen[0])).logsigActivacion();
for (i = 1 ; i <= numCapas; i++){
salidaCapa[i] = ((mPesos[i].multiplica(salidaCapa[i-1])).suma(coefCompen[i])).logsigActivacion();
}
outCapa = salidaCapa;

return salidaCapa;
}

public Matriz calculoError(Matriz entrada, Matriz salida_real){
Matriz error2 = new Matriz();
Matriz error = new Matriz();
error = salida_real.resta(propagacionDirecta(entrada)[numCapas]);
error2 = (error.trans()).multiplica(error);

return error;
}

public Matriz [] propagacionInversa(Matriz errorSalida){
Matriz m[] = new Matriz[numCapas+1];
Matriz delta [] = new Matriz [numCapas+1];
Matriz ones = new Matriz(errorSalida.numFilas,errorSalida.numCols,"ones");
Matriz net_inv = new Matriz();

for (int i = 0; i <= numCapas; i++){
m[i] = mPesos[i].trans();
}

delta[numCapas] = errorSalida.multComponente(
(outCapa[numCapas]).multComponente((ones.resta(outCapa[numCapas]))));
net_inv = m[numCapas].multiplica(delta[numCapas]);
for (int i = numCapas-1; i >= 0 ; i--){
ones = new Matriz(net_inv.numFilas,net_inv.numCols,"ones");
delta[i] = net_inv.multComponente(
(outCapa[i]).multComponente((ones.resta(outCapa[i]))));
net_inv = m[i].multiplica(delta[i]);
}
delta_propa = delta;

return delta;
}

/**
* Actualiza los pesos luego que el se ha propagado el error
*
* @param entrada Matriz la entrada
* @param rata double la rata de aprendizaje
* @return Matriz[] regresa las matrices de vada capa ya actualizados
*/
public Matriz [] actuliazacionPesos(Matriz entrada,double rata){
Matriz temp[] = new Matriz [numCapas+1];
Matriz t[] = new Matriz [numCapas+1];

rata = 2*rata;
temp[0] = mPesos[0].suma(
(delta_propa[0].productoEscalarMatriz(rata)).multiplica(entrada.trans()));
t[0] = coefCompen[0].suma(delta_propa[0].productoEscalarMatriz(rata));

for (int i = 1 ; i <= numCapas; i++){
temp[i] = mPesos[i].suma(
(delta_propa[i].productoEscalarMatriz(rata)).multiplica((outCapa[i-1].trans())));
t[i] = coefCompen[i].suma(delta_propa[i].productoEscalarMatriz(rata));
}
mPesos = temp;
coefCompen = t;
return temp;
}

/**
* Simula la red neuronal dependiendo de la entrada presentada a la red
*
* @param patronesEntrada Matriz el patron de entrada
* @param aux String
* @return Matriz[]
*/
public Matriz [] simulacion(Matriz patronesEntrada,String aux){
Matriz p [] = new Matriz [patronesEntrada.numCols];
Matriz t[] = new Matriz [patronesEntrada.numCols];
Matriz salidaCapa[] = new Matriz [numCapas+1];

for (int j = 0; j < patronesEntrada.numCols;j++){
p[j] = new Matriz(patronesEntrada.numFilas,1);
for (int i = 0; i < patronesEntrada.numFilas;i++)
p[j].matrizDbl[i][0] = patronesEntrada.matrizDbl[i][0];
salidaCapa = propagacionDirecta(p[j]);
t[j] = salidaCapa[numCapas];
}
for (int j = 0; j < patronesEntrada.numCols; j++){
System.out.print("entradas\n"+p[j].toString());
System.out.print("salidas\n"+t[j].toString());
}
return t;
}

/**
* devuelva la salida real de la red neuronal cuando de le presenta el
* patron p
* @param p Matriz patron de entrada
* @return Matriz patron de salida a
*/
public Matriz simulacion(Matriz p){
Matriz salida = new Matriz (numSalidas,1);
salida = propagacionDirecta(p)[numCapas];

return salida;
}



public void entrenamientoOnLine(Matriz [] patronEntrada,Matriz [] salida){

Matriz e = new Matriz();
Matriz error2 = new Matriz(1,1);

double errorDouble = 0;

for (int i = 0; i < patronEntrada.length; i++){
e = salida[i].resta(simulacion(patronEntrada[i]));
error2 = (e.trans()).multiplica(e);
errorDouble = error2.matrizDbl[0][0];

while (Math.sqrt(errorDouble) > 0.001){
//System.out.println(i);
this.propagacionInversa(e);
this.actuliazacionPesos(patronEntrada[i],0.1);
k += 1;
//System.out.println(error2.toString());
e = salida[i].resta(simulacion(patronEntrada[i]));
error2 = (e.trans()).multiplica(e);
errorDouble = error2.matrizDbl[0][0];
i = 0;
//System.out.println(this.mPesos[0].toString());
}
}
//System.out.print("prueba\n"+simulacion(patronEntrada).toString());
}

public void entrenamientoOffLine(Matriz [] P, Matriz [] T){
Matriz e = new Matriz(P[0].numFilas,1), E;
Matriz error2 = new Matriz(1,1);
double errorDouble = 100;

while (Math.sqrt(errorDouble) > 0.1)
//for (int k = 0; k < 100 ; k++)
{
for (int i = 0; i < P.length; i++){
e = (T[i].resta(simulacion(P[i]))).suma(e);
}
System.out.println(e.toString());
E = e.productoEscalarMatriz(1.0 / (double) P.length);
error2 = (E.trans()).multiplica(E);
errorDouble = error2.matrizDbl[0][0];
System.out.print(errorDouble + "\n");
this.propagacionInversa(E);
for (int i = 0; i < P.length; i++)
this.actuliazacionPesos(P[i],0.1);
k += 1;
}



}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,"cuerpo","titulo",JOptionPane.DEFAULT_OPTION);
}
}

********************************************************************
**********RECONOCIMIENTO DE MONEDAS*********************************
********************************************************************


Module calculos
Dim resp(256) As Integer
Sub bitmap_to_matriz(ByRef matr(,) As Integer, ByRef mibitmap As Bitmap)
Dim i, j, nf, nc As Integer
Dim micolor As Color
nc = UBound(matr, 2) 'UBound: debuelve el maximo valor permitido de un arreglo
nf = UBound(matr, 1)

For i = 0 To nf
For j = 0 To nc
micolor = mibitmap.GetPixel(j, i) 'getpixel: metodo de mapa de bits y obtiene el color
matr(i, j) = micolor.R
Next
Next
End Sub

Sub matriz_to_bitmap(ByRef matr(,) As Integer, ByRef mibitmap As Bitmap)
Dim i, j, nf, nc, valor As Integer
Dim micolor As Color
nc = UBound(matr, 2) 'UBound: debuelve el maximo valor permitido de un arreglo
nf = UBound(matr, 1)

For i = 0 To nf
For j = 0 To nc
valor = matr(i, j)
micolor = Color.FromArgb(255, valor, valor, valor)
mibitmap.SetPixel(j, i, micolor)
Next
Next
End Sub

Sub normalizar255(ByRef reales(,) As Double, ByRef matriz(,) As Integer)
Dim vmin As Double
Dim vmax As Double
Dim i, j, nc, nf As Integer
vmin = minval(reales)
vmax = maxval(reales)
nc = UBound(reales, 2)
nf = UBound(reales, 1)
'vmin = reales(0, 0)
For i = 0 To nf
For j = 0 To nc
matriz(i, j) = (reales(i, j) - vmin) * 255 / (vmax - vmin)
If (matriz(i, j) < 0) Then matriz(i, j) = 0
If (matriz(i, j) > 255) Then matriz(i, j) = 255
Next
Next
End Sub

Sub normalizar255_E(ByRef reales(,) As Integer, ByRef matriz(,) As Integer)
Dim vmin As Double
Dim vmax As Double
Dim i, j, nc, nf, cont As Integer
vmin = minval(reales)
vmax = maxval(reales)
nc = UBound(reales, 2)
nf = UBound(reales, 1)
cont = 1
For i = 0 To nf
For j = 0 To nc
matriz(i, j) = (reales(i, j) - vmin) * 255 / (vmax - vmin)
If (matriz(i, j) < 0) Then matriz(i, j) = 0
If (matriz(i, j) > 255) Then matriz(i, j) = cont
Next
cont += 1
Next
End Sub

Function minval(ByRef reales(,) As Integer) As Integer
Dim i, j, nc, nf As Integer
Dim vmin As Double
nc = UBound(reales, 2)
nf = UBound(reales, 1)
vmin = reales(0, 0)
For i = 0 To nf
For j = 0 To nc 'indice de columnas
If (vmin > reales(i, j)) Then vmin = reales(i, j)
Next
Next
Return vmin
End Function

Function maxval(ByRef reales(,) As Integer) As Integer
Dim i, j, nc, nf As Integer
Dim vmax As Double
nc = UBound(reales, 2)
nf = UBound(reales, 1)
vmax = reales(0, 0)
For i = 0 To nf
For j = 0 To nc 'indice de columnas
If (vmax < reales(i, j)) Then vmax = reales(i, j)
Next
Next
Return vmax
End Function

Function minval(ByRef reales(,) As Double) As Double
Dim i, j, nc, nf As Integer
Dim vmin As Double
nc = UBound(reales, 2)
nf = UBound(reales, 1)
vmin = reales(0, 0)
For i = 0 To nf
For j = 0 To nc 'indice de columnas
If (vmin > reales(i, j)) Then vmin = reales(i, j)
Next
Next
Return vmin
End Function
Function maxval(ByRef reales(,) As Double) As Double
Dim i, j, nc, nf As Integer
Dim vmax As Double
nc = UBound(reales, 2)
nf = UBound(reales, 1)
vmax = reales(0, 0)
For i = 0 To nf
For j = 0 To nc 'indice de columnas
If (vmax < reales(i, j)) Then vmax = reales(i, j)
Next
Next
Return vmax
End Function

Sub color_gris(ByRef imagen1 As Bitmap, ByRef imagen2 As Bitmap)
Dim i, j As Integer
Dim color1, color2 As Color
Dim grisd As Double
Dim gris As Integer
Dim r, g, b As Integer
Dim mr(imagen1.Height - 1, imagen1.Width - 1) As Integer
' bitmap_to_matriz(mr, imagen1)
For i = 0 To imagen1.Height - 1
For j = 0 To imagen1.Width - 1
color1 = imagen1.GetPixel(j, i)
r = color1.R
g = color1.G
b = color1.B
grisd = 0.299 * r + 0.587 * g + 0.114 * b
gris = Math.Round(grisd)
If (gris > 255) Then gris = 255
color2 = Color.FromArgb(255, gris, gris, gris)
imagen2.SetPixel(j, i, color2)
Next
Next
End Sub

Sub histograma1(ByRef mibitmap As Bitmap, ByRef arreglo() As Long)
Dim i, j, valor As Integer
Dim micolor As Color
'nc = UBound(matr, 2) --> y en el bitmap(alto de pixeles)
'nf = UBound(matr, 1) --> x en el bitmap(ancho de pixeles)

'j --> columnas : i --> filas
For i = 0 To mibitmap.Height - 1
For j = 0 To mibitmap.Width - 1
micolor = mibitmap.GetPixel(j, i) 'getpixel: metodo de mapa de bits y obtiene el color
'si es pa los 3 colores hay q poner los 3 componentes
valor = micolor.R
arreglo(valor) += 1

Next
Next
For i = 0 To 255
If arreglo(i) <> 0 Then
'MessageBox.Show(arreglo(i), i, MessageBoxButtons.OK)
End If

Next
End Sub

Sub ordenar(ByRef vec() As Integer, ByRef mediana As Integer)
Dim i, j, n, aux As Integer
n = UBound(vec, 1)

For i = 0 To n - 1
For j = 0 To n - 1
If (vec(j) > vec(j + 1)) Then
aux = vec(j)
vec(j) = vec(j + 1)
vec(j + 1) = aux
End If
Next
Next
mediana = vec(Math.Abs(n / 2))
End Sub

Sub filtro_mediana(ByRef imagen As Bitmap, ByRef tamano As Integer)
Dim nx, ny, i, j, i1, j1, i3, j3, nFiltro, vPixel, mediana As Integer
nx = imagen.Width - 1 : ny = imagen.Height - 1
Dim matrizInic(ny, nx) As Integer, matrizfinal(ny, nx) As Double
bitmap_to_matriz(matrizInic, imagen)
nFiltro = tamano - 1
Dim vec(tamano * tamano - 1), cont As Integer
cont = 0
For i = 0 To ny
For j = 0 To nx
cont = 0
For i1 = i - (nFiltro / 2) To i + (nFiltro / 2)
For j1 = j - (nFiltro / 2) To j + (nFiltro / 2)
i3 = i1 : j3 = j1
If i3 < 0 Then i3 = i1 * (-1)
If j3 < 0 Then j3 = j1 * (-1)
If i3 > ny Then i3 = ny - (i1 - ny)
If j3 > nx Then j3 = nx - (j1 - nx)
vPixel = matrizInic(i3, j3)
vec(cont) = vPixel
cont = cont + 1
Next
Next
ordenar(vec, mediana)
matrizfinal(i, j) = mediana
Next
Next
'MessageBox.Show(mediana)
normalizar255(matrizfinal, matrizInic)
matriz_to_bitmap(matrizInic, imagen)
End Sub

Function Umbral(ByRef mibitmap As Bitmap)
Dim i, j, valor, valumbral As Integer
Dim micolor As Color
Dim arreglo(256) As Long
For i = 0 To mibitmap.Height - 1
For j = 0 To mibitmap.Width - 1
micolor = mibitmap.GetPixel(j, i)
valor = micolor.R
arreglo(valor) += 1
Next
Next
valumbral = 0
For i = 0 To 255
If arreglo(i) >= valumbral Then
valumbral = arreglo(i)
Else
valumbral = valumbral
End If
Next
Return valumbral
End Function

Sub binarizar(ByRef imagen1 As Bitmap)
Dim i, j, nc, nf, arreglo(256) As Integer
Dim IO(imagen1.Height - 1, imagen1.Width - 1) As Integer
Dim IB(imagen1.Height - 1, imagen1.Width - 1) As Integer

nc = imagen1.Width - 1 : nf = imagen1.Height - 1
' MessageBox.Show(cont)
bitmap_to_matriz(IO, imagen1)
For i = 1 To nf
For j = 1 To nc
If IO(i, j) >= 50 Then
IB(i, j) = 255
Else
IB(i, j) = 0
End If
Next j
Next i
matriz_to_bitmap(IB, imagen1)
End Sub
Sub etiquetado(ByRef imagen1 As Bitmap)
Dim i, j, etiq, nc, nf As Integer
Dim IO(imagen1.Height - 1, imagen1.Width - 1) As Integer

etiq = 50 'And IO(j + 1, i - 1) = 0 & _And IO(j + 1, i) = 0
nc = imagen1.Width - 1 : nf = imagen1.Height - 1
bitmap_to_matriz(IO, imagen1)
For i = 0 To nf - 1
For j = 0 To nc - 1
If IO(i, j) <> 0 Then
If IO(i, j - 1) = 0 And IO(i - 1, j) = 0 Then
etiq = etiq + 1
IO(i, j) = etiq
'MessageBox.Show(etiq)
Else
If IO(i + 1, j) <> 0 Then
IO(i + 1, j) = IO(i, j)
End If
End If
End If
Next
Next
End Sub

Sub etiquetado_4p(ByRef imagen As Bitmap)

Dim i, j, i1, j1, nf, nc, iequiv, etiq, pizq, psup As Integer
Dim matriz(imagen.Height - 1, imagen.Width - 1) As Integer
Dim matriz1(imagen.Height - 1, imagen.Width - 1) As Integer
Dim existe As Boolean
bitmap_to_matriz(matriz, imagen)
nf = UBound(matriz, 1)
nc = UBound(matriz, 2)
Dim tequiv(nf, 2)
etiq = 1
iequiv = 0
For i = 0 To nf
For j = 0 To nc
If matriz(i, j) <> 0 Then
If i - 1 < 0 Then
psup = 0
Else
psup = matriz(i - 1, j)
End If
If j - 1 < 0 Then
pizq = 0
Else
pizq = matriz(i, j - 1)
End If
If pizq = 0 And psup = 0 Then
etiq = etiq + 1
matriz(i, j) = etiq
End If
If pizq <> 0 And psup <> 0 Then
matriz(i, j) = pizq
If pizq <> psup Then
'agrega a tabla de equivalencia
existe = False
If iequiv > 0 Then
'verifica que psup y pizq no esten en tabla
For i1 = 0 To iequiv - 1
If tequiv(i1, 0) = psup And tequiv(i1, 1) = pizq Then
existe = True
End If
Next
End If
If existe = False Then
tequiv(iequiv, 0) = psup
tequiv(iequiv, 1) = pizq
tequiv(iequiv, 2) = 0
iequiv = iequiv + 1
End If
End If
End If
If pizq <> 0 And psup = 0 Or _
pizq = 0 And psup <> 0 Then
matriz(i, j) = pizq + psup
End If
End If
Next
Next
Debug.Write("numero de etiquetas=" & etiq & vbCrLf)
Debug.Write("antes de proceso de equiv" & vbCrLf)
'For i = 0 To iequiv - 1
' Debug.Write(i & " " & tequiv(i, 0) & " " & tequiv(i, 1) & " " & tequiv(i, 2) & vbCrLf)
'Next

'proceso de tabla de equivalencias
Dim vr, vb As Integer
' transformacion de tequiv
' se asegura que tequiv(i,0) For i = 0 To iequiv - 1
If tequiv(i, 0) > tequiv(i, 1) Then
vr = tequiv(i, 0) : tequiv(i, 0) = tequiv(i, 1) : tequiv(i, 1) = vr
End If
Next

For i = 0 To iequiv - 1
If tequiv(i, 2) = 0 Then
tequiv(i, 2) = tequiv(i, 0)
End If
vr = tequiv(i, 0)
vb = tequiv(i, 1)
For j = 0 To iequiv - 1
If tequiv(j, 2) = 0 Then
If tequiv(j, 0) = vr Or tequiv(j, 1) = vr _
Or tequiv(j, 0) = vb Or tequiv(j, 1) = vb Then
tequiv(j, 2) = tequiv(i, 2)
vr = tequiv(j, 0)
vb = tequiv(j, 1)
j = 0
End If
End If
Next j

Debug.Write("- " & i)
Next

Debug.Write("luego proceso de equivalencias" & vbCrLf)
For i = 0 To iequiv - 1
Debug.Write(i & " " & tequiv(i, 0) & " " & tequiv(i, 1) & " " & tequiv(i, 2) & vbCrLf)
Next
'genera tabla de reemplazos
Dim tr(etiq)
For j = 0 To etiq
tr(j) = j
Next
For j = 0 To iequiv - 1
For j1 = 0 To 1
tr(tequiv(j, j1)) = tequiv(j, 2)
Next
Next
'REEMPLAZO
For i = 0 To nf
For j = 0 To nc
matriz(i, j) = tr(matriz(i, j))
Next j
Next i
Debug.Write("matriz final" & vbCrLf)
For i = 0 To nf
For j = 0 To nc
If matriz(i, j) <> 0 Then
Debug.Write(i & " ; " & j & " valor " & matriz(i, j) & vbCrLf)
End If
Next
Next

MessageBox.Show("****Fin Reconocimiento****")
normalizar255_E(matriz, matriz1)
matriz_to_bitmap(matriz1, imagen)

End Sub

Function etiqueta(ByRef matriz(,) As Integer, ByRef nf As Integer, ByRef nc As Integer) As Integer

Dim i, j, cont, k As Integer
Dim arr(256), temp(256) As Integer
cont = 0
For i = 0 To 255
arr(i) = i
Next
For i = 0 To nf
For j = 0 To nc
For k = 0 To 255
If matriz(i, j) <> 0 Then
If matriz(i, j) = arr(k) Then

End If
End If
Next
Next
Next


End Function

Sub calculo_valores(ByRef val() As Long, ByRef uno As Integer, ByRef cinco As Integer, ByRef diez As Integer, ByRef vcinc As Integer, ByRef cinq As Integer, ByRef und As Integer)

Dim i As Integer
uno = 0 : diez = 0 : cinco = 0 : vcinc = 0 : cinq = 0 : und = 0

For i = 0 To 255
If val(i) >= 7054 And val(i) <= 8454 Then
diez += 1
End If
If val(i) >= 8455 And val(i) <= 9900 Then
uno += 1
End If
If val(i) >= 9968 And val(i) <= 12182 Then
cinco += 1
End If
If val(i) >= 12183 And val(i) <= 15000 Then
vcinc += 1
End If
If val(i) >= 15200 And val(i) <= 19000 Then
und += 1
End If
If val(i) >= 19759 And val(i) <= 25000 Then
cinq += 1
End If
Next

End Sub

End Module

*****************************************************************
*****************************************************************

Imports System.Drawing
Imports System.drawing.Drawing2D
Imports System.Drawing.Graphics
Imports System.Drawing.Image
Imports System.Windows
Imports System.Math

Public Class Form1

Private Sub btncargar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncargar.Click
Dim imagen As Bitmap
imagen = New Bitmap(Me.PictureBox1.Width, Me.PictureBox1.Height) 'a esa imagen le asigna el ancho y el alto del picturebox
With Me.ofd1
'.InitialDirectory = "C:\"
.Filter = "Formatos (*.bmp;*.jpg;*.jpeg;*.gif;*.tif)|" & _
"*.bmp;*.jpg;*.jpeg;*.gif;*.tif|Bitmaps (*.bmp)|*.bmp|" & _
"GIFs (*.gif)|*.gif|JPEGs (*.jpg)|*.jpg;*.jpeg|TIFs (*.tif)|*.tif"
.FilterIndex = 1
End With
If ofd1.ShowDialog() = Windows.Forms.DialogResult.OK Then
imagen = FromFile(ofd1.FileName) 'este le transfiere la imagen desde el archivo fisico a memoria a un objeto tipo bitmap
End If
Me.PictureBox1.Width = imagen.Width
Me.PictureBox1.Height = imagen.Height
Me.PictureBox1.Image = imagen
lb_ah1.Text = "W " & imagen.Width & " - " & "H " & imagen.Height
End Sub


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim miimagen1 As Bitmap

Dim miimagen2 As Bitmap
'Dim uncen, cinc, diezc, vintc, cincc As Integer
Dim uno, diez, cinco, vcinc, cinq, und As Integer


Dim valhisto(255) As Long
miimagen1 = New Bitmap(Me.PictureBox1.Image)
miimagen2 = New Bitmap(miimagen1.Width, miimagen1.Height)
color_gris(miimagen1, miimagen2)
Dim tamano As Integer

tamano = 9
filtro_mediana(miimagen2, tamano)
binarizar(miimagen2)
'Dim matriz(miimagen2.Height - 1, miimagen2.Width - 1) As Integer
etiquetado_4p(miimagen2)
histograma1(miimagen2, valhisto)

calculo_valores(valhisto, uno, cinco, diez, vcinc, cinq, und)
txt_uc.Text = uno
txt_dc.Text = diez
txt_cc.Text = cinco
txt_vc.Text = vcinc
txt_qc.Text = cinq
txt_ud.Text = und


End Sub

Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class

viernes, 22 de mayo de 2009

Hopfield

package hoppfield;

/**
* @author GILBERT ADRIAN
*/

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Hpfield_java extends JFrame implements ActionListener {
/**
* El numero de neuronas en la red neuronal
*/
public static final int NETWORK_SIZE = 8;

/**
* Los pesos de la matriz para las ocho
* neuronas conectadas.
*/
JTextField matrix[][] =
new JTextField[NETWORK_SIZE][NETWORK_SIZE];

/**
* El patron de entrada, usado en cada
* entrenamiento o corrida de la red neuronal
* cuando la red neuronal ha sido corrida
* ha sido ingresado el patron
*/
JComboBox input[] = new JComboBox[NETWORK_SIZE];

/**
* La salida de cada una de las 8 neuronas.
*/
JTextField output[] = new JTextField[NETWORK_SIZE];
/**
* El boton clear utilizado para limpiar los pesos
* de la matriz.
*/
JButton btnClear = new JButton("Clear");
/**
* El boton entrenar, Usado para ejecutar el boton train.
*/
JButton btnTrain = new JButton("Train");
/**
* Para correr es boton untilizado en la red neuronal
*/
JButton btnRun = new JButton("Run");
/**
* Crea todos los conponentes y su posicion
*/
public Hpfield_java()
{
setTitle("Hopfield Neural Network");

// Crea conecciones en el panel
JPanel connections = new JPanel();
connections.setLayout(
new GridLayout(NETWORK_SIZE,NETWORK_SIZE) );
for ( int row=0; row < NETWORK_SIZE;row++ ) {
for ( int col=0; col < NETWORK_SIZE;col++ ) {
matrix[row][col] = new JTextField(3);
matrix[row][col].setText("0") ;
connections.add(matrix[row][col]);
}
}

Container content = getContentPane();

GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
content.setLayout(gridbag);

c.fill = GridBagConstraints.NONE;
c.weightx = 1.0;

// Peso del label de la matriz
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.NORTHWEST;
content.add(
new JLabel(
"Weight Matrix for the Hopfield Neural Network:"),c);

// Tamanio de la matriz
c.anchor = GridBagConstraints.CENTER;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(connections,c);
c.gridwidth = 1;

// Entrada del label del patron
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel(
"Click \"Train\" to train the following pattern:"),c);

// Input pattern

String options[] = { "0","1"};

JPanel inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
for ( int i=0 ; i < NETWORK_SIZE;i++ ) {
input[i] = new JComboBox(options);
inputPanel.add(input[i]);

}

c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(inputPanel,c);

// Salida del label del patron
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel("Click \"Run\" to see output pattern:"),c);

// Salida del patron

JPanel outputPanel = new JPanel();
outputPanel.setLayout(new FlowLayout());
for ( int i=0; i < NETWORK_SIZE;i++ ) {
output[i] = new JTextField(3);
output[i].setEditable(false);
outputPanel.add(output[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(outputPanel,c);

// Botones

JPanel buttonPanel = new JPanel();
btnClear = new JButton("Clear");
btnTrain = new JButton("Train");
btnRun = new JButton("Run");
btnClear.addActionListener(this);
btnTrain.addActionListener(this);
btnRun.addActionListener(this);
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(btnClear);
buttonPanel.add(btnTrain);
buttonPanel.add(btnRun);
content.add(buttonPanel,c);

// Ajustar tamanio y posicion
pack();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension d = toolkit.getScreenSize();
setLocation(
(int)(d.width-this.getSize().getWidth())/2,
(int)(d.height-this.getSize().getHeight())/2 );
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
}
/**
* Usado para disparar los eventos de los botones
* y manejar los metodos
*/
public void actionPerformed(ActionEvent e)
{
if ( e.getSource()==btnRun )
run();
else if ( e.getSource()==btnClear )
clear();
else if ( e.getSource()==btnTrain )
train();
}

/**
* Llamado cuando la red neuronal ha sido corrida en contra
* la entrada
*/
protected void run()
{
boolean pattern[] = new boolean[NETWORK_SIZE];
int wt[][] = new int[NETWORK_SIZE][NETWORK_SIZE];

for ( int row=0;row < NETWORK_SIZE;row++ )
for ( int col=0; col < NETWORK_SIZE;col++ )
wt[row][col]=Integer.parseInt(matrix[row][col].getText());
for ( int row=0;row < NETWORK_SIZE;row++ ) {
int i = input[row].getSelectedIndex();
if ( i==0 )
pattern[row] = false;
else
pattern[row] = true;
}

Layer net = new Layer(wt);
net.activation(pattern);

for ( int row=0; row < NETWORK_SIZE;row++ ) {
if ( net.output[row] )
output[row].setText("1");
else
output[row].setText("0");
if ( net.output[row]==pattern[row] )
output[row].setBackground(java.awt.Color.green);
else
output[row].setBackground(java.awt.Color.red);
}
}
/**
* LLamado para eliminar los pesos de la matriz
*/
protected void clear()
{
for ( int row=0; row < NETWORK_SIZE;row++ )
for ( int col=0; col < NETWORK_SIZE;col++ )
matrix[row][col].setText("0");
}

/**
* Llamada para entrenar los pesos de la matriz base
* con el patron ingresado
*/
protected void train()
{
int work[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
int bi[] = new int[NETWORK_SIZE];

for ( int x=0 ; x < NETWORK_SIZE;x++ ) {
if ( input[x].getSelectedIndex()==0 )
bi[x] = -1;
else
bi[x] = 1;
}

for ( int row=0; row < NETWORK_SIZE;row++ )
for ( int col=0; col < NETWORK_SIZE;col++ ) {
work[row][col] = bi[row]*bi[col];
}

for ( int x=0; x < NETWORK_SIZE;x++ )
work[x][x] =0;

for ( int row=0; row < NETWORK_SIZE;row++ )
for ( int col=0; col < NETWORK_SIZE;col++ ) {
int i = Integer.parseInt(matrix[row][col].getText());
matrix[row][col].setText( "" + (work[row][col]));
}
}
}

***********************
*******************************************
package hoppfield;
/**
* @author GILBERT ADRIAN
*/
public class Neuron {
/**
* Los pesos entre esta neurona y otra esta en el metodo Layer
*/
public int weightv[];
/**
* Activacion de resultados de esta neurona
*/
public int activation;
/**
* El constructor. Los pesos entre esta neurona y las otras
* incluida ella misma es pasada en un array. Usualmente los pesos
* entre esta neurona y ella misma es cero.
*/
public Neuron(int in[])
{
weightv = in;
}
/**
* Metodo llamado para determinar si la nerurona podria ser activada
*/
public int act(boolean x[] )
{
int i;
int a=0;

for ( i=0; i < x.length;i++ )
if ( x[i] )
a+=weightv[i];
return a;
}
}
******************************
********************************
package hoppfield;
/**
* @author GILBERT ADRIAN
*/
public class Layer {
/**
* El Array de neuronas
*/
protected Neuron neuron[] = new Neuron[8];

/**
* Salida de las neuronas
*/
protected boolean output[] = new boolean[8];

/**
* El numero de neuronas en esta capa. Puesto a q esta es una capa
* de neurona simple, este es tambien el numero de neuronas en la red.
*/
protected int neurons;

/**
* Una constante se multiplica a la funcion threshold
*/
public static final double lambda = 1.0;

/**
* EL constructor. El peso de la matriz por las
* neuronas debe ser pasado aqui.
* Puesto a que es una capa simple de red el peso de
* del array debe ser siempre un cuadrado perfecto estos
* pesos son utilizados para inicializar la neurona.
*/
Layer(int weights[][])
{
neurons = weights[0].length;

neuron = new Neuron[neurons];
output = new boolean[neurons];

for ( int i=0;i neuron[i]=new Neuron(weights[i]);
}

/**
* El metodo threshold es usado para determinar si la red de neuronas
* sera disparada al dar un patron. Este threshold utiliza
* una tangente Hyperbolica (tanh).
*/
public boolean threshold(int k)
{
double kk = k * lambda;
double a = Math.exp( kk );
double b = Math.exp( -kk );
double tanh = (a-b)/(a+b);
return(tanh>=0);
}

/**
* Este metodo es corrido pacorrer la red neuronal
*/
void activation(boolean pattern[])
{
int i,j;
for ( i=0;i<8;i++ ) {
neuron[i].activation = neuron[i].act(pattern);
output[i] = threshold(neuron[i].activation);
}
}
}
*************************
*********************************************
package hoppfield;

import javax.swing.JFrame;

/**
* @author GILBERT ADRIAN
*/
public class Main {
public static void main(String[] args) {
JFrame f = new Hpfield_java();
f.show();
}
}

hopfield



import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Example: The Hopfield Neural Network
*
* This is an example that implements a Hopfield neural
* network. This example network contains four fully
* connected neurons. This file, Hopfield, implements a
* Swing interface into the other two neural network
* classes: Layer and Neuron.
*
* @author Jeff Heaton
* @version 1.0
*/
public class Hopfield extends JFrame implements ActionListener {
/**
* The number of neurons in this neural network.
*/
public static final int NETWORK_SIZE = 4;
/**
* The weight matrix for the four fully connected
* neurons.
*/
JTextField matrix[][] =
new JTextField[NETWORK_SIZE][NETWORK_SIZE];
/**
* The input pattern, used to either train
* or run the neural network. When the network
* is being trained, this is the training
* data. When the neural network is to be ran
* this is the input pattern.
*/
JComboBox input[] = new JComboBox[NETWORK_SIZE];
/**
* The output from each of the four neurons.
*/
JTextField output[] = new JTextField[NETWORK_SIZE];
/**
* The clear button. Used to clear the weight
* matrix.
*/
JButton btnClear = new JButton("Clear");
/**
* The train button. Used to train the
* neural network.
*/
JButton btnTrain = new JButton("Train");
/**
* The run button. Used to run the neural
* network.
*/
JButton btnRun = new JButton("Run");
/**
* Constructor, create all of the components and position
* the JFrame to the center of the screen.
*/
public Hopfield()
{
setTitle("Hopfield Neural Network");
// create connections panel
JPanel connections = new JPanel();
connections.setLayout(
new GridLayout(NETWORK_SIZE,NETWORK_SIZE) );
for ( int row=0;row < NETWORK_SIZE;row++ ) {
for ( int col=0;col < NETWORK_SIZE;col++ ) {
matrix[row][col] = new JTextField(3);
matrix[row][col].setText("0");
connections.add(matrix[row][col]);
}
}
Container content = getContentPane();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
content.setLayout(gridbag);
c.fill = GridBagConstraints.NONE;
c.weightx = 1.0;
// Weight matrix label
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.NORTHWEST;
content.add(
new JLabel(
"Weight Matrix for the Hopfield Neural Network:"),c);
// Weight matrix
c.anchor = GridBagConstraints.CENTER;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(connections,c);
c.gridwidth = 1;
// Input pattern label
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel(
"Click \"Train\" to train the following pattern:"),c);
// Input pattern
String options[] = { "0","1"};
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
for ( int i=0;i < NETWORK_SIZE;i++ ) {
input[i] = new JComboBox(options);
inputPanel.add(input[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(inputPanel,c);
// Output pattern label
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel("Click \"Run\" to see output pattern:"),c);
// Output pattern
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new FlowLayout());
for ( int i=0; i < NETWORK_SIZE;i++ ) {
output[i] = new JTextField(3);
output[i].setEditable(false);
outputPanel.add(output[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(outputPanel,c);
// Buttons
JPanel buttonPanel = new JPanel();
btnClear = new JButton("Clear");
btnTrain = new JButton("Train");
btnRun = new JButton("Run");
btnClear.addActionListener(this);
btnTrain.addActionListener(this);
btnRun.addActionListener(this);
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(btnClear);
buttonPanel.add(btnTrain);
buttonPanel.add(btnRun);
content.add(buttonPanel,c);
// adjust size and position
pack();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension d = toolkit.getScreenSize();
setLocation(
(int)(d.width-this.getSize().getWidth())/2,
(int)(d.height-this.getSize().getHeight())/2 );
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
}
/**
* Used to dispatch events from the buttons
* to the handler methods.
*
* @param e The event
*/
public void actionPerformed(ActionEvent e)
{
if ( e.getSource()==btnRun )
run();
else if ( e.getSource()==btnClear )
clear();
else if ( e.getSource()==btnTrain )
train();
}
/**
* Called when the neural network is to be ran against
* the input.
*/
protected void run()
{
boolean pattern[] = new boolean[NETWORK_SIZE];
int wt[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
for ( int row=0; row < NETWORK_SIZE;row++ )
for ( int col=0; col < NETWORK_SIZE;col++ )
wt[row][col]=Integer.parseInt(matrix[row][col].getText());
for ( int row=0; row < NETWORK_SIZE;row++ ) {
int i = input[row].getSelectedIndex();
if ( i==0 )
pattern[row] = false;
else
pattern[row] = true;
}
Layer net = new Layer(wt);
net.activation(pattern);
for ( int row=0; row < NETWORK_SIZE;row++ ) {
if ( net.output[row] )
output[row].setText("1");
else
output[row].setText("0");
if ( net.output[row]==pattern[row] )
output[row].setBackground(java.awt.Color.green);
else
output[row].setBackground(java.awt.Color.red);
}
}
/**
* Called to clear the weight matrix.
*/
protected void clear()
{
for ( int row=0; row < NETWORK_SIZE;row++ )
for ( int col=0; col < NETWORK_SIZE;col++ )
matrix[row][col].setText("0");
}
/**
* Called to train the weight matrix based on the
* current input pattern.
*/
protected void train()
{
int work[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
int bi[] = new int[NETWORK_SIZE];
for ( int x=0; x < NETWORK_SIZE;x++ ) {
if ( input[x].getSelectedIndex()==0 )
bi[x] = -1;
else
bi[x] = 1;
}
for ( int row=0; row < NETWORK_SIZE;row++ )
for ( int col=0; col < NETWORK_SIZE;col++ ) {
work[row][col] = bi[row]*bi[col];
}
for ( int x=0; x < NETWORK_SIZE;x++ )
work[x][x] =-1;
for ( int row=0; row < NETWORK_SIZE;row++ )
for ( int col=0; col < NETWORK_SIZE;col++ ) {
int i = Integer.parseInt(matrix[row][col].getText());
matrix[row][col].setText( "" + (i+work[row][col]));
}
}
/**
* Main program entry point, display the
* frame.
*
* @param args Command line arguments are not used
*/
static public void main(String args[])
{
JFrame f = new Hopfield();
f.show();
}
} < network_size;x++" col="0; col < NETWORK_SIZE;col++" i="0;
i < NETWORK_SIZE;i++" f="new" content="getContentPane();">

jueves, 21 de mayo de 2009

HOPFIELD





/**
* Hopfield.java
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/**
* Example: The Hopfield Neural Network
*
* This is an example that implements a Hopfield neural
* network. This example network contains four fully
* connected neurons. This file, Hopfield, implements a
* Swing interface into the other two neural network
* classes: Layer and Neuron.
*
* @author Jeff Heaton
* @version 1.0
*/
public class Hopfield extends JFrame implements ActionListener {

/**
* The number of neurons in this neural network.
*/
public static final int NETWORK_SIZE = 8;

/**
* The weight matrix for the four fully connected
* neurons.
*/
JTextField matrix[][] =
new JTextField[NETWORK_SIZE][NETWORK_SIZE];


/**
* The input pattern, used to either train
* or run the neural network. When the network
* is being trained, this is the training
* data. When the neural network is to be ran
* this is the input pattern.
*/
JComboBox input[] = new JComboBox[NETWORK_SIZE];

/**
* The output from each of the four neurons.
*/
JTextField output[] = new JTextField[NETWORK_SIZE];

/**
* The clear button. Used to clear the weight
* matrix.
*/
JButton btnClear = new JButton("Clear");

/**
* The train button. Used to train the
* neural network.
*/
JButton btnTrain = new JButton("Train");

/**
* The run button. Used to run the neural
* network.
*/
JButton btnRun = new JButton("Run");

/**
* Constructor, create all of the components and position
* the JFrame to the center of the screen.
*/
public Hopfield()
{
setTitle("Hopfield Neural Network");

// create connections panel
JPanel connections = new JPanel();
connections.setLayout(
new GridLayout(NETWORK_SIZE,NETWORK_SIZE) );
for ( int row=0;row for ( int col=0;col matrix[row][col] = new JTextField(3);
matrix[row][col].setText("0");
connections.add(matrix[row][col]);
}
}

Container content = getContentPane();

GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
content.setLayout(gridbag);

c.fill = GridBagConstraints.NONE;
c.weightx = 1.0;

// Weight matrix label
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.NORTHWEST;
content.add(
new JLabel(
"Weight Matrix for the Hopfield Neural Network:"),c);

// Weight matrix
c.anchor = GridBagConstraints.CENTER;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(connections,c);
c.gridwidth = 1;

// Input pattern label
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel(
"Click \"Train\" to train the following pattern:"),c);

// Input pattern

String options[] = { "0","1"};

JPanel inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
for ( int i=0;i input[i] = new JComboBox(options);
inputPanel.add(input[i]);

}

c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(inputPanel,c);

// Output pattern label
c.anchor = GridBagConstraints.NORTHWEST;
c.gridwidth = GridBagConstraints.REMAINDER; //end row
content.add(
new JLabel("Click \"Run\" to see output pattern:"),c);

// Output pattern

JPanel outputPanel = new JPanel();
outputPanel.setLayout(new FlowLayout());
for ( int i=0;i output[i] = new JTextField(3);
output[i].setEditable(false);
outputPanel.add(output[i]);
}
c.gridwidth = GridBagConstraints.REMAINDER; //end row
c.anchor = GridBagConstraints.CENTER;
content.add(outputPanel,c);

// Buttons

JPanel buttonPanel = new JPanel();
btnClear = new JButton("Clear");
btnTrain = new JButton("Train");
btnRun = new JButton("Run");
btnClear.addActionListener(this);
btnTrain.addActionListener(this);
btnRun.addActionListener(this);
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(btnClear);
buttonPanel.add(btnTrain);
buttonPanel.add(btnRun);
content.add(buttonPanel,c);

// adjust size and position
pack();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension d = toolkit.getScreenSize();
setLocation(
(int)(d.width-this.getSize().getWidth())/2,
(int)(d.height-this.getSize().getHeight())/2 );
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);


}

/**
* Used to dispatch events from the buttons
* to the handler methods.
*
* @param e The event
*/
public void actionPerformed(ActionEvent e)
{
if ( e.getSource()==btnRun )
run();
else if ( e.getSource()==btnClear )
clear();
else if ( e.getSource()==btnTrain )
train();
}

/**
* Called when the neural network is to be ran against
* the input.
*/
protected void run()
{
boolean pattern[] = new boolean[NETWORK_SIZE];
int wt[][] = new int[NETWORK_SIZE][NETWORK_SIZE];

for ( int row=0;row for ( int col=0;col wt[row][col]=Integer.parseInt(matrix[row][col].getText());
for ( int row=0;row int i = input[row].getSelectedIndex();
if ( i==0 )
pattern[row] = false;
else
pattern[row] = true;
}

Layer net = new Layer(wt);
net.activation(pattern);

for ( int row=0;row if ( net.output[row] )
output[row].setText("1");
else
output[row].setText("0");
if ( net.output[row]==pattern[row] )
output[row].setBackground(java.awt.Color.green);
else
output[row].setBackground(java.awt.Color.red);
}

}

/**
* Called to clear the weight matrix.
*/
protected void clear()
{
for ( int row=0;row for ( int col=0;col matrix[row][col].setText("0");
}

/**
* Called to train the weight matrix based on the
* current input pattern.
*/
protected void train()
{

int work[][] = new int[NETWORK_SIZE][NETWORK_SIZE];
int bi[] = new int[NETWORK_SIZE];

for ( int row=0;row for ( int col=0;col work[row][col] = 0;
}

for ( int x=0;x if ( input[x].getSelectedIndex()==0 )
bi[x] = -1;
else
bi[x] = 1;
}

for ( int row=0;row for ( int col=0;col work[row][col] = bi[row]*bi[col];
}

for ( int x=0;x work[x][x] =0;

for ( int row=0;row for ( int col=0;col int i = Integer.parseInt(matrix[row][col].getText());
matrix[row][col].setText( "" + (work[row][col]));
}
}

/**
* Main program entry point, display the
* frame.
*
* @param args Command line arguments are not used
*/
static public void main(String args[])
{
JFrame f = new Hopfield();
f.show();
}
}
 
/**
* Layer.java
*/
public class Layer {

/**
* An array of neurons.
*/
protected Neuron neuron[] = new Neuron[8];

/**
* The output of the neurons.
*/
protected boolean output[] = new boolean[8];

/**
* The number of neurons in this layer. And because this is a
* single layer neural network, this is also the number of
* neurons in the network.
*/
protected int neurons;

/**
* A constant to multiply against the threshold function.
* This is not used, and is set to 1.
*/
public static final double lambda = 1.0;

/**
* The constructor. The weight matrix for the
* neurons must be passed in. Because this is
* a single layer network the weight array should
* always be perfectly square(i.e. 4x4). These
* weights are used to initialize the neurons.
*
* @param weights A 2d array that contains the weights
* between each
* neuron and the other neurons.
*/
Layer(int weights[][])
{
neurons = weights[0].length;

neuron = new Neuron[neurons];
output = new boolean[neurons];

for ( int i=0;i neuron[i]=new Neuron(weights[i]);
}

/**
* The threshold method is used to determine if the neural
* network will fire for a given pattern. This threshold
* uses the hyperbolic tangent (tanh).
*
* @param k The product of the neuron weights and the input
* pattern.
* @return Whether to fire or not to fire.
*/
public boolean threshold(int k)
{
double kk = k * lambda;
double a = Math.exp( kk );
double b = Math.exp( -kk );
double tanh = (a-b)/(a+b);
return(tanh>=0);
}

/**
* This method is called to actually run the neural network.
*
* @param pattern The input pattern to present to the
* neural network.
*/
void activation(boolean pattern[])
{
int i,j;
for ( i=0;i<8;i++ ) {
neuron[i].activation = neuron[i].act(pattern);
output[i] = threshold(neuron[i].activation);
}
}
}
 
/**
* Neuron.java
*/
public class Neuron {

/**
* The weights between this neuron and the other neurons on
* the layer.
*/
public int weightv[];

/**
* Activation results for this neuron.
*/
public int activation;

/**
* The constructor. The weights between this neuron and
* every other neuron(including itself) is passed in as
* an array. Usually the weight between this neuron and
* itself is zero.
*
* @param in The weight vector.
*/
public Neuron(int in[])
{
weightv = in;
}

/**
* This method is called to determine if the neuron would
* activate, or fire.
*
* @param x Neuron input
* @return If the neuron would activate, or fire
*/
public int act(boolean x[] )
{
int i;
int a=0;

for ( i=0;i if ( x[i] )
a+=weightv[i];
return a;
}

}




todo el codigo fue tomado de la pagina
mejorado para manejar 8 neuronas y controlar al momento de entrenar la neurana
http://www.heatonresearch.com/articles/series/1/

lunes, 4 de mayo de 2009

Perceptron

package perceptron;
public class perceptron
{
float factorAprendizaje;
float output;
float[] pesos;
float error;
public perceptron(float[] pesos, float factorAprendizaje)
{
this.pesos = pesos;
this.factorAprendizaje = factorAprendizaje;
this.error = 1f;this.output = 0f;
}
public float output(float[] entradas)
{
output = 0f; for(int i = 0; i < output =" funcionPerceptron(output);"> 0) return 1;
return o;
}

public float error(float salidaDeseada)
{
error = salidaDeseada - output;
return error;
}

public void calculaPesos(float[] entradas)
{
if(error != 0)
{
for(int i = 0; i < entradas.length; i++)
{
this.pesos[i] = (factorAprendizaje * error) * entradas[i] + pesos[i];
}
}
}

public float[] execute(float[][] entradas)
{
float[] result = new float[entradas.length];
for(int i = 0; i < entradas.length; i++)
{
result[i] = output(entradas[i]);
}
return result;
}
}

Redes Neuronales

Redes neuronales
La Neurona
A finales del siglo 19 se logró una mayor claridad sobre el trabajo del cerebro debido a los trabajos de Ramón y Cajal en España y Sherrington en Inglaterra. El primero trabajó en la anatomía de las neuronas y el segundo en los puntos de conexión de las mismas o sinápsis.
El tejido nervioso es el más diferenciado del organismo y está constituido por células nerviosas, fibras nerviosas y la neuroglia, que está formada por varias clases de células. La célula nerviosa se denomina neurona, que es la unidad funcional del sistema nervioso. Hay neuronas bipolares, con dos prolongaciones de fibras y multipolares, con numerosas prolongaciones. Pueden ser neuronas sensoriales, motoras y de asociación.
Se estima que en cada milímetro del cerebro hay cerca de 50.000 neuronas. La estructura de una neurona se muestra en la figura 1.
El tamaño y la forma de las neuronas es variable, pero con las mismas subdivisiones que muestra la figura. El cuerpo de la neurona o Soma contiene el núcleo. Se encarga de todas las actividades metabólicas de la neurona y recibe la información de otras neuronas vecinas a través de las conexiones sinápticas.
Las dendritas son las conexiones de entrada de la neurona. Por su parte el axón es la "salida" de la neurona y se utiliza para enviar impulsos o señales a otras células nerviosas. Cuando el axón esta cerca de sus células destino se divide en muchas ramificaciones que forman sinápsis con el soma o axones de otras células. Esta unión puede ser "inhibidora" o "excitadora" según el transmisor que las libere. Cada neurona recibe de 10.000 a 100.000 sinápsis y el axón realiza una cantidad de conexiones similar.
La transmisión de una señal de una célula a otra por medio de la sinápsis es un proceso químico. En él se liberan substancias transmisoras en el lado del emisor de la unión. El efecto es elevar o disminuir el potencial eléctrico dentro del cuerpo de la célula receptora. Si su potencial alcanza el umbral se envía un pulso o potencial de acción por el axón. Se dice, entonces, que la célula se disparó. Este pulso alcanza otras neuronas a través de la distribuciones de los axones.
La Red Neuronal
El sistema de neuronas biológico esta compuesto por neuronas de entrada (censores) conectados a una compleja red de neuronas "calculadoras" (neuronas ocultas), las cuales, a su vez, están conectadas a las neuronas de salidas que controlan, por ejemplo, los músculos. La figura 6 muestra un esquema conceptual. Los censores pueden ser señales de los oídos, ojos, etc. las respuestas de las neuronas de salida activan los músculos correspondientes. En el cerebro hay una gigantesca red de neuronas "calculadoras" u ocultas que realizan la computación necesaria. De esta manera similar, una red neuronal artificial debe ser compuesta por censores del tipo mecánico o eléctrico.
Historia De Redes Neuronales Artificiales
En Breve
Los intentos por imitar el funcionamiento del cerebro han seguido la evolución del estado de la tecnología. Por ejemplo, al finalizar el siglo 19 se le comparó con la operación de la bomba hidráulica; durante la década de 1920 a 1930 se intento utilizar la teoría de la conmutación telefónica como punto de partida de un sistema de conocimiento similar al del cerebro. Entre 1940 y 1950 los científicos comenzaron a pensar seriamente en las redes neuronales utilizando como concepto la noción de que las neuronas del cerebro funcionan como interruptores digitales (on - off) de manera también similar al recién desarrollado computador digital. Así nace la idea de "revolución cibernética" que maneja la analogía entre el cerebro y el computador digital.
1943 Teoría de las Redes Neuronales Artificiales
Walter Pitts junto a Bertran Russell y Warren McCulloch intentaron explicar el funcionamiento del cerebro humano, por medio de una red de células conectadas entre sí, para experimentar ejecutando operaciones lógicas. Partiendo del menor suceso psíquico (estimado por ellos): el impulso todo/nada, generado por una célula nerviosa.
El bucle "sentidos - cerebro - músculos", mediante la retroalimentación producirían una reacción positiva si los músculos reducen la diferencia entre una condición percibida por los sentidos y un estado físico impuesto por el cerebro.
También definieron la memoria como un conjunto de ondas que reverberan en un circuito cerrado de neuronas.
1949 Conductividad de la sinápsis en las Redes Neuronales.
Seis años después de que McCulloch y Pitts mostraran sus Redes Neuronales, el fisiólogo Donald O. Hebb (de la McGill University) expuso que estas (las redes neuronales) podían aprender. Su propuesta tenia que ver con la conductividad de la sinápsis, es decir, con las conexiones entre neuronas. Hebb expuso que la repetida activación de una neurona por otra a través de una sinápsis determinada, aumenta su conductividad, y la hacia más propensa a ser activada sucesivamente, induciendo a la formación de un circuito de neuronas estrechamente conectadas entre sí.
1951 Primera Red Neuronal
El extraordinario estudiante de Harvard, Marvin Minsky conoció al científico Burrhus Frederic Skinner, con el que trabajó algún tiempo ayudándole en el diseño y creación de máquinas para sus experimentos. Minsky se inspiró en Skinner para gestar su primera idea "oficial" sobre inteligencia artificial, su Red Neuronal. Por aquel entonces entabló amistad con otro brillante estudiante, Dean Edmonds, el cual estaba interesado en el estudio de una nueva ciencia llamada Electrónica.
Durante el verano de 1951, Minsky y Edmonds montaron la primera máquina de redes neuronales, compuesta básicamente de 300 tubos de vacío y un piloto automático de un bombardero B-24. Llamaron a su creación "Sharc", se trataba nada menos que de una red de 40 neuronas artificiales que imitaban el cerebro de una rata. Cada neurona hacia el papel de una posición del laberinto y cuando se activaba daba a entender que la "rata" sabia en que punto del laberinto estaba. Las neuronas que estaban conectadas alrededor de la activada, hacían la función de alternativas que seguir por el cerebro, la activación de la siguiente neurona, es decir, la elección entre "derecha" o "izquierda" en este caso estaría dada por la fuerza de sus conexiones con la neurona activada. Por ejemplo, la "rata" completaba bien el recorrido eligiendo a partir de la quinta neurona la opción "izquierda" (que correspondería a la sexta), es entonces cuando las conexiones entre la quinta y sexta se hacen más fuertes (dicha conexión era realizada por el piloto automático), haciendo desde este momento más propensa esta decisión en un futuro. Pero las técnicas Skinnerianas (que eran las que se habían puesto en funcionamiento en esta red neuronal) no podrían llevar muy lejos a este nuevo engendro, la razón pasa porque esto, en sí, no es inteligencia, pues la red neuronal nunca llegaría a trazar un plan.
Después de su Red Neuronal, Minsky escribió su tesis doctoral acerca de esta, en ella describía "cerebros mucho mayores", exponiendo que si se realizaba este proyecto a gran escala, con miles o millones de neuronas más y con diferentes censores y tipos de retroalimentación… la máquina podría ser capaz de razonar, mas el sabia que la realización de esta Red Neuronal era imposible y decidió buscar otra forma de crear inteligencia…
Las Redes Neuronales Artificiales
Sistema Experto.
Un método más avanzado para representar el conocimiento, es el sistema experto. Típicamente está compuesto por varias clases de información almacenada: Las reglas If - Then le dicen al sistema como se debe reaccionar ante los estados del "mundo". Una regla del sistema experto puede ser if Y es un hombre, Then Y es mortal. Los hechos describen el estado del "mundo". Por ejemplo: Juan es mortal. Por último, una máquina de inferencia relaciona los hechos conocidos con las reglas If - Then y genera una conclusión. En el ejemplo: Juan es mortal. Esta nueva conclusión se añade a la colección de hechos que se almacena en los medios ópticos o magnéticos del computador digital. De esta forma, un sistema experto sintetiza nuevo conocimiento a partir de su "entendimiento" del mundo que le rodea. De esta forma, un sistema experto es un método de representación y procesamiento del conocimiento, mucho más rico y poderoso que un simple programa de computador. Sin embargo, con respecto a la manera en que opera el cerebro humano, las limitaciones son múltiples. Los problemas planteados en términos difusos o ambiguos , por ejemplo, son muy complejos de analizar o "conocer" con sistemas de procesamiento simbólico, como los sistemas expertos o programas de computador.
Interpretación De La Neurona Por Computadora
Una neurona se puede comparar con una caja negra compuesta por varias entradas y una salida. La relación de activación entre la salida y la entrada, o en términos circuitales o de teoría de control, la función de transferencia se encuentra en la ..figura 2.
La variable f es la frecuencia de activación o emisión de potenciales y u es la intensidad del estímulo del soma.