blib/lib/AI/NeuralNet/Mesh.pm

filter: Statementstmt 51.5% 384 / 745 Branchbran 34.4% 62 / 180 Conditioncond 26.1% 22 / 84 MC/DCmcdc 10.4% 5 / 48 Subroutinesub 47.6% 41 / 86 Podpod 89.5% 43 / 48 totaltotal 46.7% 557 / 1191 CC 193 SCAR 30.1
CC
193
Cov
46%
load_old
110.0
extend
72.0
extend_layer
56.0
CRAP 20.3
↑ Summary
1 #!/usr/bin/perl
2
3 # Copyright (c) 2000 Josiah Bryan USA
4 #
5 # See AUTHOR section in pod text below for usage and distribution rights.
6 #
7
8 1 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 $AI::NeuralNet::Mesh::VERSION = "0.44";
10 1 $AI::NeuralNet::Mesh::ID =
11 '$Id: AI::NeuralNet::Mesh.pm, v'.$AI::NeuralNet::Mesh::VERSION.' 2000/15/09 03:29:08 josiah Exp $';
12 }
13
14 package AI::NeuralNet::Mesh;
15
16 1 require Exporter;
17 1 @ISA = qw(Exporter);
18 1 @EXPORT = qw(range intr pdiff);
19 1 %EXPORT_TAGS = (
20 'default' => [ qw ( range intr pdiff )],
21 'all' => [ qw ( p low high ramp and_gate or_gate range intr pdiff ) ],
22 'p' => [ qw ( p low high intr pdiff ) ],
23 'acts' => [ qw ( ramp and_gate or_gate range ) ],
24 );
25 1 @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} }, qw( p low high ramp and_gate or_gate ) );
26
27 1 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 1 ▶ use Benchmark;
Subroutine BEGIN: called CC=1 SCAR=0.0
29
30 # See POD for usage of this variable.
31 1 $AI::NeuralNet::Mesh::Connector = '_c';
32
33 # Debugging subs
34 1 $AI::NeuralNet::Mesh::DEBUG = 0;
35 0 ▶ sub whowasi { (caller(1))[3] . '()' }
Subroutine whowasi: not called CC=1 SCAR=6.9
Pod undocumented
36 0 ▶ sub debug { shift; $AI::NeuralNet::Mesh::DEBUG = shift || 0; }
Subroutine debug: not called CC=2 SCAR=17.9
Pod documented
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
37 1566 ▶ sub d { shift if(substr($_[0],0,4) eq 'AI::'); my ($a,$b,$c)=(shift,shift,$AI::NeuralNet::Mesh::DEBUG); print $a if($c == $b); return $c }
Subroutine d: called CC=3 SCAR=11.0
Pod undocumented
Branch: 2 branches
BranchTrueFalseTotal
if substr($_[0], 0, 4) eq "AI::" 994 572 1566
if $c == $b 78 1488 1566
38 0 ▶ sub verbose {debug @_};
Subroutine verbose: not called CC=1 SCAR=6.9
Pod documented
39 0 ▶ sub verbosity {debug @_};
Subroutine verbosity: not called CC=1 SCAR=6.9
Pod documented
40 0 ▶ sub v {debug @_};
Subroutine v: not called CC=1 SCAR=6.9
Pod documented
41
42
43 # Return version of ::ID string passed or current version of this
44 # module if no string is passed. Used in load() to detect file versions.
45 1 ▶ sub version {
Subroutine version: called CC=3 SCAR=13.1
Pod undocumented
46 1 ▶ shift if(substr($_[0],0,4) eq 'AI::');
Branch: 1 branch
BranchTrueFalseTotal
if substr($_[0], 0, 4) eq "AI::" 1 0 1
47 1 ▶ substr((split(/\s/,(shift || $AI::NeuralNet::Mesh::ID)))[2],1);
Condition33%1/3
shift() || $AI::NeuralNet::Mesh::ID
l!l&&r!l&&!r
100
MC/DC0%0/2
shift() || $AI::NeuralNet::Mesh::ID
shift() $AI::NeuralNet::Mesh::ID
Truth table33%1/3
A || B
A= shift()B= $AI::NeuralNet::Mesh::ID
ABresult
1X1
011
000
48 }
49
50 # Rounds a floating-point to an integer with int() and sprintf()
51 165 ▶ sub intr {
Subroutine intr: called CC=2 SCAR=7.6
Pod documented
52 165 ▶ shift if(substr($_[0],0,4) eq 'AI::');
Branch: 1 branch
BranchTrueFalseTotal
if substr($_[0], 0, 4) eq "AI::" 165 0 165
53 165 try { return int(sprintf("%.0f",shift)) }
54 0 catch { return 0 }
55 }
56
57 # Package constructor
58 3 ▶ sub new {
Subroutine new: called CC=11 SCAR=26.6
Pod documented
59 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
60 3 my $type = shift;
61 3 my $self = {};
62 3 my $layers = shift;
63 3 my $nodes = shift;
64 3 ▶ my $outputs = shift || $nodes;
Condition66%2/3
shift() || $nodes
l!l&&r!l&&!r
102
MC/DC50%1/2
shift() || $nodes
shift() $nodes
Truth table66%2/3
A || B
A= shift()B= $nodes
ABresult
1X1
011
000
65 3 ▶ my $inputs = shift || $nodes;
Condition66%2/3
shift() || $nodes
l!l&&r!l&&!r
012
MC/DC50%1/2
shift() || $nodes
shift() $nodes
Truth table66%2/3
A || B
A= shift()B= $nodes
ABresult
1X1
011
000
66
67 3 bless $self, $type;
68
69 # If $layers is a string, then it will be numerically equal to 0, so
70 # try to load it as a network file.
71 3 ▶ if($layers == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($layers == 0) 1 2 3
72 # We use a "1" flag as the second argument to indicate that we
73 # want load() to call the new constructor to make a network the
74 # same size as in the file and return a refrence to the network,
75 # instead of just creating the network from pre-exisiting refrence
76 1 return $self->load($layers,1);
77 }
78
79 # Looks like we got ourselves a layer specs array
80 2 ▶ if(ref($layers) eq "ARRAY") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $layers eq 'ARRAY') { } 1 1 2
81 1 ▶ if(ref($layers->[0]) eq "HASH") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $layers->[0] eq 'HASH') { } 0 1 1
82 0 $self->{total_nodes} = 0;
83 0 $self->{inputs} = $layers->[0]->{nodes};
84 0 $self->{nodes} = $layers->[0]->{nodes};
85 0 $self->{outputs} = $layers->[$#{$layers}]->{nodes};
86 0 $self->{total_layers} = $#{$layers};
87 0 for (0..$#{$layers}){$self->{layers}->[$_] = $layers->[$_]->{nodes}}
88 0 for (0..$self->{total_layers}){$self->{total_nodes}+=$self->{layers}->[$_]}
89 } else {
90 1 $self->{inputs} = $layers->[0];
91 1 $self->{nodes} = $layers->[0];
92 1 $self->{outputs} = $layers->[$#{$layers}];
93 1 $self->{layers} = $layers;
94 1 $self->{total_layers} = $#{$self->{layers}};
95 1 $self->{total_nodes} = 0;
96 1 for (0..$self->{total_layers}) {
97 3 $self->{total_nodes}+=$self->{layers}->[$_];
98 }
99 }
100 } else {
101 1 $self->{total_nodes} = $layers * $nodes + $outputs;
102 1 $self->{total_layers} = $layers;
103 1 $self->{nodes} = $nodes;
104 1 $self->{inputs} = $inputs;
105 1 $self->{outputs} = $outputs;
106 }
107
108 # Initalize misc. variables
109 2 $self->{col_width} = 5;
110 2 $self->{random} = 0;
111 2 $self->{const} = 0.0001;
112 2 $self->{connector} = $AI::NeuralNet::Mesh::Connector;
113
114 # Build mesh
115 2 $self->_init();
116
117 # Initalize activation, thresholds, etc, if provided
118 2 ▶ if(ref($layers->[0]) eq "HASH") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $layers->[0] eq "HASH") 0 2 2
119 0 for (0..$self->{total_layers}) {
120 0 $self->activation($_,$layers->[$_]->{activation});
121 0 $self->threshold($_,$layers->[$_]->{threshold});
122 0 $self->mean($_,$layers->[$_]->{mean});
123 }
124 }
125
126 # Done!
127 2 return $self;
128 }
129
130
131 # Internal usage
132 # Connects one range of nodes to another range
133 6 ▶ sub _c {
Subroutine _c: called CC=5 SCAR=16.8
134 6 my $self = shift;
135 6 my $r1a = shift;
136 6 my $r1b = shift;
137 6 my $r2a = shift;
138 6 my $r2b = shift;
139 6 ▶ my $m1 = shift || $self->{mesh};
Condition33%1/3
shift() || $self->{'mesh'}
l!l&&r!l&&!r
060
MC/DC0%0/2
shift() || $self->{'mesh'}
shift() $self->{'mesh'}
Truth table33%1/3
A || B
A= shift()B= $self->{'mesh'}
ABresult
1X1
011
000
140 6 ▶ my $m2 = shift || $m1;
Condition33%1/3
shift() || $m1
l!l&&r!l&&!r
060
MC/DC0%0/2
shift() || $m1
shift() $m1
Truth table33%1/3
A || B
A= shift()B= $m1
ABresult
1X1
011
000
141 6 for my $y ($r1a..$r1b-1) {
142 12 for my $z ($r2a..$r2b-1) {
143 18 $m1->[$y]->add_output_node($m2->[$z]);
144 }
145 }
146 }
147
148 # Internal usage
149 # Creates the mesh of neurons
150 3 ▶ sub _init {
Subroutine _init: called CC=9 SCAR=22.2
151 3 my $self = shift;
152 3 my $nodes = $self->{nodes};
153 3 ▶ my $outputs = $self->{outputs} || $nodes;
Condition33%1/3
$self->{'outputs'} || $nodes
l!l&&r!l&&!r
300
MC/DC0%0/2
$self->{'outputs'} || $nodes
$self->{'outputs'} $nodes
Truth table33%1/3
A || B
A= $self->{'outputs'}B= $nodes
ABresult
1X1
011
000
154 3 ▶ my $inputs = $self->{inputs} || $nodes;
Condition33%1/3
$self->{'inputs'} || $nodes
l!l&&r!l&&!r
300
MC/DC0%0/2
$self->{'inputs'} || $nodes
$self->{'inputs'} $nodes
Truth table33%1/3
A || B
A= $self->{'inputs'}B= $nodes
ABresult
1X1
011
000
155 3 my $layers = $self->{total_layers};
156 3 ▶ my $tmp = $self->{total_nodes} || ($layers * $nodes + $outputs);
Condition33%1/3
$self->{'total_nodes'} || $layers * $nodes + $outputs
l!l&&r!l&&!r
300
MC/DC0%0/2
$self->{'total_nodes'} || $layers * $nodes + $outputs
$self->{'total_nodes'} $layers * $nodes + $outputs
Truth table33%1/3
A || B
A= $self->{'total_nodes'}B= $layers * $nodes + $outputs
ABresult
1X1
011
000
157 3 my $layer_specs = $self->{layers};
158 3 my $connector = $self->{connector};
159 3 my ($x,$y,$z);
160 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
161
162 # Just to be safe.
163 3 $self->{total_nodes} = $tmp;
164
165 # If they didn't give layer specifications, then we derive our own specs.
166 3 ▶ if(!(defined $self->{layers})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"layers"}) 1 2 3
167 1 $layer_specs = [split(',',"$nodes," x $layers)];
168 1 $layer_specs->[$#{$layer_specs}+1]=$outputs;
169 1 $self->{layers} = $layer_specs;
170 }
171
172 # First create the individual nodes
173 3 for my $x (0..$tmp-1) {
174 15 $self->{mesh}->[$x] = AI::NeuralNet::Mesh::node->new($self);
175 }
176
177 # Get an instance of an output (data collector) node
178 3 $self->{output} = AI::NeuralNet::Mesh::output->new($self);
179
180 # Connect the output layer to the data collector
181 3 for $x (0..$outputs-1) {
182 3 $self->{mesh}->[$tmp-$outputs+$x]->add_output_node($self->{output});
183 }
184
185 # Now we use the _c() method to connect the layers together.
186 3 $y=0;
187 3 my $c = $connector.'($self,$y,$y+$z,$y+$z,$y+$z+$layer_specs->[$x+1])';
188 3 for $x (0..$layers-1) {
189 6 $z = $layer_specs->[$x];
190 6 d("layer $x size: $z (y:$y)\n,",1);
191 6 eval $c;
192 6 $y+=$z;
193 }
194
195 # Get an instance of our cap node.
196 3 $self->{input}->{cap} = AI::NeuralNet::Mesh::cap->new();
197
198 # Add a cap to the bottom of the mesh to stop it from trying
199 # to recursivly adjust_weight() where there are no more nodes.
200 3 for my $x (0..$inputs-1) {
201 $self->{input}->{IDs}->[$x] =
202 6 $self->{mesh}->[$x]->add_input_node($self->{input}->{cap});
203 }
204 }
205
206 # See POD for usage
207 0 ▶ sub extend {
Subroutine extend: not called CC=8 SCAR=42.8
Pod documented
208 0 my $self = shift;
209 0 my $layers = shift;
210
211 # Looks like we got ourselves a layer specs array
212 0 ▶ if(ref($layers) eq "ARRAY") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $layers eq 'ARRAY') { } 0 0 0
213 0 ▶ if($self->{total_layers}!=$#{$layers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"total_layers"} != $#{$layers;}) 0 0 0
214 0 $self->{error} = "extend(): Cannot add new layers. Create a new network to add layers.\n";
215 0 return undef;
216 }
217 0 ▶ if(ref($layers->[0]) eq "HASH") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $layers->[0] eq 'HASH') { } 0 0 0
218 0 $self->{total_nodes} = 0;
219 0 $self->{inputs} = $layers->[0]->{nodes};
220 0 $self->{nodes} = $layers->[0]->{nodes};
221 0 $self->{outputs} = $layers->[$#{$layers}]->{nodes};
222 0 for (0..$#{$layers}){
223 0 $self->extend_layer($_,$layers->[$_]);
224 0 $self->{layers}->[$_] =$layers->[$_]->{nodes};
225 }
226 0 for (0..$self->{total_layers}){$self->{total_nodes}+=$self->{layers}->[$_]}
227 } else {
228 0 $self->{inputs} = $layers->[0];
229 0 $self->{nodes} = $layers->[0];
230 0 $self->{outputs} = $layers->[$#{$layers}];
231 0 $self->{total_nodes} = 0;
232 0 for (0..$self->{total_layers}){$self->extend_layer($_,$layers->[$_])}
233 0 $self->{layers} = $layers;
234 0 for (0..$self->{total_layers}){$self->{total_nodes}+= $self->{layers}->[$_]}
235 }
236 } else {
237 0 $self->{error} = "extend(): Invalid argument type.\n";
238 0 return undef;
239 }
240 0 return 1;
241 }
242
243 # See POD for usage
244 0 ▶ sub extend_layer {
Subroutine extend_layer: not called CC=7 SCAR=40.3
Pod documented
245 0 my $self = shift;
246 0 ▶ my $layer = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
247 0 my $specs = shift;
248 0 ▶ if(!$specs) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($specs) 0 0 0
249 0 $self->{error} = "extend_layer(): You must provide specs to extend layer $layer with.\n";
250 0 return undef;
251 }
252 0 ▶ if(ref($specs) eq "HASH") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $specs eq 'HASH') { } 0 0 0
253 0 ▶ $self->activation($layer,$specs->{activation}) if($specs->{activation});
Branch: 1 branch
BranchTrueFalseTotal
if $specs->{"activation"} 0 0 0
254 0 ▶ $self->threshold($layer,$specs->{threshold}) if($specs->{threshold});
Branch: 1 branch
BranchTrueFalseTotal
if $specs->{"threshold"} 0 0 0
255 0 ▶ $self->mean($layer,$specs->{mean}) if($specs->{mean});
Branch: 1 branch
BranchTrueFalseTotal
if $specs->{"mean"} 0 0 0
256 0 return $self->add_nodes($layer,$specs->{nodes});
257 } else {
258 0 return $self->add_nodes($layer,$specs);
259 }
260 0 return 1;
261 }
262
263 # Pseudo-internal usage
264 0 ▶ sub add_nodes {
Subroutine add_nodes: not called CC=5 SCAR=31.4
Pod documented
265 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
266 0 my $self = shift;
267 0 my $layer = shift;
268 0 my $nodes = shift;
269 0 my $n = 0;
270 0 my $more = $nodes - $self->{layers}->[$layer] - 1;
271 0 d("Checking on extending layer $layer to $nodes nodes (check:$self->{layers}->[$layer]).\n",9);
272 0 ▶ return 1 if ($nodes == $self->{layers}->[$layer]);
Branch: 1 branch
BranchTrueFalseTotal
if $nodes == $self->{"layers"}[$layer] 0 0 0
273 0 ▶ if ($self->{layers}->[$layer]>$nodes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"layers"}[$layer] > $nodes) 0 0 0
274 0 $self->{error} = "add_nodes(): I cannot remove nodes from the network with this version of my module. You must create a new network to remove nodes.\n";
275 0 return undef;
276 }
277 0 d("Extending layer $layer by $more.\n",9);
278 0 for (0..$more){$self->{mesh}->[$#{$self->{mesh}}+1]=AI::NeuralNet::Mesh::node->new($self)}
279 0 for(0..$layer-2){$n+=$self->{layers}->[$_]}
280 0 $self->_c($n,$n+$self->{layers}->[$layer-1],$#{$self->{mesh}}-$more+1,$#{$self->{mesh}});
281 0 $self->_c($#{$self->{mesh}}-$more+1,$#{$self->{mesh}},$n+$self->{layers}->[$layer],$n+$self->{layers}->[$layer]+$self->{layers}->[$layer+1]);
282 }
283
284
285 # See POD for usage
286 42 ▶ sub run {
Subroutine run: called CC=6 SCAR=19.2
Pod documented
287 42 my $self = shift;
288 42 my $inputs = shift;
289 42 my $const = $self->{const};
290 #my $start = new Benchmark;
291 42 ▶ $inputs = $self->crunch($inputs) if($inputs == 0);
Branch: 1 branch
BranchTrueFalseTotal
if $inputs == 0 0 42 42
292 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
293 42 for my $x (0..$#{$inputs}) {
294 84 ▶ last if($x>$self->{inputs});
Branch: 1 branch
BranchTrueFalseTotal
if $x > $self->{"inputs"} 0 84 84
295 84 d("inputing $inputs->[$x] at index $x with ID $self->{input}->{IDs}->[$x].\n",1);
296 84 $self->{mesh}->[$x]->input($inputs->[$x]+$const,$self->{input}->{IDs}->[$x]);
297 }
298 42 ▶ if($#{$inputs}<$self->{inputs}-1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($#{$inputs;} < $self->{"inputs"} - 1) 0 42 42
299 0 for my $x ($#{$inputs}+1..$self->{inputs}-1) {
300 0 d("inputing 1 at index $x with ID $self->{input}->{IDs}->[$x].\n",1);
301 0 $self->{mesh}->[$x]->input(1,$self->{input}->{IDs}->[$x]);
302 }
303 }
304 #$self->{benchmark} = timestr(timediff(new Benchmark, $start));
305 42 return $self->{output}->get_outputs();
306 }
307
308 # See POD for usage
309 0 ▶ sub run_uc {
Subroutine run_uc: not called CC=1 SCAR=6.9
Pod documented
310 0 $_[0]->uncrunch(run(@_));
311 }
312
313 # See POD for usage
314 7 ▶ sub learn {
Subroutine learn: called CC=23 SCAR=33.8
Pod documented
315 7 my $self = shift;
316 7 my $inputs = shift; # input set
317 7 my $outputs = shift; # target outputs
318 7 my %args = @_; # get args into hash
319 7 ▶ my $inc = $args{inc} || 0.002; # learning gradient
Condition50%1/2
$args{'inc'} || 0.002
l!l
07
MC/DC0%0/1
$args{'inc'} || 0.002
$args{'inc'}
Truth table50%1/2
A
A= $args{'inc'}
Aresult
11
00
320 7 ▶ my $max = $args{max} || 1024; # max iteterations
Condition50%1/2
$args{'max'} || 1024
l!l
07
MC/DC0%0/1
$args{'max'} || 1024
$args{'max'}
Truth table50%1/2
A
A= $args{'max'}
Aresult
11
00
321 7 ▶ my $degrade = $args{degrade} || 0; # enable gradient degrading
Condition50%1/2
$args{'degrade'} || 0
l!l
70
MC/DC0%0/1
$args{'degrade'} || 0
$args{'degrade'}
Truth table50%1/2
A
A= $args{'degrade'}
Aresult
11
00
322 7 ▶ my $error = ($args{error}>-1 && defined $args{error}) ? $args{error} : -1;
Branch: 1 branch
BranchTrueFalseTotal
$args{'error'} > -1 && defined $args{'error'} ? : 0 7 7
Condition33%1/3
$args{"error"} > -1 and defined $args{"error"}
!ll&&!rl&&r
070
MC/DC0%0/2
$args{"error"} > -1 and defined $args{"error"}
$args{"error"} > -1 defined $args{"error"}
Truth table33%1/3
A and B
A= $args{"error"} > -1B= defined $args{"error"}
ABresult
0X0
100
111
323 7 my $dinc = 0.0002; # amount to adjust gradient by
324 7 my $diff = 100; # error magin between results
325 7 my $start = new Benchmark;
326 7 ▶ $inputs = $self->crunch($inputs) if($inputs == 0);
Branch: 1 branch
BranchTrueFalseTotal
if $inputs == 0 0 7 7
327 7 ▶ $outputs = $self->crunch($outputs) if($outputs == 0);
Branch: 1 branch
BranchTrueFalseTotal
if $outputs == 0 0 7 7
328 7 my ($flag,$ldiff,$cdiff,$_mi,$loop,$y);
329 7 ▶ while(!$flag && ($max ? $loop<$max : 1)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $flag and $max ? $loop < $max : 1) 39 7 46
$max ? : 39 0 39
Condition66%2/3
not $flag and $max ? $loop < $max : 1
!ll&&!rl&&r
7039
MC/DC50%1/2
not $flag and $max ? $loop < $max : 1
not $flag $max ? $loop < $max : 1
Truth table66%2/3
not(A) and B
A= not $flagB= $max ? $loop < $max : 1
ABresult
0X0
100
111
330 39 my $b = new Benchmark;
331 39 my $got = $self->run($inputs);
332 39 $diff = pdiff($got,$outputs);
333 39 $flag = 1;
334
335 39 ▶ if(($error>-1 ? $diff<$error : 0) || !$diff) {
Branch: 2 branches
BranchTrueFalseTotal
if ($error > -1 ? $diff < $error : 0 or not $diff) 0 39 39
$error > -1 ? : 0 39 39
Condition33%1/3
$error > -1 ? $diff < $error : 0 or not $diff
l!l&&r!l&&!r
0039
MC/DC0%0/2
$error > -1 ? $diff < $error : 0 or not $diff
$error > -1 ? $diff < $error : 0 not $diff
Truth table33%1/3
A or not(B)
A= $error > -1 ? $diff < $error : 0B= not $diff
ABresult
1X1
011
000
336 0 $flag=1;
337 0 last;
338 }
339
340 39 ▶ if($degrade) {
Branch: 1 branch
BranchTrueFalseTotal
if ($degrade) 39 0 39
341 39 $inc -= ($dinc*$diff);
342
343 39 ▶ if($diff eq $ldiff) {
Branch: 1 branch
BranchTrueFalseTotal
if ($diff eq $ldiff) { } 11 28 39
344 11 $cdiff++;
345 11 $inc += ($dinc*$diff)+($dinc*$cdiff*10);
346 } else {
347 28 $cdiff=0;
348 }
349 39 $ldiff = $diff;
350 }
351
352 39 for my $x (0..$self->{outputs}-1) {
353 39 my $a = $got->[$x];
354 39 my $b = $outputs->[$x];
355 39 d("got: $a, wanted: $b\n",2);
356 39 ▶ if ($a != $b) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a != $b) 32 7 39
357 32 $flag = 0;
358 32 $y = $self->{total_nodes}-$self->{outputs}+$x;
359 32 ▶ $self->{mesh}->[$y]->adjust_weight(($a<$b?1:-1)*$inc,$b);
Branch: 1 branch
BranchTrueFalseTotal
$a < $b ? : 8 24 32
360 }
361 }
362
363 39 $loop++;
364
365 39 d("===============================Loop: [$loop]===================================\n",4);
366 39 d("Current Error: $diff\tCurrent Increment: $inc\n",4);
367 39 d("Benchmark: ".timestr(timediff(new Benchmark,$b))."\n",4);
368 39 d("============================Results, [$loop]===================================\n",4);
369 39 d("Actual: ",4);
370 39 ▶ join_cols($got,($self->{col_width})?$self->{col_width}:5) if(d()==4);
Branch: 2 branches
BranchTrueFalseTotal
if d() == 4 0 39 39
$self->{'col_width'} ? : 0 0 0
371 39 d("Target: ",4);
372 39 ▶ join_cols($outputs,($self->{col_width})?$self->{col_width}:5) if(d()==4);
Branch: 2 branches
BranchTrueFalseTotal
if d() == 4 0 39 39
$self->{'col_width'} ? : 0 0 0
373 39 d("\n",4);
374 39 d('.',12);
375 39 d('['.join(',',@{$got})."-".join(',',@{$outputs}).']',13);
376 }
377 7 my $str = "Learning took $loop loops and ".timestr(timediff(new Benchmark,$start))."\n";
378 7 d($str,3); $self->{benchmark} = "$loop loops and ".timestr(timediff(new Benchmark,$start))."\n";
379 7 return $str;
380 }
381
382
383 # See POD for usage
384 1 ▶ sub learn_set {
Subroutine learn_set: called CC=6 SCAR=18.3
Pod documented
385 1 my $self = shift;
386 1 my $data = shift;
387 1 my %args = @_;
388 1 my $len = $#{$data}/2;
389 1 my $inc = $args{inc};
390 1 my $max = $args{max};
391 1 my $error = $args{error};
392 1 my $degrade = $args{degrade};
393 1 ▶ my $p = (defined $args{flag}) ?$args{flag} :1;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'flag'} ? : 0 1 1
394 1 ▶ my $row = (defined $args{row}) ?$args{row}+1:1;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'row'} ? : 0 1 1
395 1 ▶ my $leave = (defined $args{leave})?$args{leave}:0;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'leave'} ? : 0 1 1
396 1 for my $x (0..$len-$leave) {
397 7 d("Learning set $x...\n",4);
398 7 my $str = $self->learn( $data->[$x*2],
399 $data->[$x*2+1],
400 inc=>$inc,
401 max=>$max,
402 error=>$error,
403 degrade=>$degrade);
404 }
405
406 1 ▶ if ($p) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p) { } 1 0 1
407 1 return pdiff($data->[$row],$self->run($data->[$row-1]));
408 } else {
409 0 return $data->[$row]->[0]-$self->run($data->[$row-1])->[0];
410 }
411 }
412
413 # See POD for usage
414 0 ▶ sub run_set {
Subroutine run_set: not called CC=3 SCAR=24.8
Pod documented
415 0 my $self = shift;
416 0 my $data = shift;
417 0 my $len = $#{$data}/2;
418 0 my (@results,$res);
419 0 for my $x (0..$len) {
420 0 $res = $self->run($data->[$x*2]);
421 0 for(0..$#{$res}){$results[$x]->[$_]=$res->[$_]}
422 0 d("Running set $x [$res->[0]]...\r",4);
423 }
424 0 return \@results;
425 }
426
427 #
428 # Loads a CSV-like dataset from disk
429 #
430 # Usage:
431 # my $set = $set->load_set($file, $column, $seperator);
432 #
433 # Returns a data set of the same format as required by the
434 # learn_set() method. $file is the disk file to load set from.
435 # $column an optional variable specifying the column in the
436 # data set to use as the class attribute. $class defaults to 0.
437 # $seperator is an optional variable specifying the seperator
438 # character between values. $seperator defaults to ',' (a single comma).
439 # NOTE: This does not handle quoted fields, or any other record
440 # seperator other than "\n".
441 #
442 0 ▶ sub load_set {
Subroutine load_set: not called CC=7 SCAR=40.3
Pod documented
443 0 my $self = shift;
444 0 my $file = shift;
445 0 ▶ my $attr = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
446 0 ▶ my $sep = shift || ',';
Condition0%0/2
shift() || ','
l!l
00
MC/DC0%0/1
shift() || ','
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
447 0 my $data = [];
448 0 open(FILE, $file);
449 0 my @lines = <FILE>;
450 0 close(FILE);
451 0 for my $x (0..$#lines) {
452 0 chomp($lines[$x]);
453 0 my @tmp = split /$sep/, $lines[$x];
454 0 my $c=0;
455 0 for(0..$#tmp){
456 0 ▶ $tmp[$_]=$self->crunch($tmp[$_])->[0] if($tmp[$_]=~/[AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz]/);
Branch: 1 branch
BranchTrueFalseTotal
if $tmp[$_] =~ /[AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz]/ 0 0 0
457 0 ▶ if($_!=$attr){$data->[$x*2]->[$c]=$tmp[$c];$c++}
Branch: 1 branch
BranchTrueFalseTotal
if ($_ != $attr) 0 0 0
458 };
459 0 d("Loaded line $x, [@tmp] \r",4);
460 0 $data->[$x*2+1]=[$tmp[$attr]];
461 }
462 0 return $data;
463 }
464
465 # See POD for usage
466 0 ▶ sub get_outs {
Subroutine get_outs: not called CC=2 SCAR=17.9
Pod documented
467 0 my $self = shift;
468 0 my $data = shift;
469 0 my $len = $#{$data}/2;
470 0 my $outs = [];
471 0 for my $x (0..$len) {
472 0 $outs->[$x] = $data->[$x*2+1];
473 }
474 0 return $outs;
475 }
476
477 # Save entire network state to disk.
478 2 ▶ sub save {
Subroutine save: called CC=8 SCAR=20.9
Pod documented
479 2 my $self = shift;
480 2 my $file = shift;
481 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
482
483 2 open(FILE,">$file");
484
485 2 print FILE "header=$AI::NeuralNet::Mesh::ID\n";
486
487 2 print FILE "total_layers=$self->{total_layers}\n";
488 2 print FILE "total_nodes=$self->{total_nodes}\n";
489 2 print FILE "nodes=$self->{nodes}\n";
490 2 print FILE "inputs=$self->{inputs}\n";
491 2 print FILE "outputs=$self->{outputs}\n";
492 2 ▶ print FILE "layers=",(($self->{layers})?join(',',@{$self->{layers}}):''),"\n";
Branch: 1 branch
BranchTrueFalseTotal
$self->{'layers'} ? : 2 0 2
493
494 2 print FILE "rand=$self->{random}\n";
495 2 print FILE "const=$self->{const}\n";
496 2 print FILE "cw=$self->{col_width}\n";
497 2 print FILE "crunch=$self->{_crunched}->{_length}\n";
498 2 print FILE "rA=$self->{rA}\n";
499 2 print FILE "rB=$self->{rB}\n";
500 2 print FILE "rS=$self->{rS}\n";
501 2 ▶ print FILE "rRef=",(($self->{rRef})?join(',',@{$self->{rRef}}):''),"\n";
Branch: 1 branch
BranchTrueFalseTotal
$self->{'rRef'} ? : 1 1 2
502
503 2 for my $a (0..$self->{_crunched}->{_length}-1) {
504 0 print FILE "c$a=$self->{_crunched}->{list}->[$a]\n";
505 }
506
507 2 my $n = 0;
508 2 for my $x (0..$self->{total_layers}) {
509 6 for my $y (0..$self->{layers}->[$x]-1) {
510 10 my $w='';
511 10 for my $z (0..$self->{layers}->[$x-1]-1) {
512 16 $w.="$self->{mesh}->[$n]->{_inputs}->[$z]->{weight},";
513 }
514 10 print FILE "n$n=$w$self->{mesh}->[$n]->{activation},$self->{mesh}->[$n]->{threshold},$self->{mesh}->[$n]->{mean}\n";
515 10 $n++;
516 }
517 }
518
519 2 close(FILE);
520
521 2 ▶ if(!(-f $file)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file) 0 2 2
522 0 $self->{error} = "Error writing to \"$file\".";
523 0 return undef;
524 }
525
526 2 return $self;
527 }
528
529 # Load entire network state from disk.
530 1 ▶ sub load {
Subroutine load: called CC=10 SCAR=24.3
Pod documented
531 1 my $self = shift;
532 1 my $file = shift;
533 1 my $load_flag = shift;
534
535 1 my @lines;
536
537 1 ▶ if(-f $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $file) { } 1 0 1
538 1 open(FILE,"$file");
539 1 @lines=<FILE>;
540 1 close(FILE);
541 } else {
542 0 @lines=split /\n/, $file;
543 }
544
545 1 my %db;
546 1 for my $line (@lines) {
547 20 chomp($line);
548 20 my ($a,$b) = split /=/, $line;
549 20 $db{$a}=$b;
550 }
551
552 1 ▶ if(!$db{"header"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($db{"header"}) 0 1 1
553 0 $self->{error} = "Invalid format.";
554 0 return undef;
555 }
556
557 1 ▶ return $self->load_old($file) if($self->version($db{"header"})<0.21);
Branch: 1 branch
BranchTrueFalseTotal
if $self->version($db{"header"}) < "0.21" 0 1 1
558
559 1 ▶ if($load_flag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($load_flag) { } 1 0 1
560 1 undef $self;
561 1 $self = AI::NeuralNet::Mesh->new([split(',',$db{layers})]);
562 } else {
563 0 $self->{inputs} = $db{inputs};
564 0 $self->{nodes} = $db{nodes};
565 0 $self->{outputs} = $db{outputs};
566 0 $self->{layers} = [split(',',$db{layers})];
567 0 $self->{total_layers} = $db{total_layers};
568 0 $self->{total_nodes} = $db{total_nodes};
569 }
570
571 # Load variables
572 1 $self->{random} = $db{"rand"};
573 1 $self->{const} = $db{"const"};
574 1 $self->{col_width} = $db{"cw"};
575 1 $self->{rA} = $db{"rA"};
576 1 $self->{rB} = $db{"rB"};
577 1 $self->{rS} = $db{"rS"};
578 1 $self->{rRef} = [split /\,/, $db{"rRef"}];
579
580 1 $self->{_crunched}->{_length} = $db{"crunch"};
581
582 1 for my $a (0..$self->{_crunched}->{_length}-1) {
583 0 $self->{_crunched}->{list}->[$a] = $db{"c$a"};
584 }
585
586 1 $self->_init();
587
588 1 my $n = 0;
589 1 for my $x (0..$self->{total_layers}) {
590 3 for my $y (0..$self->{layers}->[$x]-1) {
591 5 my @l = split /\,/, $db{"n$n"};
592 5 for my $z (0..$self->{layers}->[$x-1]-1) {
593 8 $self->{mesh}->[$n]->{_inputs}->[$z]->{weight} = $l[$z];
594 }
595 5 my $z = $self->{layers}->[$x-1];
596 5 $self->{mesh}->[$n]->{activation} = $l[$z];
597 5 $self->{mesh}->[$n]->{threshold} = $l[$z+1];
598 5 $self->{mesh}->[$n]->{mean} = $l[$z+2];
599 5 $n++;
600 }
601 }
602
603 1 return $self;
604 }
605
606 # Load entire network state from disk.
607 0 ▶ sub load_old {
Subroutine load_old: not called CC=10 SCAR=47.0
Pod undocumented
608 0 my $self = shift;
609 0 my $file = shift;
610 0 my $load_flag = shift;
611
612 0 ▶ if(!(-f $file)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file) 0 0 0
613 0 $self->{error} = "File \"$file\" does not exist.";
614 0 return undef;
615 }
616
617 0 open(FILE,"$file");
618 0 my @lines=<FILE>;
619 0 close(FILE);
620
621 0 my %db;
622 0 for my $line (@lines) {
623 0 chomp($line);
624 0 my ($a,$b) = split /=/, $line;
625 0 $db{$a}=$b;
626 }
627
628 0 ▶ if(!$db{"header"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($db{"header"}) 0 0 0
629 0 $self->{error} = "Invalid format.";
630 0 return undef;
631 }
632
633 0 ▶ if($load_flag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($load_flag) { } 0 0 0
634 0 undef $self;
635
636 # Create new network
637 $self = AI::NeuralNet::Mesh->new($db{"layers"},
638 $db{"nodes"},
639 0 $db{"outputs"});
640 } else {
641 0 $self->{total_layers} = $db{"layers"};
642 0 $self->{nodes} = $db{"nodes"};
643 0 $self->{outputs} = $db{"outputs"};
644 0 $self->{inputs} = $db{"nodes"};
645 #$self->{total_nodes} = $db{"total"};
646 }
647
648 # Load variables
649 0 $self->{random} = $db{"rand"};
650 0 $self->{const} = $db{"const"};
651 0 $self->{col_width} = $db{"cw"};
652 0 $self->{rA} = $db{"rA"};
653 0 $self->{rB} = $db{"rB"};
654 0 $self->{rS} = $db{"rS"};
655 0 $self->{rRef} = [split /\,/, $db{"rRef"}];
656
657 0 $self->{_crunched}->{_length} = $db{"crunch"};
658
659 0 for my $a (0..$self->{_crunched}->{_length}-1) {
660 0 $self->{_crunched}->{list}->[$a] = $db{"c$a"};
661 }
662
663
664 0 $self->_init();
665
666 0 my $nodes = $self->{nodes};
667 0 my $outputs = $self->{outputs};
668 0 my $tmp = $self->{total_nodes};
669 0 my $div = intr($nodes/$outputs);
670
671 # Load input and hidden
672 0 for my $a (0..$tmp-1) {
673 0 my @l = split /\,/, $db{"n$a"};
674 0 for my $b (0..$nodes-1) {
675 0 $self->{mesh}->[$a]->{_inputs}->[$b]->{weight} = $l[$b];
676 }
677 }
678
679 # Load output layer
680 0 for my $x (0..$outputs-1) {
681 0 my @l = split /\,/, $db{"n".($tmp+$x)};
682 0 for my $y (0..$div-1) {
683 0 $self->{mesh}->[$tmp+$x]->{_inputs}->[$y]->{weight} = $l[$y];
684 }
685 }
686
687 0 return $self;
688 }
689
690 # Dumps the complete weight matrix of the network to STDIO
691 0 ▶ sub show {
Subroutine show: not called CC=4 SCAR=23.2
Pod documented
692 0 my $self = shift;
693 0 my $n = 0;
694 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
695 0 for my $x (0..$self->{total_layers}) {
696 0 for my $y (0..$self->{layers}->[$x]-1) {
697 0 for my $z (0..$self->{layers}->[$x-1]-1) {
698 0 print "$self->{mesh}->[$n]->{_inputs}->[$z]->{weight},";
699 }
700 0 $n++;
701 }
702 0 print "\n";
703 }
704 }
705
706 # Set the activation type of a specific layer.
707 # usage: $net->activation($layer,$type);
708 # $type can be: "linear", "sigmoid", "sigmoid_2".
709 # You can use "sigmoid_1" as a synonym to "sigmoid".
710 # Type can also be a CODE ref, ( ref($type) eq "CODE" ).
711 # If $type is a CODE ref, then the function is called in this form:
712 # $output = &$type($sum_of_inputs,$self);
713 # The code ref then has access to all the data in that node (thru the
714 # blessed refrence $self) and is expected to return the value to be used
715 # as the output for that node. The sum of all the inputs to that node
716 # is already summed and passed as the first argument.
717 0 ▶ sub activation {
Subroutine activation: not called CC=5 SCAR=28.8
Pod documented
718 0 my $self = shift;
719 0 ▶ my $layer = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
720 0 ▶ my $value = shift || 'linear';
Condition0%0/2
shift() || 'linear'
l!l
00
MC/DC0%0/1
shift() || 'linear'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
721 0 my $n = 0;
722 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
723 0 for(0..$layer-1){$n+=$self->{layers}->[$_]}
724 0 for($n..$n+$self->{layers}->[$layer]-1) {
725 0 $self->{mesh}->[$_]->{activation} = $value;
726 }
727 }
728
729 # Applies an activation type to a specific node
730 0 ▶ sub node_activation {
Subroutine node_activation: not called CC=5 SCAR=29.4
Pod documented
731 0 my $self = shift;
732 0 ▶ my $layer = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
733 0 ▶ my $node = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
734 0 ▶ my $value = shift || 'linear';
Condition0%0/2
shift() || 'linear'
l!l
00
MC/DC0%0/1
shift() || 'linear'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
735 0 my $n = 0;
736 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
737 0 for(0..$layer-1){$n+=$self->{layers}->[$_]}
738 0 $self->{mesh}->[$n+$node]->{activation} = $value;
739 }
740
741 # Set the activation threshold for a specific layer.
742 # Only applicable if that layer uses "sigmoid" or "sigmoid_2"
743 # usage: $net->threshold($layer,$threshold);
744 0 ▶ sub threshold {
Subroutine threshold: not called CC=5 SCAR=28.8
Pod documented
745 0 my $self = shift;
746 0 ▶ my $layer = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
747 0 ▶ my $value = shift || 0.5;
Condition0%0/2
shift() || 0.5
l!l
00
MC/DC0%0/1
shift() || 0.5
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
748 0 my $n = 0;
749 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
750 0 for(0..$layer-1){$n+=$self->{layers}->[$_]}
751 0 for($n..$n+$self->{layers}->[$layer]-1) {
752 0 $self->{mesh}->[$_]->{threshold} = $value;
753 }
754 }
755
756 # Applies a threshold to a specific node
757 0 ▶ sub node_threshold {
Subroutine node_threshold: not called CC=5 SCAR=29.4
Pod documented
758 0 my $self = shift;
759 0 ▶ my $layer = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
760 0 ▶ my $node = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
761 0 ▶ my $value = shift || 0.5;
Condition0%0/2
shift() || 0.5
l!l
00
MC/DC0%0/1
shift() || 0.5
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
762 0 my $n = 0;
763 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
764 0 for(0..$layer-1){$n+=$self->{layers}->[$_]}
765 0 $self->{mesh}->[$n+$node]->{threshold} = $value;
766 }
767
768 # Set mean (avg.) flag for a layer.
769 # usage: $net->mean($layer,$flag);
770 # If $flag is true, it enables finding the mean for that layer,
771 # If $flag is false, disables mean.
772 0 ▶ sub mean {
Subroutine mean: not called CC=5 SCAR=28.8
Pod undocumented
773 0 my $self = shift;
774 0 ▶ my $layer = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
775 0 ▶ my $value = shift || 0;
Condition0%0/2
shift() || 0
l!l
00
MC/DC0%0/1
shift() || 0
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
776 0 my $n = 0;
777 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
778 0 for(0..$layer-1){$n+=$self->{layers}->[$_]}
779 0 for($n..$n+$self->{layers}->[$layer]-1) {
780 0 $self->{mesh}->[$_]->{mean} = $value;
781 }
782 }
783
784
785 # Returns a pcx object
786 0 ▶ sub load_pcx {
Subroutine load_pcx: not called CC=2 SCAR=17.9
Pod documented
787 0 my $self = shift;
788 0 my $file = shift;
789 0 eval('use PCX::Loader');
790 0 ▶ if(@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 0 0
791 0 $self->{error}="Cannot load PCX::Loader module: @_";
792 0 return undef;
793 }
794 0 return PCX::Loader->new($self,$file);
795 }
796
797 # Crunch a string of words into a map
798 0 ▶ sub crunch {
Subroutine crunch: not called CC=3 SCAR=24.8
Pod documented
799 0 my $self = shift;
800 0 my @ws = split(/[\s\t]/,shift);
801 0 my (@map,$ic);
802 0 for my $a (0..$#ws) {
803 0 $ic=$self->crunched($ws[$a]);
804 0 ▶ if(!defined $ic) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $ic) { } 0 0 0
805 0 $self->{_crunched}->{list}->[$self->{_crunched}->{_length}++]=$ws[$a];
806 0 $map[$a]=$self->{_crunched}->{_length};
807 } else {
808 0 $map[$a]=$ic;
809 }
810 }
811 0 return \@map;
812 }
813
814 # Finds if a word has been crunched.
815 # Returns undef on failure, word index for success.
816 0 ▶ sub crunched {
Subroutine crunched: not called CC=3 SCAR=24.8
Pod documented
817 0 my $self = shift;
818 0 for my $a (0..$self->{_crunched}->{_length}-1) {
819 0 ▶ return $a+1 if($self->{_crunched}->{list}->[$a] eq $_[0]);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_crunched"}{"list"}[$a] eq $_[0] 0 0 0
820 }
821 0 $self->{error} = "Word \"$_[0]\" not found.";
822 0 return undef;
823 }
824
825 # Alias for crunched(), above
826 0 ▶ sub word { crunched(@_) }
Subroutine word: not called CC=1 SCAR=6.9
Pod documented
827
828 # Uncrunches a map (array ref) into an array of words (not an array ref)
829 # and returns array
830 0 ▶ sub uncrunch {
Subroutine uncrunch: not called CC=2 SCAR=17.9
Pod documented
831 0 my $self = shift;
832 0 my $map = shift;
833 0 my ($c,$el,$x);
834 0 foreach $el (@{$map}) {
835 0 $c .= $self->{_crunched}->{list}->[$el-1].' ';
836 }
837 0 return $c;
838 }
839
840 # Sets/gets randomness facter in the network. Setting a value of 0
841 # disables random factors.
842 0 ▶ sub random {
Subroutine random: not called CC=2 SCAR=17.9
Pod documented
843 0 my $self = shift;
844 0 my $rand = shift;
845 0 ▶ return $self->{random} if(!(defined $rand));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rand 0 0 0
846 0 $self->{random} = $rand;
847 }
848
849 # Sets/gets column width for printing lists in debug modes 1,3, and 4.
850 0 ▶ sub col_width {
Subroutine col_width: not called CC=2 SCAR=17.9
Pod documented
851 0 my $self = shift;
852 0 my $width = shift;
853 0 ▶ return $self->{col_width} if(!$width);
Branch: 1 branch
BranchTrueFalseTotal
unless $width 0 0 0
854 0 $self->{col_width} = $width;
855 }
856
857 # Sets/gets run const. facter in the network. Setting a value of 0
858 # disables run const. factor.
859 0 ▶ sub const {
Subroutine const: not called CC=2 SCAR=17.9
Pod documented
860 0 my $self = shift;
861 0 my $const = shift;
862 0 ▶ return $self->{const} if(!(defined $const));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $const 0 0 0
863 0 $self->{const} = $const;
864 }
865
866 # Return benchmark time from last learn() operation.
867 0 ▶ sub benchmark {
Subroutine benchmark: not called CC=1 SCAR=6.9
Pod documented
868 0 shift->{benchmarked};
869 }
870
871 # Same as benchmark()
872 0 ▶ sub benchmarked {
Subroutine benchmarked: not called CC=1 SCAR=6.9
Pod documented
873 0 benchmark(shift);
874 }
875
876 # Return the last error in the mesh, or undef if no error.
877 0 ▶ sub error {
Subroutine error: not called CC=2 SCAR=17.9
Pod documented
878 0 my $self = shift;
879 0 ▶ return undef if !$self->{error};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"error"} 0 0 0
880 0 chomp($self->{error});
881 0 return $self->{error}."\n";
882 }
883
884 # Used to format array ref into columns
885 # Usage:
886 # join_cols(\@array,$row_length_in_elements,$high_state_character,$low_state_character);
887 # Can also be called as method of your neural net.
888 # If $high_state_character is null, prints actual numerical values of each element.
889 0 ▶ sub join_cols {
Subroutine join_cols: not called CC=6 SCAR=34.4
Pod documented
890 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
891 0 ▶ shift if(substr($_[0],0,4) eq 'AI::');
Branch: 1 branch
BranchTrueFalseTotal
if substr($_[0], 0, 4) eq "AI::" 0 0 0
892 0 my $map = shift;
893 0 my $break = shift;
894 0 my $a = shift;
895 0 my $b = shift;
896 0 my $x;
897 0 foreach my $el (@{$map}) {
898 0 ▶ my $str = ((int($el))?$a:$b);
Branch: 1 branch
BranchTrueFalseTotal
int $el ? : 0 0 0
899 0 ▶ $str=$el."\0" if(!$a);
Branch: 1 branch
BranchTrueFalseTotal
unless $a 0 0 0
900 0 print $str; $x++;
901 0 ▶ if($x>$break-1) { print "\n"; $x=0; }
Branch: 1 branch
BranchTrueFalseTotal
if ($x > $break - 1) 0 0 0
902 }
903 0 print "\n";
904 }
905
906 # Returns percentage difference between all elements of two
907 # array refs of exact same length (in elements).
908 # Now calculates actual difference in numerical value.
909 40 ▶ sub pdiff {
Subroutine pdiff: called CC=7 SCAR=19.5
Pod documented
910 1 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
911 40 ▶ shift if(substr($_[0],0,4) eq 'AI::');
Branch: 1 branch
BranchTrueFalseTotal
if substr($_[0], 0, 4) eq "AI::" 0 40 40
912 40 my $a1 = shift;
913 40 my $a2 = shift;
914 40 my $a1s = $#{$a1};
915 40 my $a2s = $#{$a2};
916 40 my ($a,$b,$diff,$t);
917 40 $diff=0;
918 40 for my $x (0..$a1s) {
919 40 $a = $a1->[$x]; $b = $a2->[$x];
920 40 ▶ if($a!=$b) {
Branch: 1 branch
BranchTrueFalseTotal
if ($a != $b) 32 8 40
921 32 ▶ if($a<$b){$t=$a;$a=$b;$b=$t;}
Branch: 1 branch
BranchTrueFalseTotal
if ($a < $b) 8 24 32
922 32 ▶ $a=1 if(!$a); $diff+=(($a-$b)/$a)*100;
Branch: 1 branch
BranchTrueFalseTotal
unless $a 0 32 32
923 }
924 }
925 40 ▶ $a1s = 1 if(!$a1s);
Branch: 1 branch
BranchTrueFalseTotal
unless $a1s 40 0 40
926 40 return sprintf("%.10f",($diff/$a1s));
927 }
928
929 # Returns $fa as a percentage of $fb
930 0 ▶ sub p {
Subroutine p: not called CC=2 SCAR=17.9
Pod documented
931 0 ▶ shift if(substr($_[0],0,4) eq 'AI::');
Branch: 1 branch
BranchTrueFalseTotal
if substr($_[0], 0, 4) eq "AI::" 0 0 0
932 0 my ($fa,$fb)=(shift,shift);
933 0 sprintf("%.3f",$fa/$fb*100); #((($fb-$fa)*((($fb-$fa)<0)?-1:1))/$fa)*100
934 }
935
936 # Returns the index of the element in array REF passed with the highest
937 # comparative value
938 0 ▶ sub high {
Subroutine high: not called CC=5 SCAR=34.0
Pod documented
939 0 ▶ shift if(substr($_[0],0,4) eq 'AI::');
Branch: 1 branch
BranchTrueFalseTotal
if substr($_[0], 0, 4) eq "AI::" 0 0 0
940 0 my $ref1 = shift; my ($el,$len,$tmp); $tmp=0;
941 0 foreach $el (@{$ref1}) { $len++ }
942 0 ▶ for my $x (0..$len-1) { $tmp = $x if($ref1->[$x] > $ref1->[$tmp]) }
Branch: 1 branch
BranchTrueFalseTotal
if $ref1->[$x] > $ref1->[$tmp] 0 0 0
943 0 return $tmp;
944 }
945
946 # Returns the index of the element in array REF passed with the lowest
947 # comparative value
948 0 ▶ sub low {
Subroutine low: not called CC=5 SCAR=34.0
Pod documented
949 0 ▶ shift if(substr($_[0],0,4) eq 'AI::');
Branch: 1 branch
BranchTrueFalseTotal
if substr($_[0], 0, 4) eq "AI::" 0 0 0
950 0 my $ref1 = shift; my ($el,$len,$tmp); $tmp=0;
951 0 foreach $el (@{$ref1}) { $len++ }
952 0 ▶ for my $x (0..$len-1) { $tmp = $x if($ref1->[$x] < $ref1->[$tmp]) }
Branch: 1 branch
BranchTrueFalseTotal
if $ref1->[$x] < $ref1->[$tmp] 0 0 0
953 0 return $tmp;
954 }
955
956 # Following is a collection of a few nifty custom activation functions.
957 # range() is exported by default, the rest you can get with:
958 # use AI::NeuralNet::Mesh ':acts'
959 # The ':all' tag also gets these into your namespace.
960
961 #
962 # range() returns a closure limiting the output
963 # of that node to a specified set of values.
964 # Good for output layers.
965 #
966 # usage example:
967 # $net->activation(4,range(0..5));
968 # or:
969 # ..
970 # {
971 # nodes => 1,
972 # activation => range 5..2
973 # }
974 # ..
975 # You can also pass an array containing the range
976 # values (not array ref), or you can pass a comma-
977 # seperated list of values as parameters:
978 #
979 # $net->activation(4,range(@numbers));
980 # $net->activation(4,range(6,15,26,106,28,3));
981 #
982 # Note: when using a range() activatior, train the
983 # net TWICE on the data set, because the first time
984 # the range() function searches for the top value in
985 # the inputs, and therefore, results could flucuate.
986 # The second learning cycle guarantees more accuracy.
987 #
988 0 ▶ sub range {
Subroutine range: not called CC=1 SCAR=6.9
Pod documented
989 0 my @r=@_;
990 0 ▶ sub{$_[1]->{t}=$_[0]if($_[0]>$_[1]->{t});$r[intr($_[0]/$_[1]->{t}*$#r)]}
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] > $_[1]{"t"} 0 0 0
991 0 }
992
993 #
994 # ramp() preforms smooth ramp activation between 0 and 1 if $r is 1,
995 # or between -1 and 1 if $r is 2. $r defaults to 1, as you can see.
996 #
997 # Note: when using a ramp() activatior, train the
998 # net at least TWICE on the data set, because the first
999 # time the ramp() function searches for the top value in
1000 # the inputs, and therefore, results could flucuate.
1001 # The second learning cycle guarantees more accuracy.
1002 #
1003 0 ▶ sub ramp {
Subroutine ramp: not called CC=3 SCAR=24.8
Pod documented
1004 0 ▶ my $r=shift||1;my $t=($r<2)?0:-1;
Branch: 1 branch
BranchTrueFalseTotal
$r < 2 ? : 0 0 0
Condition0%0/2
shift() || 1
l!l
00
MC/DC0%0/1
shift() || 1
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1005 0 ▶ sub{$_[1]->{t}=$_[0]if($_[0]>$_[1]->{t});$_[0]/$_[1]->{t}*$r-$b}
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] > $_[1]{"t"} 0 0 0
1006 0 }
1007
1008 # Self explanitory, pretty much. $threshold is used to decide if an input
1009 # is true or false (1 or 0). If an input is below $threshold, it is false.
1010 0 ▶ sub and_gate {
Subroutine and_gate: not called CC=2 SCAR=17.9
Pod documented
1011 0 ▶ my $threshold = shift || 0.5;
Condition0%0/2
shift() || 0.5
l!l
00
MC/DC0%0/1
shift() || 0.5
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1012 0 ▶ sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1013 0 my $sum = shift;
1014 0 my $self = shift;
1015 0 ▶ for my $x (0..$self->{_inputs_size}-1) { return $self->{_parent}->{const} if!$self->{_inputs}->[$x]->{value}<$threshold }
Branch: 1 branch
BranchTrueFalseTotal
if !$self->{"_inputs"}[$x]{"value"} < $threshold 0 0 0
1016 0 return $sum/$self->{_inputs_size};
1017 }
1018 0 }
1019
1020 # Self explanitory, $threshold is used same as above.
1021 0 ▶ sub or_gate {
Subroutine or_gate: not called CC=2 SCAR=17.9
Pod documented
1022 0 ▶ my $threshold = shift || 0.5;
Condition0%0/2
shift() || 0.5
l!l
00
MC/DC0%0/1
shift() || 0.5
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1023 0 ▶ sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1024 0 my $sum = shift;
1025 0 my $self = shift;
1026 0 ▶ for my $x (0..$self->{_inputs_size}-1) { return $sum/$self->{_inputs_size} if!$self->{_inputs}->[$x]->{value}<$threshold }
Branch: 1 branch
BranchTrueFalseTotal
if !$self->{"_inputs"}[$x]{"value"} < $threshold 0 0 0
1027 0 return $self->{_parent}->{const};
1028 }
1029 0 }
1030
1031 1 1;
1032
1033 package AI::NeuralNet::Mesh::node;
1034
1035 1 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
1036
1037 # Node constructor
1038 15 ▶ sub new {
Subroutine new: called CC=1 SCAR=0.0
1039 15 my $type = shift;
1040 15 my $self ={
1041 _parent => shift,
1042 _inputs => [],
1043 _outputs => []
1044 };
1045 15 bless $self, $type;
1046 }
1047
1048 # Receive inputs from other nodes, and also send
1049 # outputs on.
1050 416 ▶ sub input {
Subroutine input: called CC=15 SCAR=32.1
1051 416 my $self = shift;
1052 416 my $input = shift;
1053 416 my $from_id = shift;
1054
1055 416 $self->{_inputs}->[$from_id]->{value} = $input * $self->{_inputs}->[$from_id]->{weight};
1056 416 $self->{_inputs}->[$from_id]->{input} = $input;
1057 416 $self->{_inputs}->[$from_id]->{fired} = 1;
1058
1059 416 $self->{_parent}->d("got input $input from id $from_id, weighted to $self->{_inputs}->[$from_id]->{value}.\n",1);
1060
1061 416 my $flag = 1;
1062 416 ▶ for my $x (0..$self->{_inputs_size}-1) { $flag = 0 if(!$self->{_inputs}->[$x]->{fired}) }
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_inputs"}[$x]{"fired"} 6 742 748
1063 416 ▶ if ($flag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flag) { } 410 6 416
1064 410 $self->{_parent}->d("all inputs fired for $self.\n",1);
1065 410 my $output = 0;
1066
1067 # Sum
1068 410 for my $i (@{$self->{_inputs}}) {
1069 736 $output += $i->{value};
1070 }
1071
1072 # Handle activations, thresholds, and means
1073 410 ▶ $output /= $self->{_inputs_size} if($self->{flag_mean});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"flag_mean"} 0 410 410
1074 #$output += (rand()*$self->{_parent}->{random});
1075 410 ▶ $output = ($output>=$self->{threshold})?1:0 if(($self->{activation} eq "sigmoid") || ($self->{activation} eq "sigmoid_1"));
Branch: 2 branches
BranchTrueFalseTotal
if $self->{"activation"} eq "sigmoid" or $self->{"activation"} eq "sigmoid_1" 0 410 410
$output >= $self->{'threshold'} ? : 0 0 0
Condition33%1/3
$self->{"activation"} eq "sigmoid" or $self->{"activation"} eq "sigmoid_1"
l!l&&r!l&&!r
00410
MC/DC0%0/2
$self->{"activation"} eq "sigmoid" or $self->{"activation"} eq "sigmoid_1"
$self->{"activation"} eq "sigmoid" $self->{"activation"} eq "sigmoid_1"
Truth table33%1/3
A or B
A= $self->{"activation"} eq "sigmoid"B= $self->{"activation"} eq "sigmoid_1"
ABresult
1X1
011
000
1076 410 ▶ if($self->{activation} eq "sigmoid_2") {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"activation"} eq "sigmoid_2") 0 410 410
1077 0 ▶ $output = 1 if($output >$self->{threshold});
Branch: 1 branch
BranchTrueFalseTotal
if $output > $self->{"threshold"} 0 0 0
1078 0 ▶ $output = -1 if($output <$self->{threshold});
Branch: 1 branch
BranchTrueFalseTotal
if $output < $self->{"threshold"} 0 0 0
1079 0 ▶ $output = 0 if($output==$self->{threshold});
Branch: 1 branch
BranchTrueFalseTotal
if $output == $self->{"threshold"} 0 0 0
1080 }
1081
1082 # Handle CODE refs
1083 0 ▶ $output = &{$self->{activation}}($output,$self) if(ref($self->{activation}) eq "CODE");
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->{"activation"} eq "CODE" 0 410 410
1084
1085 # Send output
1086 410 for my $o (@{$self->{_outputs}}) { $o->{node}->input($output,$o->{from_id}) }
1087 } else {
1088 6 $self->{_parent}->d("all inputs have NOT fired for $self.\n",1);
1089 }
1090 }
1091
1092 24 ▶ sub add_input_node {
Subroutine add_input_node: called CC=2 SCAR=6.9
1093 24 my $self = shift;
1094 24 my $node = shift;
1095 24 ▶ my $i = $self->{_inputs_size} || 0;
Condition100%2/2
$self->{'_inputs_size'} || 0
l!l
915
MC/DC100%1/1
$self->{'_inputs_size'} || 0
$self->{'_inputs_size'}
Truth table100%2/2
A
A= $self->{'_inputs_size'}
Aresult
11
00
1096 24 $self->{_inputs}->[$i]->{node} = $node;
1097 24 $self->{_inputs}->[$i]->{value} = 0;
1098 24 $self->{_inputs}->[$i]->{weight} = 1; #rand()*1;
1099 24 $self->{_inputs}->[$i]->{fired} = 0;
1100 24 $self->{_inputs_size} = ++$i;
1101 24 return $i-1;
1102 }
1103
1104 21 ▶ sub add_output_node {
Subroutine add_output_node: called CC=2 SCAR=6.9
1105 21 my $self = shift;
1106 21 my $node = shift;
1107 21 ▶ my $i = $self->{_outputs_size} || 0;
Condition100%2/2
$self->{'_outputs_size'} || 0
l!l
615
MC/DC100%1/1
$self->{'_outputs_size'} || 0
$self->{'_outputs_size'}
Truth table100%2/2
A
A= $self->{'_outputs_size'}
Aresult
11
00
1108 21 $self->{_outputs}->[$i]->{node} = $node;
1109 21 $self->{_outputs}->[$i]->{from_id} = $node->add_input_node($self);
1110 21 $self->{_outputs_size} = ++$i;
1111 21 return $i-1;
1112 }
1113
1114 224 ▶ sub adjust_weight {
Subroutine adjust_weight: called CC=3 SCAR=11.0
1115 224 my $self = shift;
1116 224 my $inc = shift;
1117 224 for my $i (@{$self->{_inputs}}) {
1118 320 $i->{weight} += $inc * $i->{weight};
1119 320 ▶ $i->{node}->adjust_weight($inc) if($i->{node});
Branch: 1 branch
BranchTrueFalseTotal
if $i->{"node"} 320 0 320
1120 }
1121 }
1122
1123 1 1;
1124
1125 # Internal usage, prevents recursion on empty nodes.
1126 package AI::NeuralNet::Mesh::cap;
1127 3 ▶ sub new { bless {}, shift }
Subroutine new: called CC=1 SCAR=0.0
1128 0 ▶ sub input {}
Subroutine input: not called CC=1 SCAR=0.0
1129 128 ▶ sub adjust_weight {}
Subroutine adjust_weight: called CC=1 SCAR=0.0
1130 0 ▶ sub add_output_node {}
Subroutine add_output_node: not called CC=1 SCAR=0.0
1131 0 ▶ sub add_input_node {}
Subroutine add_input_node: not called CC=1 SCAR=0.0
1132 1 1;
1133
1134 # Internal usage, collects data from output layer.
1135 package AI::NeuralNet::Mesh::output;
1136
1137 1 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
1138
1139 3 ▶ sub new {
Subroutine new: called CC=1 SCAR=0.0
1140 3 my $type = shift;
1141 3 my $self ={
1142 _parent => shift,
1143 _inputs => [],
1144 };
1145 3 bless $self, $type;
1146 }
1147
1148 3 ▶ sub add_input_node {
Subroutine add_input_node: called CC=1 SCAR=0.0
1149 3 my $self = shift;
1150 3 return (++$self->{_inputs_size})-1;
1151 }
1152
1153 162 ▶ sub input {
Subroutine input: called CC=1 SCAR=0.0
1154 162 my $self = shift;
1155 162 my $input = shift;
1156 162 my $from_id = shift;
1157 162 $self->{_parent}->d("GOT INPUT [$input] FROM [$from_id]\n",1);
1158 162 $self->{_inputs}->[$from_id] = $self->{_parent}->intr($input);
1159 }
1160
1161 42 ▶ sub get_outputs {
Subroutine get_outputs: called CC=1 SCAR=0.0
1162 42 my $self = shift;
1163 42 return $self->{_inputs};
1164 }
1165
1166 1 1;
1167
1168 __END__
↑ Summary