Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.

domingo, 31 de julio de 2022

Graficando red neuronal en 4K (perceptrón).

Código 1 (Graficando_Perceptron):

package blogger_graficando;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Graficando_Perceptron extends javax.swing.JFrame {

    public int x = 3840;
    public int y = 2160;

    public Graficando_Perceptron() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

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

        jPanelEstructura = new javax.swing.JPanel();
        jLabelEstructura = new javax.swing.JLabel();
        jTextFieldEstructura = new javax.swing.JTextField();
        jPanelResolucion = new javax.swing.JPanel();
        jLabelAnchura = new javax.swing.JLabel();
        jTextFieldAnchura = new javax.swing.JTextField();
        jLabelAltura = new javax.swing.JLabel();
        jTextFieldAltura = new javax.swing.JTextField();
        jPanelBotonera = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButtonGraficar = new javax.swing.JButton();
        jButtonRestaurar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Graficando Perceptron");

        jLabelEstructura.setText("Estructura:");

        jTextFieldEstructura.setText("4,20,20,20,20,8");

        javax.swing.GroupLayout jPanelEstructuraLayout = new javax.swing.GroupLayout(jPanelEstructura);
        jPanelEstructura.setLayout(jPanelEstructuraLayout);
        jPanelEstructuraLayout.setHorizontalGroup(
            jPanelEstructuraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelEstructuraLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(jLabelEstructura)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextFieldEstructura, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanelEstructuraLayout.setVerticalGroup(
            jPanelEstructuraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelEstructuraLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelEstructuraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelEstructuraLayout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabelEstructura))
                    .addComponent(jTextFieldEstructura, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanelResolucion.setLayout(new java.awt.GridLayout());

        jLabelAnchura.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelAnchura.setText("Anchura:");
        jPanelResolucion.add(jLabelAnchura);

        jTextFieldAnchura.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextFieldAnchura.setText("3840");
        jPanelResolucion.add(jTextFieldAnchura);

        jLabelAltura.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelAltura.setText("Altura:");
        jPanelResolucion.add(jLabelAltura);

        jTextFieldAltura.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextFieldAltura.setText("2160");
        jPanelResolucion.add(jTextFieldAltura);

        jPanelBotonera.setLayout(new java.awt.GridLayout());
        jPanelBotonera.add(jLabel1);
        jPanelBotonera.add(jLabel2);

        jButtonGraficar.setText("Graficar");
        jButtonGraficar.setFocusable(false);
        jButtonGraficar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonGraficar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonGraficar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGraficarActionPerformed(evt);
            }
        });
        jPanelBotonera.add(jButtonGraficar);

        jButtonRestaurar.setText("Restaurar");
        jButtonRestaurar.setFocusable(false);
        jButtonRestaurar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtonRestaurar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtonRestaurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRestaurarActionPerformed(evt);
            }
        });
        jPanelBotonera.add(jButtonRestaurar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jPanelBotonera, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jPanelResolucion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jPanelEstructura, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jPanelBotonera, jPanelEstructura, jPanelResolucion});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanelEstructura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelResolucion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanelBotonera, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jPanelBotonera, jPanelEstructura, jPanelResolucion});

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

    private void jButtonGraficarActionPerformed(java.awt.event.ActionEvent evt) {                                                
        String estructura = jTextFieldEstructura.getText();
        x = Integer.parseInt(jTextFieldAnchura.getText());
        y = Integer.parseInt(jTextFieldAltura.getText());
        BufferedImage imagen = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
        Dibujar t = new Dibujar(imagen.getGraphics(), x, y, jTextFieldEstructura.getText());
        try {
            ImageIO.write(imagen, "png", new File("p" + x + "x" + y+"(" + estructura + ").png"));
        } catch (IOException e) {
            System.out.println("Error de escritura");
        }

    }                                               

    private void jButtonRestaurarActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        jTextFieldEstructura.setText("4,20,20,20,20,8");
        jTextFieldAnchura.setText("3840");
        jTextFieldAltura.setText("2160");

    }                                                

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Graficando_Perceptron().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonGraficar;
    private javax.swing.JButton jButtonRestaurar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabelAltura;
    private javax.swing.JLabel jLabelAnchura;
    private javax.swing.JLabel jLabelEstructura;
    private javax.swing.JPanel jPanelBotonera;
    private javax.swing.JPanel jPanelEstructura;
    private javax.swing.JPanel jPanelResolucion;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextFieldAltura;
    private javax.swing.JTextField jTextFieldAnchura;
    private javax.swing.JTextField jTextFieldEstructura;
    // End of variables declaration       
        
  

}



