blib/lib/Algorithm/AM/DataSet.pm

filter: Statementstmt 96.0% 120 / 125 Branchbran 93.1% 41 / 44 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 95.4% 21 / 22 Podpod 100% 8 / 8 totaltotal 95.4% 190 / 199 CC 23 SCAR 14.9
CC
23
Cov
95%
dataset_from_file
9.1
__ANON__
8.0
add_item
4.0
CRAP 4.5
« blib/lib/Algorithm/AM/Result.pm ↑ Summary blib/lib/Algorithm/AM/DataSet/Item.pm »
1 package Algorithm::AM::DataSet;
2 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 10 our $VERSION = '3.13';
5 # ABSTRACT: Manage data used by Algorithm::AM
6 10 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 10 ▶use Algorithm::AM::DataSet::Item;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use Exporter::Easy (
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 OK => ['dataset_from_file']
11 10 );
12  
13 #pod =head1 SYNOPSIS
14 #pod
15 #pod use Algorithm::AM::DataSet 'dataset_from_file';
16 #pod use Algorithm::AM::DataSet::Item 'new_item';
17 #pod my $dataset = Algorithm::AM::DataSet->new(cardinality => 10);
18 #pod # or
19 #pod $dataset = dataset_from_file(path => 'finnverb', format => 'nocommas');
20 #pod $dataset->add_item(
21 #pod new_item(features => [qw(a b c d e f g h i)]));
22 #pod my $item = $dataset->get_item(2);
23 #pod
24 #pod =head1 DESCRIPTION
25 #pod
26 #pod This package contains a list of items that can be used by
27 #pod L<Algorithm::AM> or L<Algorithm::AM::Batch> for classification.
28 #pod DataSets can be made one item at a time via the L</add_item> method,
29 #pod or they can be read from files via the L</dataset_from_file> function.
30 #pod
31 #pod =head2 C<new>
32 #pod
33 #pod Creates a new DataSet object. You must provide a C<cardinality> argument
34 #pod indicating the number of features to be contained in each data vector.
35 #pod You can then add items via the add_item method. Each item will contain
36 #pod a feature vector, and also optionally a class label and a comment
37 #pod (also called a "spec").
38 #pod
39 #pod =cut
40 50 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
41 50 my ($class, %opts) = @_;
42  
43 50 my $new_opts = _check_opts(%opts);
44  
45 48 my $self = bless $new_opts, $class;
46  
47 48 $self->_init;
48  
49 48 return $self;
50 }
51  
52 # check the options for validity
53 # Return an option hash to initialize $self with
54 # For now only 'cardinality' is allowed/required.
55 50 ▶sub _check_opts {
Subroutine _check_opts: called CC=3 SCAR=11.0
56 50 my (%opts) = @_;
57  
58 50 my %final_opts;
59  
60 50 ▶ if(!defined $opts{cardinality}){
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opts{"cardinality"}) 1 49 50
61 1 croak q{Failed to provide 'cardinality' parameter};
62 }
63 49 $final_opts{cardinality} = $opts{cardinality};
64 49 delete $opts{cardinality};
65  
66 49 ▶ if(keys %opts){
Branch: 1 branch
BranchTrueFalseTotal
if (keys %opts) 1 48 49
67 # sort the keys in the error message to make testing possible
68 1 croak 'Unknown parameters in DataSet constructor: ' .
69 (join ', ', sort keys %opts);
70 }
71  
72 48 return \%final_opts;
73 }
74  
75 # initialize internal state
76 48 ▶sub _init {
Subroutine _init: called CC=1 SCAR=0.0
77 48 my ($self) = @_;
78 # contains all of the items in the dataset
79 48 $self->{items} = [];
80  
81 # map unique class labels to unique integers;
82 # these are the indices of the class labels in class_list below;
83 # the indices must start at 1 for AM to work, as 0 is reserved
84 # for heterogeneity.
85 48 $self->{class_num_index} = {};
86 # contains the list of class strings in an order that matches
87 # the indices in class_num_index
88 48 $self->{class_list} = [];
89 # the total number of different classes contained in the data set
90 48 $self->{num_classes} = 0;
91 48 return;
92 }
93  
94 #pod =head2 C<cardinality>
95 #pod
96 #pod Returns the number of features contained in the feature vector of a
97 #pod single item.
98 #pod
99 #pod =cut
100 881 ▶sub cardinality {
Subroutine cardinality: called CC=1 SCAR=0.0
Pod documented
101 881 my ($self) = @_;
102 881 return $self->{cardinality};
103 }
104  
105 #pod =head2 C<size>
106 #pod
107 #pod Returns the number of items in the data set.
108 #pod
109 #pod =cut
110 830 ▶sub size {
Subroutine size: called CC=1 SCAR=0.0
Pod documented
111 830 my ($self) = @_;
112 830 return scalar @{$self->{items}};
113 }
114  
115 #pod =head2 C<classes>
116 #pod
117 #pod Returns the list of all unique class labels in the data set.
118 #pod
119 #pod =cut
120 0 ▶sub classes {
Subroutine classes: not called CC=1 SCAR=6.9
Pod documented
121 0 my ($self) = @_;
122 0 return @{ $self->{class_list} };
123 }
124  
125 #pod =head2 C<add_item>
126 #pod
127 #pod Adds a new item to the data set. The input may be either an
128 #pod L<Algorithm::AM::DataSet::Item> object, or the arguments to create
129 #pod one via its constructor (features, class, comment). This method will
130 #pod croak if the cardinality of the item does not match L</cardinality>.
131 #pod
132 #pod =cut
133 276 ▶sub add_item {
Subroutine add_item: called CC=4 SCAR=13.9
Pod documented
134 276 my ($self, @args) = @_;
135 276 my $item;
136 276 ▶ if('Algorithm::AM::DataSet::Item' eq ref $args[0]){
Branch: 1 branch
BranchTrueFalseTotal
if ('Algorithm::AM::DataSet::Item' eq ref $args[0]) { } 219 57 276
137 219 $item = $args[0];
138 }else{
139 57 $item = Algorithm::AM::DataSet::Item->new(@args);
140 }
141  
142 275 ▶ if($self->cardinality != $item->cardinality){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->cardinality != $item->cardinality) 1 274 275
143 croak 'Expected ' . $self->cardinality .
144 ' features, but found ' . (scalar $item->cardinality) .
145 1 ' in ' . (join ' ', @{$item->features}) .
146 ' (' . $item->comment . ')';
147 }
148  
149 274 ▶ if(defined $item->class){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $item->class) 270 4 274
150 270 $self->_update_class_vars($item->class);
151 }
152  
153 # store the new item
154 274 push @{$self->{items}}, $item;
155 274 return;
156 }
157  
158 # keep track of classes; needs updating for new item
159 270 ▶sub _update_class_vars {
Subroutine _update_class_vars: called CC=2 SCAR=6.9
160 270 my ($self, $class) = @_;
161  
162 270 ▶ if(!$self->{class_num_index}->{$class}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"class_num_index"}{$class}) 47 223 270
163 47 $self->{num_classes}++;
164 47 $self->{class_num_index}->{$class} = $self->{num_classes};
165 47 push @{$self->{class_list}}, $class;
166 }
167 270 return;
168 }
169  
170 #pod =head2 C<get_item>
171 #pod
172 #pod Return the item at the given index. This will be a
173 #pod L<Algorithm::AM::DataSet::Item> object.
174 #pod
175 #pod =cut
176 60306 ▶sub get_item {
Subroutine get_item: called CC=1 SCAR=0.0
Pod documented
177 60306 my ($self, $index) = @_;
178 60306 return $self->{items}->[$index];
179 }
180  
181 #pod =head2 C<num_classes>
182 #pod
183 #pod Returns the number of different classification labels contained in
184 #pod the data set.
185 #pod
186 #pod =cut
187 388 ▶sub num_classes {
Subroutine num_classes: called CC=1 SCAR=0.0
Pod documented
188 388 my ($self) = @_;
189 388 return $self->{num_classes};
190 }
191  
192 # Used by AM. Return an arrayref containing all of the
193 # classes for the data set (ordered the same as the data set).
194 194 ▶sub _data_classes {
Subroutine _data_classes: called CC=2 SCAR=7.0
195 194 my ($self) = @_;
196 my @classes = map {
197 30018 ▶ defined $_->class ?
Branch: 1 branch
BranchTrueFalseTotal
defined $_->class ? : 30018 0 30018
198 $self->_index_for_class($_->class) :
199 undef
200 194 } @{$self->{items}};
201 194 return \@classes;
202 }
203  
204 # Used by AM. Return the integer mapped to the given class string.
205 60053 ▶sub _index_for_class {
Subroutine _index_for_class: called CC=1 SCAR=0.0
206 60053 my ($self, $class) = @_;
207 60053 return $self->{class_num_index}->{$class};
208 }
209  
210 # Used by Result, which traverses data structures from
211 # AM's guts.
212 364 ▶sub _class_for_index {
Subroutine _class_for_index: called CC=1 SCAR=0.0
213 364 my ($self, $index) = @_;
214 364 return $self->{class_list}->[$index - 1];
215 }
216  
217 #pod =head2 C<dataset_from_file>
218 #pod
219 #pod This function may be exported. Given 'path' and 'format' arguments,
220 #pod it reads a file containing a dataset and returns a new DataSet object
221 #pod with the given data. The 'path' argument should be the path to the
222 #pod file. The 'format' argument should be 'commas' or 'nocommas',
223 #pod indicating one of the following formats. You may also specify 'unknown'
224 #pod and 'null' arguments to indicate the strings meant to represent an
225 #pod unknown class value and null feature values. By default these are
226 #pod 'UNK' and '='.
227 #pod
228 #pod The 'commas' file format is shown below:
229 #pod
230 #pod class , f eat u re s , your comment here
231 #pod
232 #pod The commas separate the class label, feature values, and comments,
233 #pod and the whitespace around the commas is optional. Each feature value
234 #pod is separated with whitespace.
235 #pod
236 #pod The 'nocommas' file format is shown below:
237 #pod
238 #pod class features your comment here
239 #pod
240 #pod Here the class, feature values, and comments are separated by
241 #pod whitespace. Each feature value must be a single character with no
242 #pod separating characters, so here the features are f, e, a, t, u, r,
243 #pod e, and s.
244 #pod
245 #pod Lines beginning with a pound character (C<#>) are ignored.
246 #pod
247 #pod =cut
248 12 ▶sub dataset_from_file {## no critic (RequireArgUnpacking)
Subroutine dataset_from_file: called CC=9 SCAR=22.1
Pod documented
249 12 my (%opts) = (
250 unknown => 'UNK',
251 null => '=',
252 @_
253 );
254  
255 croak q[Failed to provide 'path' parameter]
256 12 ▶ unless exists $opts{path};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"path"} 1 11 12
257 croak q[Failed to provide 'format' parameter]
258 11 ▶ unless exists $opts{format};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"format"} 1 10 11
259  
260 my ($path, $format, $unknown, $null) = (
261 10 path($opts{path}), @opts{'format', 'unknown', 'null'});
262  
263 10 ▶ croak "Could not find file $path"
Branch: 1 branch
BranchTrueFalseTotal
unless $path->exists 1 9 10
264 unless $path->exists;
265  
266 9 my ($field_sep, $feature_sep);
267 9 ▶ if($format eq 'commas'){
Branch: 2 branches
BranchTrueFalseTotal
if ($format eq 'commas') { } 4 5 9
elsif ($format eq 'nocommas') { } 4 1 5
268 # class/features/comment separated by a comma
269 4 $field_sep = qr{\s*,\s*};
270 # features separated by space
271 4 $feature_sep = qr{\s+};
272 }elsif($format eq 'nocommas'){
273 # class/features/comment separated by space
274 4 $field_sep = qr{\s+};
275 # no seps for features; each is a single character
276 4 $feature_sep = qr{};
277 }else{
278 1 croak "Unknown value $format for format parameter " .
279 q{(should be 'commas' or 'nocommas')};
280 }
281  
282 8 ▶ if(!defined $unknown){
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $unknown) 0 8 8
283 0 croak q[Must provide a defined value for 'unknown' parameter];
284 }
285  
286 8 my $reader = _read_data_sub(
287 $path, $unknown, $null, $field_sep, $feature_sep);
288 8 my $item = $reader->();
289 8 ▶ if(!$item){
Branch: 1 branch
BranchTrueFalseTotal
unless ($item) 0 8 8
290 0 croak "No data found in file $path";
291 }
292 8 my $dataset = __PACKAGE__->new(cardinality => $item->cardinality);
293 8 $dataset->add_item($item);
294 8 ▶ while($item = $reader->()){
Branch: 1 branch
BranchTrueFalseTotal
if ($item = &$reader()) 189 7 196
295 189 $dataset->add_item($item);
296 }
297 7 return $dataset;
298 }
299  
300 # return a sub that returns one Item per call from the given FH,
301 # and returns undef once the file is done being read. Throws errors
302 # on bad file contents.
303 # Input is file (Path::Tiny), string representing unknown class,
304 # string representing null feature, field separator (class,
305 # features, comment) and feature separator
306 8 ▶sub _read_data_sub {
Subroutine _read_data_sub: called CC=1 SCAR=0.0
307 8 my ($data_file, $unknown, $null,
308 $field_sep, $feature_sep) = @_;
309 8 my $data_fh = $data_file->openr_utf8;
310 8 my $line_num = 0;
311 205 ▶ return sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
312 205 my $line;
313 # grab the next non-blank line from the file
314 205 ▶ while($line = <$data_fh>){
Branch: 1 branch
BranchTrueFalseTotal
if (defined($line = readline $data_fh)) 201 7 208
315 201 $line_num++;
316 # skip comments
317 201 ▶ next if $line =~ m/^\s*#/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*#/ 2 199 201
318 # cross-platform chomp
319 199 $line =~ s/\R$//;
320 199 $line =~ s/^\s+|\s+$//g;
321 199 ▶ last if $line;
Branch: 1 branch
BranchTrueFalseTotal
if $line 198 1 199
322 }
323 205 ▶ return unless $line;
Branch: 1 branch
BranchTrueFalseTotal
unless $line 7 198 205
324 198 my ($class, $feats, $comment) = split /$field_sep/, $line, 3;
325 # the line has to have at least the class label and features
326 198 ▶ if(!defined $feats){
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $feats) 1 197 198
327 1 croak "Couldn't read data at line $line_num in $data_file";
328 }
329 # if the class is specified as unknown, set it to undef to
330 # indicate this to Item
331 197 ▶ if($class eq $unknown){
Branch: 1 branch
BranchTrueFalseTotal
if ($class eq $unknown) 4 193 197
332 4 undef $class;
333 }
334  
335 197 my @data_vars = split /$feature_sep/, $feats;
336 # set null features to ''
337 197 ▶ @data_vars = map {$_ eq $null ? '' : $_} @data_vars;
Branch: 1 branch
BranchTrueFalseTotal
$_ eq $null ? : 319 1594 1913
338  
339 197 return Algorithm::AM::DataSet::Item->new(
340 features=> \@data_vars,
341 class => $class,
342 comment => $comment
343 );
344 8 };
345 }
346  
347 10 1;
348  
349 __END__
« blib/lib/Algorithm/AM/Result.pm ↑ Summary blib/lib/Algorithm/AM/DataSet/Item.pm »