Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.text.DecimalFormat;
- import java.util.LinkedList;
- import javax.swing.*;
- public class Perceptron{
- private int x1=1,x2=1;
- private double w1,w2;
- private int []desired={0,0,0,1};
- private double y=0;
- private double c=0.2,alpha=0.1;
- private double error;
- private StringBuffer st;
- public Perceptron(){
- }
- public void start(){
- st=new StringBuffer();
- boolean exe=true;
- int count=0;
- st.append(" x1 x2| desired | w1\t w2\t|actual | error\t| w1\tw2 \n");
- st.append(" ============================================================ \n");
- while(exe&&count<50){
- exe=false;
- for(int i=0;i<4;i++){
- x2=Math.abs(x2-1); //to generate input,x2 0,1
- if(x2==0){
- x1=Math.abs(x1-1);//to generate input,x1 0,1
- }
- st.append(" "+x1+" "+x2+" | "+desired[i]
- +"\t | "+String.format("%.1f",w1)+"\t "+String.format("%.1f",w2)+"\t| " );
- activation();//activation process : y = summation of input(i) x weight(i), minus threshold
- int actual;
- if(y<0){// y is negative
- actual = 0;
- }
- else{// y is positive
- actual = 1;
- }
- error=desired[i]-actual;
- if(error!=0){//error occur : error = -1,1
- exe=true;
- weightTraining();// weight training : produce new weight
- }
- st.append(actual+"\t| "+error+"\t| "+w1+" "+w2);
- st.append("\n");
- }
- count++;
- st.append(" ============================================================ \n");
- }
- if(count>=50){
- JOptionPane.showMessageDialog(null,"Program Terminate.\nbecause system can't learn.\n(Infinite Loop)'","Message",JOptionPane.ERROR_MESSAGE);
- }
- }
- public void initialize(double tres,double alpha,double w1, double w2){
- this.w1=Double.parseDouble(String.format("%.1f",w1));
- this.w2=Double.parseDouble(String.format("%.1f",w2));
- this.c=Double.parseDouble(String.format("%.1f",tres));
- this.alpha=Double.parseDouble(String.format("%.1f",alpha));
- }
- public void activation(){
- y=(x1*w1+x2*w2)-c;
- }
- public void weightTraining(){
- DecimalFormat df = new DecimalFormat("#.#");
- Double.parseDouble(df.format(w1));
- w1=Double.parseDouble(df.format(w1+(alpha*error*x1)));
- w2=Double.parseDouble(df.format(w2+(alpha*error*x2)));
- }
- public void reset(){
- }
- public String toString(){
- String str=st.toString();
- return str;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment