fork(2) download
  1.  
  2. class Example{
  3. int x1, x2;
  4. double o;
  5. Example(int x1, int x2, double o){
  6. this.x1 = x1;
  7. this.x2 = x2;
  8. this.o = o;
  9. }
  10. }
  11.  
  12. class DeltaRulePerceptron {
  13. double w1, w2;
  14. double dw1, dw2;
  15. double n;
  16.  
  17. DeltaRulePerceptron(){
  18. //Random values
  19. w1 = -0.8;
  20. w2 = 0.7;
  21. n = 0.05;
  22. }
  23.  
  24. public double computeOutput(Example example){
  25. return example.x1 * w1 + example.x2*w2;
  26. }
  27.  
  28. public void trianWithDelta(Example[] examples){
  29. for(int i=0;i<1000;++i){
  30.  
  31. //System.out.println("Iteration #"+i);
  32. dw1 = 0;
  33. dw2 = 0;
  34.  
  35. for(Example ex:examples){
  36. double o = computeOutput(ex);
  37. double t = ex.o;
  38.  
  39. //System.out.println("o = "+o+" t = "+t);
  40.  
  41. dw1 = dw1 + n*(t-o)*ex.x1;
  42. dw2 = dw2 + n*(t-o)*ex.x2;
  43. }
  44.  
  45. w1 += dw1;
  46. w2 += dw2;
  47. }
  48. }
  49.  
  50. public static void main(String[] args){
  51. DeltaRulePerceptron dr = new DeltaRulePerceptron();
  52.  
  53. //AND boolean function
  54. Example[] examples = new Example[]{
  55. new Example(-1, -1, -1),
  56. new Example(-1 , 1, -1),
  57. new Example( 1, -1, -1),
  58. new Example( 1, 1, 1)
  59. };
  60. dr.trianWithDelta(examples);
  61. System.out.println("Trained weights : "+dr.w1+" "+dr.w2);
  62.  
  63. //Test
  64. System.out.println(dr.sign(dr.computeOutput(examples[0])));
  65. System.out.println(dr.sign(dr.computeOutput(examples[1])));
  66. System.out.println(dr.sign(dr.computeOutput(examples[2])));
  67. System.out.println(dr.sign(dr.computeOutput(examples[3])));
  68.  
  69.  
  70. }
  71.  
  72. public int sign(double output){
  73. return output>0?+1:-1;
  74. }
  75. }
  76.  
Success #stdin #stdout 0.13s 320576KB
stdin
Standard input is empty
stdout
Trained weights : 0.49999999999999994 0.5000000000000002
-1
1
-1
1