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 qw/FeatureWithLabel/;
use Carp qw//;
use List::MoreUtils qw/none/;
use Smart::Args::TypeTiny;
use Types::Standard qw/ArrayRef ClassName FileHandle InstanceOf Num Str/;

my $InstanceOfPackage = InstanceOf[__PACKAGE__];

sub new {
    args
        my $class => ClassName,
        my $data_set => ArrayRef[FeatureWithLabel];

    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 => $InstanceOfPackage,
        my $data => FeatureWithLabel;

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

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

sub as_problem {
    args
        my $self => $InstanceOfPackage,
        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 => $InstanceOfPackage;

    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 1.161 second using v1.00-cache-2.02-grep-82fe00e-cpan-1925d2aa809 )