-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathand.rb
114 lines (105 loc) · 2.78 KB
/
and.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
require 'csv'
$dataset, $w, $samples = [], [], []
$bias, $threshold, $miu = 1, 0, 0.3
def readFile(namaFile)
data = []
CSV.foreach(namaFile) do |row|
$kolom = row.count
$kolom.times { |i|
data[i] = row[i].to_i
}
$dataset.push(data)
data = []
end
end
def inputTarget
for i in 0...$dataset.length
for j in 0...$kolom
if (j < $kolom - 1)
$input_sequence[i][j] = $dataset[i][j]
else
$target_sequence[i] = $dataset[i][j]
end
end
end
end
def randomW
puts "Random nilai w : "
for i in 0...$kolom
$w[i] = rand(-1.0 .. 1.0).round(1)
print "w#{i} : #{$w[i]}"
puts
end
puts
end
def calcNN
$iterasi = 0
begin
$indeks = $iterasi + 1
$baris, $hasil, $benar = 0, 0.0, 0
puts "Iterasi ke-#{$indeks}"
begin
$hasil = 0
puts "Data ke-#{$baris}"
for i in 0...$kolom -1
$hasil = $hasil + ($input_sequence[$baris][i].to_f * $w[i])
end
$hasil = $hasil + $bias * $w[-1]
puts "Perhitungan\t\t\t: #{$hasil.round(1)}"
if ($hasil < $threshold)
$output = 0
else
$output = 1
end
puts "Hasil Threshold\t\t: #{$output}"
$err = $target_sequence[$baris] - $output
puts "Error\t\t\t\t: #{$err}"
if($err != 0)
puts "", "Nilai W baru : "
for x in 0...$kolom
if (x != $kolom -1)
$w[x] = $w[x] + $miu * $input_sequence[$baris][x] * $err
else
$w[x] = $w[x] + $miu * $bias * $err
end
puts "w#{x} : #{$w[x].round(1)}"
end
puts
$benar = 0
else
$benar = $benar + 1
end
$baris = $baris + 1
end while($baris < $input_sequence.length)
$iterasi = $iterasi + 1
puts
end while($iterasi < 100 && $benar!= $input_sequence.length)
puts "Total iterasi : #{$iterasi}", "Hasil w : "
$kolom.times { |i|
puts "w#{i} : #{$w[i].round(1)}"
}
puts
end
def cetakData
puts "Data AND"
print "x\ty\thasil\n"
for i in 0...$dataset.length
for j in 0...$kolom
print "#{$dataset[i][j]}\t"
end
puts
end
puts
puts "Threshold : #{$threshold}"
puts
end
$stdout = File.new("hasil_AND.txt", "w")
readFile("data_and.csv")
puts "Algoritma Neural Network"
$input_sequence = Array.new($dataset.length){Array.new($kolom)}
$target_sequence = []
cetakData
inputTarget
randomW
calcNN
$stdout.sync = true