Program Jaringan Syaraf Tiruan ( Algoritma Perceptron)
File Perceptron.java
public class Perceptron {
private int[][] x;
private int[] w;
private int[] t;
private int b;
private int lRate;
private int y;
private int epoch;
private int net;
private boolean stop;
private boolean[] bobotBerubah;
public Perceptron(){
initial();
printInput();
learning();
}
private void printInput(){
System.out.println("Bobot awal dan bias: "+w[0]+" "+w[1]+" "+b);
System.out.println("Input data: x1 x2 target");
for(int i=0;i<4;i++){
System.out.println("Data ke-"+i+": "+x[i][0]+" "+x[i][1]+" "+t[i]);
}
}
private void initial(){
System.out.print("Initialing process....................\n");
// initial input
x = new int[4][2];
x[0][0] = 1;
x[0][1] = 1;
x[1][0] = 1;
x[1][1] = -1;
x[2][0] = -1;;
x[2][1] = 1;
x[3][0] = -1;
x[3][1] = -1;
// initial bobot;
w = new int[2];
w[0] = 0;
w[1] = 0;
// initial bias
b = 0;
// initial target;
t = new int[4];
t[0] = 1;
t[1] = -1;
t[2] = -1;
t[3] = -1;
// initial hasil(y) dan learning rate (alfa)
lRate = 1;
y = 0;
// initial bobot berubah
bobotBerubah = new boolean[4];
for(int i=0;i<4;i++){
bobotBerubah[i] = false;
}
}
private void learning(){
System.out.print("Learning process...............\n");
stop = false;
epoch = 0;
while(stop == false){
epoch++;
System.out.print("Epoch ke-"+epoch+"\n");
for(int i=0;i<4;i++){
net = x[i][0] * w[0] + x[i][1] * w[1] + b;
y = f(net);
if (y != t[i]) {
perbaikiBobot(i);
bobotBerubah[i] = true;
}else{
bobotBerubah[i] = false;
}
System.out.print("data ke-"+i+" w1 w2 dan b: "+w[0]+" "+w[1]+" "+b+"\n");
}
if(checkStop())stop = true;
}
}
private boolean checkStop(){
if(bobotBerubah[0])return false;
if(bobotBerubah[1])return false;
if(bobotBerubah[2])return false;
if(bobotBerubah[3])return false;
else return true;
}
private int f(int net){
if(net > 0) return 1;
else if(net == 0) return 0;
else return -1;
}
private void perbaikiBobot(int i){
w[0] = w[0] + lRate * t[i] * x[i][0];
w[1] = w[1] + lRate * t[i] * x[i][1];
b = b + lRate * t[i];
}
public void paternRecognize(int x1, int x2){
System.out.println("Pengenalan pola");
int net = x1 * w[0] + x2 * w[1] + b;
System.out.println("Input [x1 x2]: ["+x1+" "+x2+"] gerbang 'AND' dikenal dengan nilai "+f(net));
}
}
Main.java
public class Main {
public static void main(String[] args) {
Perceptron p = new Perceptron();
p.paternRecognize(1, 1);
p.paternRecognize(1, -1);
p.paternRecognize(-1, 1);
p.paternRecognize(-1, -1);
}
}
0 komentar to "Algortima Perceptron"
Posting Komentar