Algorithm-LibLinear

 view release on metacpan or  search on metacpan

lib/Algorithm/LibLinear/DataSet.pm  view on Meta::CPAN

package Algorithm::LibLinear::DataSet;

use 5.014;
use Algorithm::LibLinear::Types;
use Carp qw//;
use List::MoreUtils qw/none/;
use Smart::Args;

sub new {
    args
        my $class => 'ClassName',
        my $data_set => 'ArrayRef[Algorithm::LibLinear::LabeledData]';

    bless +{ data_set => $data_set } => $class;
}

sub load {
    args
        my $class => 'ClassName',
        my $fh => +{ isa => 'FileHandle', optional => 1, },
        my $filename => +{ isa => 'Str', optional => 1, },
        my $string => +{ isa => 'Str', optional => 1, };

    if (none { defined } ($fh, $filename, $string)) {
        Carp::croak('No source specified.');
    }
    my $source = $fh;
    $source //= do {
        open my $fh, '<', +($filename // \$string) or Carp::croak($!);
        $fh;
    };
    $class->new(data_set => $class->parse_input_file($source));
}

sub add_data {
    args
        my $self,
        my $data => 'Algorithm::LibLinear::LabeledData';

    push @{ $self->data_set }, $data;
}

sub as_arrayref { $_[0]->{data_set} }

sub as_problem {
    args
        my $self,
        my $bias => +{ isa => 'Num', default => -1.0, };

    my (@features, @labels);
    for my $data (@{ $self->as_arrayref }) {
        push @features, $data->{feature};
        push @labels, $data->{label};
    }
    Algorithm::LibLinear::Problem->new(\@labels, \@features, $bias);
}

sub as_string {
    args
        my $self;

    my $result = '';
    for my $entry (@{ $self->as_arrayref }) {
        my $feature = $entry->{feature};
        my @feature_dump =
            map { "$_:$feature->{$_}" } sort { $a <=> $b } keys %$feature;
        $result .= join(' ', $entry->{label}, @feature_dump) . "\n";
    }
    return $result;
}

sub parse_input_file {
    args_pos
        my $class => 'ClassName',

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 0.964 second using v1.00-cache-1.14-grep-28634ff-cpan-4d46879620f )