Código 2 (Dibujar.java):

package blogger_graficando;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class Dibujar {

    Graphics g;
    Graphics2D g2;
    Random random = new Random();
    Boolean c50;

    public Dibujar(Graphics g, int width, int height, String estruct) {

        g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // Grosor pincel
        Stroke stroke04 = new BasicStroke(0.4f);

        // fondo blanco
        g2.setColor(Color.WHITE);
        g2.draw3DRect(0, 0, width, height, true);
        g2.fillRect(0, 0, width, height);

        // añadir datos estructura perceptrón
        List<Integer> estructura = new ArrayList<>();
        for (String aux1 : estruct.split(",")) {
            estructura.add(Integer.parseInt(aux1));
        }

        int maxX = estructura.size();
        int maxY = maximo(estructura);

        int nParticionesX = maxX + 2; // se suma 2 para margen  izquierdo e derecho
        int nParticionesY = maxY + 2; // se suma 2 para margen  superior e inferior

        int uX = width / nParticionesX;
        int uY = height / nParticionesY;

        float uSeparadorX = (nParticionesX - estructura.size()) / 2f;
        float uSeparadorY;

        int posIniX = (int) Math.round(uX * uSeparadorX);
        int posIniY;

        int[][][] recopilador = new int[maxX][maxY][2]; // k, x, y

        // capa 0: pre-logical posiciones
        for (int x = 0; x < estructura.size(); x++) {
            for (int y = 0; y < estructura.get(x); y++) {
                uSeparadorY = (nParticionesY - estructura.get(x)) / 2f;
                posIniY = (int) Math.round(uY * uSeparadorY);
                recopilador[x][y][0] = (posIniX + (int) uX * x) + (int) (uX / 2);
                recopilador[x][y][1] = (posIniY + (int) uY * y) + (int) (uY / 2);
            }
        }

        // capa 1: graficar enlaces
        int x1, y1, x2, y2;
        g2.setStroke(stroke04);
        for (int x = 0; x < estructura.size() - 1; x++) {
            for (int y = 0; y < estructura.get(x); y++) {
                for (int k = 0; k < estructura.get(x + 1); k++) {
                    x1 = recopilador[x][y][0];
                    y1 = recopilador[x][y][1];
                    x2 = recopilador[x + 1][k][0];
                    y2 = recopilador[x + 1][k][1];
                    colorRnd();
                    g2.drawLine(x1, y1, x2, y2);
                }
            }
        }

        // capa 2: graficar neuronas
        int radio = (int) Math.round(uY / 4f);
        for (int x = 0; x < estructura.size(); x++) {
            for (int y = 0; y < estructura.get(x); y++) {
                colorRnd();
                centrarCirculo(g2, recopilador[x][y][0], recopilador[x][y][1], radio);
            }
        }

        // capa 3: marca de agua
        String marca = "https://censorcosmico.blogspot.com/";
        String estructura2 = "Estructura de red: [" + estruct + "]";
        String resolucion = "Resolución: " + width + "x" + height;
        g2.setColor(Color.DARK_GRAY);
        g2.drawString(marca, 50, 50);
        g2.drawString(estructura2, 50, 70);
        g2.drawString(resolucion, 50, 90);

    }

    private void centrarCirculo(Graphics g2, int x, int y, int r) {
        x = x - (r / 2);
        y = y - (r / 2);
        g2.fillOval(x, y, r, r);
    }

    /* Busca número mayor del listado de la estructura
   * Utilizado para acomodar la gráfica al tamaño de la ventana
     */

    private int maximo(List<Integer> estructura) {
        int max = 0;
        for (int i = 0; i < estructura.size(); i++) {
            if (estructura.get(i) >= max) {
                max = estructura.get(i);
            }
        }
        return max;
    }

    private void colorRnd() {
        c50 = (random.nextInt(9) == 0);
        if (c50) {
            g2.setColor(Color.RED);
        } else {
            g2.setColor(Color.DARK_GRAY);
        }
    }

}


Resultado:


 

 

 


 

No hay comentarios:

Publicar un comentario

Con la tecnología de Blogger.