⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nn.java

📁 java applet实现的bp神经网络和感知器
💻 JAVA
字号:
import java.awt.*;import java.awt.event.*;import java.applet.*;import java.io.*;import java.net.*;import java.util.Properties;public class nn extends Applet {    Choice netChoice;//网络模型    Choice inNumChoice;    Choice hideNumChoice;    Choice outNumChoice;    Checkbox chkbox_save;    int task;    String file = null;    BpNet bpnet;    Perceptron perceptron;    boolean clear;    int row;    int left;    int bottom;    int top;    double p1[][];//训练样本集输入    double t1[][];//训练样本集输出    double p2[][];//模拟数据输入    int inNum;    int hideNum;    int outNum;    int sampleNum;    int simNum;    PrintStream ps;    int epochs;    TextArea txtarea;    public void init() {        left = 50;        top = 80;        bottom = 300;        clear = false;        row = 0;        epochs = 70001;        setLayout(new BorderLayout());        Panel topPanel = new Panel();        Panel bottomPanel = new Panel();        netChoice = new Choice();        netChoice.addItem("BP network");        netChoice.addItem("Perceptron");        netChoice.addItemListener(new ItemListener() {            public void itemStateChanged(ItemEvent event) {                repaint();            }        });        topPanel.add(netChoice);        Label lab_inNum = new Label("输入节点数:");        topPanel.add(lab_inNum);        inNumChoice = new Choice();        for (int i = 1; i < 10; i++) {            inNumChoice.addItem(String.valueOf(i));        }        topPanel.add(inNumChoice);        Label lab_hideNum = new Label("隐含节点数:");        topPanel.add(lab_hideNum);        hideNumChoice = new Choice();        for (int i = 1; i < 10; i++) {            hideNumChoice.addItem(String.valueOf(i));        }        hideNumChoice.select("3");        topPanel.add(hideNumChoice);        Label lab_outNum = new Label("输出节点数:");        topPanel.add(lab_outNum);        outNumChoice = new Choice();        for (int i = 1; i < 10; i++) {            outNumChoice.addItem(String.valueOf(i));        }        topPanel.add(outNumChoice);        Button button_load = new Button("LoadData");        button_load.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent event) {                task = 10;                repaint();            }        });        topPanel.add(button_load);        Button button_train = new Button("Train");        button_train.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent event) {                task = 1;                repaint();            }        });        topPanel.add(button_train);        Button button_sim = new Button("Simulation");        button_sim.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent event) {                task = 2;                repaint();            }        });        topPanel.add(button_sim);        chkbox_save = new Checkbox("save data");        add("North", topPanel);        txtarea = new TextArea(12, 105);        bottomPanel.add(txtarea);        add("South", bottomPanel);    }    public void paint(Graphics g) {        setBackground(Color.white);        switch (task) {            case 1:                if (netChoice.getSelectedItem() == "BP network") {                    drawBpTrain(g);                } else if (netChoice.getSelectedItem() == "Perceptron") {                    drawPerceptron(g);                }                break;            case 2:                if (netChoice.getSelectedItem() == "BP network") {                    drawBpSim(g);                } else if (netChoice.getSelectedItem() == "Perceptron") {                    drawPerceptronSim(g);                }                break;            case 10:                loadData(g);                break;        }//end switch        task = 0;    }    public void drawPerceptron(Graphics g) {        perceptron = new Perceptron(Integer.parseInt(inNumChoice.getSelectedItem()), Integer.parseInt(outNumChoice.getSelectedItem()));        double E = 0.1;        perceptron.e = E + 1;        int p = 0;//记录循环次数        while (perceptron.e > E) {            perceptron.train(p1, t1, sampleNum);            txtarea.append(String.valueOf(perceptron.e) + "\n");            p++;        }        txtarea.append("-----------------------------------\n");        txtarea.append("Perceptron\n");        txtarea.append("-----------------------------------\n");        txtarea.append("inNum:" + String.valueOf(perceptron.inNum) + "\n");        txtarea.append("outNum:" + String.valueOf(perceptron.outNum) + "\n");        txtarea.append("curTimes" + String.valueOf(p) + "\n");        /*for (int n = 0; n < sampleNum; n++) {        for (int j = 0; j < perceptron.inNum; j++) {        txtarea.append("x[" + String.valueOf(n) + "][" + String.valueOf(j) + "]" + String.valueOf(p1[n][j]) + "\n");        }        }*/        for (int i = 0; i < perceptron.inNum; i++) {            for (int j = 0; j < perceptron.outNum; j++) {                txtarea.append("w(" + String.valueOf(i) + "," + String.valueOf(j) + ")" + String.valueOf(perceptron.w[i][j]) + "\n");            }        }        txtarea.append("-----------------------------------\n");    }    public void drawPerceptronSim(Graphics g) {        double p21[] = new double[inNum];        double t2[] = new double[outNum];        txtarea.append("-------------------------------\n");        txtarea.append("Perceptron Simulation Results:\n");        txtarea.append("-------------------------------\n");        for (int n = 0; n < simNum; n++) {            for (int i = 0; i < inNum; i++) {                p21[i] = p2[n][i];            }            if (row > 10) {                row = 0;                cleartext(g);            }            t2 = perceptron.sim(p21);            row++;            txtarea.append("inputvalue:\n");            for (int i = 0; i < perceptron.inNum; i++) {                txtarea.append(String.valueOf(p21[i]) + "\n");            }            row++;            txtarea.append("outputvalue:\n");            for (int i = 0; i < perceptron.outNum; i++) {                txtarea.append(String.valueOf(t2[i]) + "\n");            }        }    }    public void drawBpTrain(Graphics g) {        int time = 1000;        double etime = 1000.0;        bpnet = new BpNet(Integer.parseInt(inNumChoice.getSelectedItem()), Integer.parseInt(hideNumChoice.getSelectedItem()), Integer.parseInt(outNumChoice.getSelectedItem()));        //绘制误差曲线坐标        g.setColor(getBackground());        g.fillRect(0, 0, left, bottom);        g.setColor(getForeground());        g.drawLine(left, bottom, left + 1000, bottom);        g.drawLine(left, bottom, left, 0);        double E = 0.0002;//精度控制参数        bpnet.e = E + 1;        int xi = 0;//横坐标        //for (int i = 0; i < 5000; i++) {        while (bpnet.e > E) {            bpnet.train(p1, t1, sampleNum);            g.setColor(Color.blue);            if (xi / 5 * 5 == xi) {                g.drawLine(left + xi / 5, bottom - (int) (bpnet.e * etime), left + xi / 5, bottom - (int) (bpnet.e * etime) - 1);            }            g.setColor(Color.black);            if (xi / 500 * 500 == xi) {                g.drawLine(left + xi / 5, bottom, left + xi / 5, bottom + 3);                g.drawString(String.valueOf(xi), left + xi / 5, bottom + 15);            }            xi++;        }        txtarea.append("-----------------------------------\n");        txtarea.append("BpNet\n");        txtarea.append("-----------------------------------\n");        txtarea.append("inNum:" + String.valueOf(bpnet.inNum) + "\n");        txtarea.append("hideNum:" + String.valueOf(bpnet.hideNum) + "\n");        txtarea.append("outNum:" + String.valueOf(bpnet.outNum) + "\n");        txtarea.append("in_rate:" + String.valueOf(bpnet.in_rate) + "\n");        txtarea.append("e:" + String.valueOf(bpnet.e) + "\n");        txtarea.append("curTimes:" + String.valueOf(xi) + "\n");        txtarea.append("w\n");        for (int i = 0; i <                bpnet.inNum; i++) {            for (int j = 0; j < bpnet.hideNum; j++) {                txtarea.append("w(" + String.valueOf(i) + "," + String.valueOf(j) + ")" + String.valueOf(bpnet.w[i][j]) + "\n");            }        }        txtarea.append("w1\n");        for (int i = 0; i < bpnet.hideNum; i++) {            for (int j = 0; j < bpnet.outNum; j++) {                txtarea.append("w1(" + String.valueOf(i) + "," + String.valueOf(j) + ")" + String.valueOf(bpnet.w1[i][j]) + "\n");            }        }        txtarea.append("-----------------------------------\n");    }//end drawbptarin    public void drawBpSim(Graphics g) {        double p21[] = new double[inNum];        double t2[] = new double[outNum];        /*if (chkbox_save.getState()) {        try {        ps = null;        ps = new PrintStream(new FileOutputStream("nnsave.txt"));        ps.println("-------------------------------");        ps.println("BpNet Simulation Results:");        ps.println("-------------------------------");        } catch (Exception e) {        }        }*/        txtarea.append("-------------------------------\n");        txtarea.append("BpNet Simulation Results:\n");        txtarea.append("-------------------------------\n");        for (int n = 0; n < simNum; n++) {            for (int i = 0; i < inNum; i++) {                p21[i] = p2[n][i];            }            if (row > 10) {                row = 0;                cleartext(g);            }            t2 = bpnet.sim(p21);            row++;            txtarea.append("inputvalue:\n");            for (int i = 0; i < bpnet.inNum; i++) {                txtarea.append(String.valueOf(p21[i]) + "\n");            }            row++;            txtarea.append("outputvalue:\n");            for (int i = 0; i < bpnet.outNum; i++) {                txtarea.append(String.valueOf(t2[i]) + "\n");            }        }//end for n    }//end drawbpsim    public void loadData(Graphics g) {//读取学习数据        clearall(g);        row = 0;        String str_p1 = "";        String str_t1 = "";        String str_p2 = "";        if (netChoice.getSelectedItem() == "Perceptron") {            file = "nndata2.txt";        } else {            file = "nndata.txt";        }        try {            URL filedata = null;            DataInputStream dis = null;            filedata = new URL(getCodeBase() + file);            dis = new DataInputStream(filedata.openStream());            String line = dis.readLine();            row++;            simNum = 1;            while (line != null) {                if (line.indexOf("inNum:") >= 0) {                    inNum = Integer.parseInt(line.substring(line.indexOf("inNum:") + 6));                }                if (line.indexOf("hideNum:") >= 0) {                    hideNum = Integer.parseInt(line.substring(line.indexOf("hideNum:") + 8));                }                if (line.indexOf("outNum:") >= 0) {                    outNum = Integer.parseInt(line.substring(line.indexOf("outNum:") + 7));                }                if (line.indexOf("sampleNum:") >= 0) {                    sampleNum = Integer.parseInt(line.substring(line.indexOf("sampleNum:") + 10));                }                if (line.indexOf("simNum:") >= 0) {                    simNum = Integer.parseInt(line.substring(line.indexOf("simNum:") + 7));                }                if (line.indexOf("p1:") >= 0) {                    str_p1 += line.substring(line.indexOf("p1:") + 3);                }                if (line.indexOf("t1:") >= 0) {                    str_t1 += line.substring(line.indexOf("t1:") + 3);                }                if (line.indexOf("p2:") >= 0) {                    str_p2 += line.substring(line.indexOf("p2:") + 3);                }                txtarea.append(line + "\n");                row++;                line = dis.readLine();            }//end while            inNumChoice.select(String.valueOf(inNum));            hideNumChoice.select(String.valueOf(hideNum));            outNumChoice.select(String.valueOf(outNum));            p1 = new double[sampleNum][inNum];            t1 = new double[sampleNum][outNum];            p2 = new double[simNum][inNum];            p1 = readarray(sampleNum, inNum, str_p1);            t1 = readarray(sampleNum, outNum, str_t1);            p2 = readarray(simNum, inNum, str_p2);        }//end try        catch (Exception e) {            System.out.println(e.getMessage());        }    }//end loadData    public void update(Graphics g) {        paint(g);    }//end update//读取数据到数组    public double[][] readarray(int r, int c, String str_array) {        String str_flow = str_array;        String str_num = "";        double array[][] = new double[r][c];        for (int i = 0; i < r; i++) {            for (int j = 0; j < c; j++) {                while ((str_flow.charAt(0) == '{') || (str_flow.charAt(0) == ',') || (str_flow.charAt(0) == '}')) {                    str_flow = str_flow.substring(1);                }                str_num = "";                while ((str_flow.charAt(0) != '{') && (str_flow.charAt(0) != ',') && (str_flow.charAt(0) != '}')) {                    str_num += str_flow.substring(0, 1);                    str_flow = str_flow.substring(1);                }                array[i][j] = Double.valueOf(str_num).doubleValue();            }        }//end for        return array;    }//end readdarray    public void cleartext(Graphics g) {        g.setColor(getBackground());        g.fillRect(0, bottom + 20, this.getSize().width, this.getSize().height);        g.setColor(getForeground());    }    public void clearall(Graphics g) {        g.setColor(getBackground());        g.fillRect(0, 0, this.getSize().width, this.getSize().height);        g.setColor(getForeground());    }    static Frame getFrame(Component c) {        while ((c = c.getParent()) != null) {            if (c instanceof Frame) {                return (Frame) c;            }        }        return null;    }    static void printComponents(Component c) {        Toolkit tk = Toolkit.getDefaultToolkit();        Frame frame = getFrame(c);        Properties props = new Properties();        props.put("awt.print.printer", "durange");        props.put("awt.print.numCopies", "2");        if (tk != null) {            String name = c.getName() + "print job";            PrintJob pj = tk.getPrintJob(frame, name, props);            if (pj != null) {                Graphics pg = pj.getGraphics();                if (pg != null) {                    try {                        c.printAll(pg);                    } finally {                        pg.dispose();                    }                }                pj.end();            }            System.out.println(props);        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -