view release on metacpan or search on metacpan
lib/AI/CRM114.pm view on Meta::CPAN
__END__
=head1 NAME
AI::CRM114 - Wrapper for the statistical data classifier CRM114
=head1 SYNOPSIS
use AI::CRM114;
my $crm = AI::CRM114->new(cmd => '/path/to/crm');
lib/AI/CRM114.pm view on Meta::CPAN
# Classify some text
my $class = $crm->classify(['osb'], ['a.css', 'b.css'], $text);
=head1 DESCRIPTION
The CRM114 Discriminator, is a collection of tools to classify data,
e.g. for use in spam filters. This module is a simple wrapper around
the command line executable. Feedback is very welcome, the interface
is unstable. Use with caution.
=head1 METHODS
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/Calibrate.pm view on Meta::CPAN
=item B<calibrate>
This is the main calibration function. The calling form is:
my $calibrated = calibrate( $data, $sorted);
$data looks like: C<[ [score, class], [score, class], [score, class]...]>
Each score is a number. Each class is either 0 (negative class) or 1
(positive class).
$sorted is boolean (0 by default) indicating whether the data are already
sorted by score. Unless this is set to 1, calibrate() will sort the data
itself.
Calibrate returns a reference to an ordered list of references:
[ [score, prob], [score, prob], [score, prob] ... ]
lib/AI/Calibrate.pm view on Meta::CPAN
B<score_prob> function, along with a new score, to get a probability.
=cut
sub calibrate {
my($data, $sorted) = @_;
if (DEBUG) {
print "Original data:\n";
for my $pair (@$data) {
my($score, $prob) = @$pair;
print "($score, $prob)\n";
}
}
# Copy the data over so PAV can clobber the PROB field
my $new_data = [ map([@$_], @$data) ];
# If not already sorted, sort data decreasing by score
if (!$sorted) {
$new_data = [ sort { $b->[SCORE] <=> $a->[SCORE] } @$new_data ];
}
PAV($new_data);
if (DEBUG) {
print("After PAV, vector is:\n");
print_vector($new_data);
}
my(@result);
my( $last_prob, $last_score);
push(@$new_data, [-1e10, 0]);
for my $pair (@$new_data) {
print "Seeing @$pair\n" if DEBUG;
my($score, $prob) = @$pair;
if (defined($last_prob) and $prob < $last_prob) {
print("Pushing [$last_score, $last_prob]\n") if DEBUG;
push(@result, [$last_score, $last_prob] );
lib/AI/Calibrate.pm view on Meta::CPAN
This module exports three functions: calibrate, score_prob and print_mapping.
=head1 BUGS
None known. This implementation is straightforward but inefficient (its time
is O(n^2) in the length of the data series). A linear time algorithm is
known, and in a later version of this module I'll probably implement it.
=head1 SEE ALSO
The AI::NaiveBayes1 perl module.
view all matches for this distribution
view release on metacpan or search on metacpan
use AI::Categorizer::Collection::Files;
use AI::Categorizer::Learner::NaiveBayes;
use File::Spec;
die("Usage: $0 <corpus>\n".
" A sample corpus (data set) can be downloaded from\n".
" http://www.cpan.org/authors/Ken_Williams/data/reuters-21578.tar.gz\n".
" or http://www.limnus.com/~ken/reuters-21578.tar.gz\n")
unless @ARGV == 1;
my $corpus = shift;
view all matches for this distribution
view release on metacpan or search on metacpan
t/01-openai.t
t/manifest.t
t/pod-coverage.t
t/pod.t
t/version.t
META.yml Module YAML meta-data (added by MakeMaker)
META.json Module JSON meta-data (added by MakeMaker)
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/Classifier/Text/FileLearner.pm view on Meta::CPAN
has iterator => ( is => 'ro', lazy_build => 1 );
sub _build_iterator {
my $self = shift;
my $rule = File::Find::Rule->new( );
$rule->file;
$rule->not_name('*.data');
$rule->start( $self->training_dir );
return $rule;
}
sub get_category {
lib/AI/Classifier/Text/FileLearner.pm view on Meta::CPAN
|| Carp::croak(
"Unable to read the specified training file: $file\n");
my $content = join('', <$fh>);
close $fh;
my $initial_features = {};
if( -f "$file.data" ){
my $data = do "$file.data";
$initial_features = $data->{initial_features}
}
my $features = $self->analyzer->analyze( $content, $initial_features );
return {
file => $file,
lib/AI/Classifier/Text/FileLearner.pm view on Meta::CPAN
}
sub teach_it {
my $self = shift;
my $learner = $self->learner;
while ( my $data = $self->next ) {
normalize( $data->{features} );
$self->weight_terms($data);
$learner->add_example(
attributes => $data->{features},
labels => $data->{categories}
);
}
}
lib/AI/Classifier/Text/FileLearner.pm view on Meta::CPAN
=pod
=head1 NAME
AI::Classifier::Text::FileLearner - Training data reader for AI::NaiveBayes
=head1 VERSION
version 0.03
=head1 SYNOPSIS
use AI::Classifier::Text::FileLearner;
my $learner = AI::Classifier::Text::FileLearner->new( training_dir => 't/data/training_set_ordered/' );
my $classifier = $learner->classifier;
=head1 DESCRIPTION
lib/AI/Classifier/Text/FileLearner.pm view on Meta::CPAN
=over 4
=item next
Internal method for traversing the training data directory.
=item classifier
Returns a trained classifier.
lib/AI/Classifier/Text/FileLearner.pm view on Meta::CPAN
=cut
__END__
# ABSTRACT: Training data reader for AI::NaiveBayes
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/CleverbotIO.pm view on Meta::CPAN
key => $self->key,
user => $self->user,
);
$ps{nick} = $self->nick if $self->has_nick && length $self->nick;
my $data =
$self->_parse_response(
$self->ua->post_form($self->endpoints->{create}, \%ps));
$self->nick($data->{nick}) if exists($data->{nick});
return $data;
}
sub _parse_response {
my ($self, $response) = @_;
lib/AI/CleverbotIO.pm view on Meta::CPAN
my $status = $response->{status};
ouch $status, $response->{reason}
if ($status != 200) && ($status != 400);
my $data = __decode_content($response);
return $data if $response->{success};
ouch 400, $data->{status};
} ## end sub _parse_response
sub __decode_content {
my $response = shift;
my $encoded = $response->{content};
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/ConfusionMatrix.pm view on Meta::CPAN
=back
=head4 C<getConfusionMatrix($hash_ref)>
Get the data used to compute the table above.
Example:
my %cm = getConfusionMatrix(\%matrix);
view all matches for this distribution
view release on metacpan or search on metacpan
eg/example.pl view on Meta::CPAN
# Show the created tree structure as rules
print map "$_\n", $dtree->rule_statements;
# Will barf on inconsistent data
my $t2 = new AI::DecisionTree;
$t2->add_instance( attributes => { foo => 'bar' },
result => 1 );
$t2->add_instance( attributes => { foo => 'bar' },
result => 0 );
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/Embedding.pm view on Meta::CPAN
my ($self, $text, $verbose) = @_;
my $response = $self->_get_embedding($text);
if ($response->{'success'}) {
my $embedding = decode_json($response->{'content'});
return join (',', @{$embedding->{'data'}[0]->{'embedding'}});
}
$self->{'error'} = 'HTTP Error - ' . $response->{'reason'};
return $response if defined $verbose;
return undef;
}
lib/AI/Embedding.pm view on Meta::CPAN
my ($self, $text, $verbose) = @_;
my $response = $self->_get_embedding($text);
if ($response->{'success'}) {
my $embedding = decode_json($response->{'content'});
return @{$embedding->{'data'}[0]->{'embedding'}};
}
$self->{'error'} = 'HTTP Error - ' . $response->{'reason'};
return $response if defined $verbose;
return undef;
}
lib/AI/Embedding.pm view on Meta::CPAN
The L<AI::Embedding> module provides an interface for working with text embeddings using various APIs. It currently supports the L<OpenAI|https://www.openai.com> L<Embeddings API|https://platform.openai.com/docs/guides/embeddings/what-are-embeddings>...
Embeddings allow the meaning of passages of text to be compared for similarity. This is more natural and useful to humans than using traditional keyword based comparisons.
An Embedding is a multi-dimensional vector representing the meaning of a piece of text. The Embedding vector is created by an AI Model. The default model (OpenAI's C<text-embedding-ada-002>) produces a 1536 dimensional vector. The resulting vector...
=head2 Comparator
Embeddings are used to compare similarity of meaning between two passages of text. A typical work case is to store a number of pieces of text (e.g. articles or blogs) in a database and compare each one to some user supplied search text. L<AI::Embed...
Alternatively, the C<comparator> method can be called with one Embedding. The C<comparator> returns a reference to a method that takes a single Embedding to be compared to the Embedding from which the Comparator was created.
When comparing multiple Embeddings to the same Embedding (such as search text) it is faster to use a C<comparator>.
lib/AI/Embedding.pm view on Meta::CPAN
my $csv_embedding = $embedding->embedding('Some text passage', [$verbose]);
Generates an embedding for the given text and returns it as a comma-separated string. The C<embedding> method takes a single parameter, the text to generate the embedding for.
Returns a (rather long) string that can be stored in a C<TEXT> database field.
If the method call fails it sets the L</"error"> message and returns C<undef>. If the optional C<verbose> parameter is true, the complete L<HTTP::Tiny> response object is also returned to aid with debugging issues when using this module.
=head2 raw_embedding
lib/AI/Embedding.pm view on Meta::CPAN
my $test_embedding = $embedding->test_embedding('Some text passage', $dimensions);
Used for testing code without making a chargeable call to the API.
Provides a CSV string of the same size and format as L<embedding> but with meaningless random data.
Returns a random embedding. Both parameters are optional. If a text string is provided, the returned embedding will always be the same random embedding otherwise it will be random and different every time. The C<dimension> parameter controls the n...
=head2 comparator
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/Evolve/Befunge.pm view on Meta::CPAN
critters may be weighed against eachother. It provides a set of
commands which may be used by the critters to do useful things within
its universe (such as make a move in a board game, do a spellcheck,
or request a google search).
Physics engines register themselves with the Physics database (which
is managed by Physics.pm). The arguments they pass to
register_physics() get wrapped up in a hash reference, which is copied
for you whenever you call Physics->new("pluginname"). The "commands"
argument is particularly important: this is where you add special
befunge commands and provide references to callback functions to
view all matches for this distribution
view release on metacpan or search on metacpan
inc/Module/Install/Metadata.pm view on Meta::CPAN
#line 1
package Module::Install::Metadata;
use strict 'vars';
use Module::Install::Base ();
use vars qw{$VERSION @ISA $ISCORE};
inc/Module/Install/Metadata.pm view on Meta::CPAN
sub read {
my $self = shift;
$self->include_deps( 'YAML::Tiny', 0 );
require YAML::Tiny;
my $data = YAML::Tiny::LoadFile('META.yml');
# Call methods explicitly in case user has already set some values.
while ( my ( $key, $value ) = each %$data ) {
next unless $self->can($key);
if ( ref $value eq 'HASH' ) {
while ( my ( $module, $version ) = each %$value ) {
$self->can($key)->($self, $module => $version );
}
inc/Module/Install/Metadata.pm view on Meta::CPAN
# We need YAML::Tiny to write the MYMETA.yml file
unless ( eval { require YAML::Tiny; 1; } ) {
return 1;
}
# Generate the data
my $meta = $self->_write_mymeta_data or return 1;
# Save as the MYMETA.yml file
print "Writing MYMETA.yml\n";
YAML::Tiny::DumpFile('MYMETA.yml', $meta);
}
inc/Module/Install/Metadata.pm view on Meta::CPAN
# We need JSON to write the MYMETA.json file
unless ( eval { require JSON; 1; } ) {
return 1;
}
# Generate the data
my $meta = $self->_write_mymeta_data or return 1;
# Save as the MYMETA.yml file
print "Writing MYMETA.json\n";
Module::Install::_write(
'MYMETA.json',
JSON->new->pretty(1)->canonical->encode($meta),
);
}
sub _write_mymeta_data {
my $self = shift;
# If there's no existing META.yml there is nothing we can do
return undef unless -f 'META.yml';
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/ExpertSystem/Simple.pm view on Meta::CPAN
Resets the system back to its initial state so that a new consoltation can be run
=item load( FILENAME )
This method takes the FILENAME of an XML knowledgebase and attempts to parse it to set up the data structures
required for a consoltation.
=item process( )
Once the knowledgebase is loaded the consultation is run by repeatedly calling this method.
lib/AI/ExpertSystem/Simple.pm view on Meta::CPAN
Then simply call the process( ) method again.
=item "continue"
The system has calculated some data but has nothing to ask the user but has still not finished.
This response will be removed in future versions.
Simply call the process( ) method again.
lib/AI/ExpertSystem/Simple.pm view on Meta::CPAN
=over 4
=item _goal
A private method to get the goal data from the knowledgebase.
=item _rule
A private method to get the rule data from the knowledgebase.
=item _question
A private method to get the question data from the knowledgebase.
=item _add_to_log
A private method to add a message to the log.
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/FANN/Evolving.pm view on Meta::CPAN
=over
=item new
Constructor requires 'file', or 'data' and 'neurons' arguments. Optionally takes
'connection_rate' argument for sparse topologies. Returns a wrapper around L<AI::FANN>.
=cut
sub new {
lib/AI/FANN/Evolving.pm view on Meta::CPAN
$self->{'ann'} = AI::FANN->new_from_file($file);
$log->debug("instantiating from file $file");
return $self;
}
# build new topology from input data
elsif ( my $data = $args{'data'} ) {
$log->debug("instantiating from data $data");
$data = $data->to_fann if $data->isa('AI::FANN::Evolving::TrainData');
# prepare arguments
my $neurons = $args{'neurons'} || ( $data->num_inputs + 1 );
my @sizes = (
$data->num_inputs,
$neurons,
$data->num_outputs
);
# build topology
if ( $args{'connection_rate'} ) {
$self->{'ann'} = AI::FANN->new_sparse( $args{'connection_rate'}, @sizes );
lib/AI/FANN/Evolving.pm view on Meta::CPAN
# copy the AI::FANN properties
$ann->template($self->{'ann'});
return $self;
}
else {
die "Need 'file', 'data' or 'ann' argument!";
}
}
=item template
lib/AI/FANN/Evolving.pm view on Meta::CPAN
# we delete the reference here so we can use
# Algorithm::Genetic::Diploid::Base's cloning method, which
# dumps and loads from YAML. This wouldn't work if the
# reference is still attached because it cannot be
# stringified, being an XS data structure
my $ann = delete $self->{'ann'};
my $clone = $self->SUPER::clone;
# clone the ANN by writing it to a temp file in "FANN/FLO"
# format and reading that back in, then delete the file
lib/AI/FANN/Evolving.pm view on Meta::CPAN
return $clone;
}
=item train
Trains the AI on the provided data object
=cut
sub train {
my ( $self, $data ) = @_;
if ( $self->train_type eq 'cascade' ) {
$log->debug("cascade training");
# set learning curve
$self->cascade_activation_functions( $self->activation_function );
# train
$self->{'ann'}->cascadetrain_on_data(
$data,
$self->neurons,
$self->neuron_printfreq,
$self->error,
);
}
lib/AI/FANN/Evolving.pm view on Meta::CPAN
# set learning curves
$self->hidden_activation_function( $self->activation_function );
$self->output_activation_function( $self->activation_function );
# train
$self->{'ann'}->train_on_data(
$data,
$self->epochs,
$self->epoch_printfreq,
$self->error,
);
}
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/FANN.pm view on Meta::CPAN
my $ann = AI::FANN->new_standard(2, 3, 1);
$ann->hidden_activation_function(FANN_SIGMOID_SYMMETRIC);
$ann->output_activation_function(FANN_SIGMOID_SYMMETRIC);
# create the training data for a XOR operator:
my $xor_train = AI::FANN::TrainData->new( [-1, -1], [-1],
[-1, 1], [1],
[1, -1], [1],
[1, 1], [-1] );
$ann->train_on_data($xor_train, 500000, 1000, 0.001);
$ann->save("xor.ann");
Run...
lib/AI/FANN.pm view on Meta::CPAN
Fast Artificial Neural Network Library is a free open source neural
network library, which implements multilayer artificial neural
networks in C with support for both fully connected and sparsely
connected networks. Cross-platform execution in both fixed and
floating point are supported. It includes a framework for easy
handling of training data sets. It is easy to use, versatile, well
documented, and fast. PHP, C++, .NET, Python, Delphi, Octave, Ruby,
Pure Data and Mathematica bindings are available. A reference manual
accompanies the library with examples and recommendations on how to
use the library. A graphical user interface is also available for
the library.
lib/AI/FANN.pm view on Meta::CPAN
=over 4
=item *
Two classes are used: C<AI::FANN> that wraps the C C<struct fann> type
and C<AI::FANN::TrainData> that wraps C<struct fann_train_data>.
=item *
Prefixes and common parts on the C function names referring to those
structures have been removed. For instance C
C<fann_train_data_shuffle> becomes C<AI::FANN::TrainData::shuffle> that
will be usually called as...
$train_data->shuffle;
=item *
Pairs of C get/set functions are wrapped in Perl with dual accessor
methods named as the attribute (and without any C<set_>/C<get_>
lib/AI/FANN.pm view on Meta::CPAN
=item $ann->train_on_file($filename, $max_epochs, $epochs_between_reports, $desired_error)
-
=item $ann->train_on_data($train_data, $max_epochs, $epochs_between_reports, $desired_error)
C<$train_data> is a AI::FANN::TrainData object.
=item $ann->cascadetrain_on_file($filename, $max_neurons, $neurons_between_reports, $desired_error)
-
=item $ann->cascadetrain_on_data($train_data, $max_neurons, $neurons_between_reports, $desired_error)
C<$train_data> is a AI::FANN::TrainData object.
=item $ann->train_epoch($train_data)
C<$train_data> is a AI::FANN::TrainData object.
=item $ann->print_connections
-
lib/AI/FANN.pm view on Meta::CPAN
=back
=head2 AI::FANN::TrainData
Wraps C C<struct fann_train_data> and provides the following method:
=over 4
=item AI::FANN::TrainData->new_from_file($filename)
lib/AI/FANN.pm view on Meta::CPAN
=item AI::FANN::TrainData->new($input1, $output1 [, $input2, $output2, ...])
C<$inputx> and C<$outputx> are arrays with the values of the input and
output layers.
=item AI::FANN::TrainData->new_empty($num_data, $num_inputs, $num_outputs)
returns a new AI::FANN::TrainData object of the sizes indicated on the
arguments. The initial values of the data contained inside the object
are random and should be set before using the train data object for
training an ANN.
=item $train->data($index)
returns two arrays with the values of the input and output layer
respectively for that index.
=item $train->data($index, $input, $output)
C<$input> and C<$output> are two arrays.
The input and output layers at the index C<$index> are set to the
values on these arrays.
view all matches for this distribution
view release on metacpan or search on metacpan
demo/cpu.pl view on Meta::CPAN
my $cpu = <STAT>; # headers
$cpu = <STAT>; # headers
for (1 .. $count ) {
$cpu = <STAT>; # read data
$cpu =~ s/.* (\d+)$/$1/;
chomp $cpu;
print "the cpu is: $cpu " . $f->label($cpu) . "\n";
}
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/FuzzyEngine.pm view on Meta::CPAN
my $problem = $fe->new_variable( -0.5 => 2,
no => [-0.5, 0, 0, 1, 0.5, 0, 1, 0],
yes => [ 0, 0, 0.5, 1, 1, 1, 1.5, 1, 2, 0],
);
# Input data is a pdl of arbitrary dimension
my $data = pdl( [0, 4, 6, 10] );
$severity->fuzzify( $data );
# Membership degrees are piddles now:
print 'Severity is high: ', $severity->high, "\n";
# [0 0.5 1 1]
view all matches for this distribution
view release on metacpan or search on metacpan
FuzzyInference.pm view on Meta::CPAN
return $obj;
}
# sub _init() - private method.
#
# no arguments. Initializes the data structures we will need.
# It also defines the default logic operations we might need.
sub _init {
my $self = shift;
FuzzyInference.pm view on Meta::CPAN
return $self->{RESULTS}{$var};
}
# sub reset() - public method
#
# cleans the data structures used.
sub reset {
my $self = shift;
my @list = $self->{SET}->listMatching(q|:implicated$|);
FuzzyInference.pm view on Meta::CPAN
and only returns useful results after a call to C<compute()> has been
made.
=item reset()
This method resets all the data structures used to compute crisp values
of the output variables. It is implicitly called by the C<compute()>
method above.
=back
view all matches for this distribution
view release on metacpan or search on metacpan
AI/Gene/Sequence.pm view on Meta::CPAN
A gene is a sequence of tokens, each a member of some group
of simillar tokens (they can of course all be members of a
single group). This module encodes genes as a string
representing token types, and an array containing the
tokens themselves, this allows for arbitary data to be
stored as a token in a gene.
For instance, a regular expression could be encoded as:
$self = ['ccartm',['a', 'b', '|', '[A-Z]', '\W', '*?'] ]
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/Genetic/Pro.pm view on Meta::CPAN
$self->_fitness_real($self->fitness);
$self->fitness(\&_fitness_cached);
return;
}
#=======================================================================
sub _check_data_ref {
my ($self, $data_org) = @_;
my $data = clone($data_org);
my $ars;
for(0..$#$data){
next if $ars->{$data->[$_]};
$ars->{$data->[$_]} = 1;
unshift @{$data->[$_]}, undef;
}
return $data;
}
#=======================================================================
# we have to find C to (in some cases) incrase value of range
# due to design model
sub _find_fix_range {
my ($self, $data) = @_;
for my $idx (0..$#$data){
if($data->[$idx]->[1] < 1){
my $const = 1 - $data->[$idx]->[1];
push @{$self->_fix_range}, $const;
$data->[$idx]->[1] += $const;
$data->[$idx]->[2] += $const;
}else{ push @{$self->_fix_range}, 0; }
}
return $data;
}
#=======================================================================
sub init {
my ( $self, $data ) = @_;
croak q/You have to pass some data to "init"!/ unless $data;
#-------------------------------------------------------------------
$self->generation(0);
$self->_init( $data );
$self->_fitness( { } );
$self->_fix_range( [ ] );
$self->_history( [ [ ], [ ], [ ] ] );
$self->_init_cache if $self->cache;
#-------------------------------------------------------------------
if($self->type eq q/listvector/){
croak(q/You have to pass array reference if "type" is set to "listvector"/) unless ref $data eq 'ARRAY';
$self->_translations( $self->_check_data_ref($data) );
}elsif($self->type eq q/bitvector/){
croak(q/You have to pass integer if "type" is set to "bitvector"/) if $data !~ /^\d+$/o;
$self->_translations( [ [ 0, 1 ] ] );
$self->_translations->[$_] = $self->_translations->[0] for 1..$data-1;
}elsif($self->type eq q/combination/){
croak(q/You have to pass array reference if "type" is set to "combination"/) unless ref $data eq 'ARRAY';
$self->_translations( [ clone($data) ] );
$self->_translations->[$_] = $self->_translations->[0] for 1..$#$data;
}elsif($self->type eq q/rangevector/){
croak(q/You have to pass array reference if "type" is set to "rangevector"/) unless ref $data eq 'ARRAY';
$self->_translations( $self->_find_fix_range( $self->_check_data_ref($data) ));
}else{
croak(q/You have to specify first "type" of vector!/);
}
my $size = 0;
lib/AI/Genetic/Pro.pm view on Meta::CPAN
else{ for(@{$self->_translations}){ $size = $_->[2] if $_->[2] > $size; } } # Provisional patch for rangevector values truncated to signed 8-bit quantities. Thx to Tod Hagan
my $package = get_package_by_element_size($size);
$self->_package($package);
my $length = ref $data ? sub { $#$data; } : sub { $data - 1 };
if($self->variable_length){
$length = ref $data ? sub { 1 + int( rand( $#{ $self->_init } ) ); } : sub { 1 + int( rand( $self->_init - 1) ); };
}
$self->_length( $length );
$self->chromosomes( [ ] );
lib/AI/Genetic/Pro.pm view on Meta::CPAN
GD->require or croak(q/You need "/.GD.q/" module to draw chart of evolution!/);
my ($self, %params) = (shift, @_);
my $graph = GD()->new(($params{-width} || 640), ($params{-height} || 480));
my $data = $self->getHistory;
if(defined $params{-font}){
$graph->set_title_font ($params{-font}, 12);
$graph->set_x_label_font($params{-font}, 10);
$graph->set_y_label_font($params{-font}, 10);
lib/AI/Genetic/Pro.pm view on Meta::CPAN
$params{legend2} || q/Mean value/,
$params{legend3} || q/Min value/,
);
$graph->set(
x_label_skip => int(($data->[0]->[-1]*4)/100),
x_labels_vertical => 1,
x_label_position => .5,
y_label_position => .5,
y_long_ticks => 1, # poziome linie
x_ticks => 1, # poziome linie
lib/AI/Genetic/Pro.pm view on Meta::CPAN
( $params{-logo} && -f $params{-logo} ? ( logo => $params{-logo} ) : ( ) )
);
my $gd = $graph->plot( [ [ 0..$#{$data->[0]} ], @$data ] ) or croak($@);
open(my $fh, '>', $params{-filename}) or croak($@);
binmode $fh;
print $fh $gd->png;
close $fh;
lib/AI/Genetic/Pro.pm view on Meta::CPAN
sub inject {
my ($self, $candidates) = @_;
for(@$candidates){
push @{$self->chromosomes},
AI::Genetic::Pro::Chromosome->new_from_data($self->_translations, $self->type, $self->_package, $_, $self->_fix_range);
$self->_fitness->{$#{$self->chromosomes}} = $self->fitness()->($self, $self->chromosomes->[-1]);
}
$self->_strict( [ ] );
$self->population( $self->population + scalar( @$candidates ) );
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/Image.pm view on Meta::CPAN
croak $response->{'content'};
}
my $reply = decode_json($response->{'content'});
return $reply->{'data'}[0]->{'url'};
}
__END__
=head1 NAME
view all matches for this distribution
view release on metacpan or search on metacpan
contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Library
General Public License (also called "this License"). Each licensee is
addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
d) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/Logic/AnswerSet.pm view on Meta::CPAN
my @out = AI::Logic::AnswerSet::singleExec("3col.txt","nodes.txt","edges.txt","-nofacts");
my @result = AI::Logic::AnswerSet::getAS(@out);
my @mappedAS = AI::Logic::AnswerSet::mapAS(@result);
The user can set some constraints on the data to be saved in the hashmap, such as predicates, or answer sets, or both.
my @mappedAS = AI::Logic::AnswerSet::mapAS(@result,@predicates,@answerSets);
For instance, think about the 3-colorability problem: imagine to
have the edges in the hashmap, and to print the edges contained in the third answer set
lib/AI/Logic/AnswerSet.pm view on Meta::CPAN
my @res = AI::Logic::AnswerSet::getAS(@output);
my @predicates = ("node","edge");
my @stats = AI::Logic::AnswerSet::statistics(\@res,\@predicates);
In this case the data structure returned is the same as the one returned by C<mapAS()>.
Hence, for each answer set (each element of the array of hashes), the hashmap will appear
like this:
{
node => 6
lib/AI/Logic/AnswerSet.pm view on Meta::CPAN
AI::Logic::AnswerSet::createNewFile($file,"b(3). b(4).");
=head3 addFacts
Quiclky adds facts to a file. Imagine to have some data(representing facts)
stored inside an array; just use this method to put them in a file and give it a name.
AI::Logic::AnswerSet::addFacts("villagers",\@villagers,">","villagersFile.txt");
In the example above, "villagers" will be the name of the facts; C<@villagers> is the array
containing the data; ">" is the file operator(will create a new file, in this case);
"villagersFile.txt" is the filename. The file will contain facts of the form "villagers(X)",
for each "X", appearing in the array C<@villagers>.
=head1 SEE ALSO
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/ML/Expr.pm view on Meta::CPAN
=cut
sub plot {
my ($x, $y, $theta, $file) = @_;
my @xdata = $x->vector_to_list();
my @ydata = $y->vector_to_list();
my @thetas = $theta->vector_to_list();
my $f = $thetas[0] . "+" . $thetas[1] . "*x";
#print STDERR "$_\n" for(@xdata);
#rint STDERR "$_\n" for(@ydata);
#print STDERR "$f\n";
#print STDERR "\n\nFILE == $file\n\n";
my $chart = Chart::Gnuplot->new(
output => $file,
title => "Nice one",
xlabel => "x",
ylabel => "y"
);
my $points = Chart::Gnuplot::DataSet->new(
xdata => \@xdata,
ydata => \@ydata,
style => "points"
);
my $func = Chart::Gnuplot::DataSet->new(
func => $f
lib/AI/ML/Expr.pm view on Meta::CPAN
title => "Cost",
xlabel => "Iter",
ylabel => "Cost"
);
$chart->png;
my $data = Chart::Gnuplot::DataSet->new(
xdata => \@iters,
ydata => \@costs,
style => "linespoints"
);
$chart->plot2d($data);
}
1;
view all matches for this distribution
view release on metacpan or search on metacpan
lib/AI/MXNet/Gluon/Contrib/NN/BasicLayers.pm view on Meta::CPAN
grad_stype=>'row_sparse', stype=>'row_sparse'));
}
method forward(GluonInput $x)
{
my $weight = $self->weight->row_sparse_data($x);
return AI::MXNet::NDArray->Embedding($x, $weight, { name=>'fwd', %{ $self->_kwargs } });
}
use overload '""' => sub {
my $self = shift;
view all matches for this distribution
view release on metacpan or search on metacpan
examples/image_classification.pl view on Meta::CPAN
use Getopt::Long qw(HelpMessage);
GetOptions(
## my Pembroke Welsh Corgi Kyuubi, enjoing Solar eclipse of August 21, 2017
'image=s' => \(my $image = 'http://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/'.
'gluon/dataset/kyuubi.jpg'),
'model=s' => \(my $model = 'resnet152_v2'),
'help' => sub { HelpMessage(0) },
) or HelpMessage(1);
## get a pretrained model (download parameters file if necessary)
my $net = get_model($model, pretrained => 1);
## ImageNet classes
my $fname = download('http://data.mxnet.io/models/imagenet/synset.txt');
my @text_labels = map { chomp; s/^\S+\s+//; $_ } IO::File->new($fname)->getlines;
## get the image from the disk or net
if($image =~ /^https/)
{
eval { require IO::Socket::SSL; };
die "Need to have IO::Socket::SSL installed for https images" if $@;
}
$image = $image =~ /^https?/ ? download($image) : $image;
# Following the conventional way of preprocessing ImageNet data:
# Resize the short edge into 256 pixes,
# And then perform a center crop to obtain a 224-by-224 image.
# The following code uses the image processing functions provided
# in the AI::MXNet::Image module.
view all matches for this distribution
view release on metacpan or search on metacpan
examples/calculator.pl view on Meta::CPAN
my($batch_size, $func) = @_;
# get samples
my $n = 16384;
## creates a pdl with $n rows and two columns with random
## floats in the range between 0 and 1
my $data = PDL->random(2, $n);
## creates the pdl with $n rows and one column with labels
## labels are floats that either sum or product, etc of
## two random values in each corresponding row of the data pdl
my $label = $func->($data->slice('0,:'), $data->slice('1,:'));
# partition into train/eval sets
my $edge = int($n / 8);
my $validation_data = $data->slice(":,0:@{[ $edge - 1 ]}");
my $validation_label = $label->slice(":,0:@{[ $edge - 1 ]}");
my $train_data = $data->slice(":,$edge:");
my $train_label = $label->slice(":,$edge:");
# build iterators around the sets
return(mx->io->NDArrayIter(
batch_size => $batch_size,
data => $train_data,
label => $train_label,
), mx->io->NDArrayIter(
batch_size => $batch_size,
data => $validation_data,
label => $validation_label,
));
}
## the network model
sub nn_fc {
my $data = mx->sym->Variable('data');
my $ln = mx->sym->exp(mx->sym->FullyConnected(
data => mx->sym->log($data),
num_hidden => 1,
));
my $wide = mx->sym->Concat($data, $ln);
my $fc = mx->sym->FullyConnected(
$wide,
num_hidden => 1
);
return mx->sym->MAERegressionOutput(data => $fc, name => 'softmax');
}
sub learn_function {
my(%args) = @_;
my $func = $args{func};
examples/calculator.pl view on Meta::CPAN
my($train_iter, $eval_iter) = samples($batch_size, $func);
my $sym = nn_fc();
## call as ./calculator.pl 1 to just print model and exit
if($ARGV[0]) {
my @dsz = @{$train_iter->data->[0][1]->shape};
my @lsz = @{$train_iter->label->[0][1]->shape};
my $shape = {
data => [ $batch_size, splice @dsz, 1 ],
softmax_label => [ $batch_size, splice @lsz, 1 ],
};
print mx->viz->plot_network($sym, shape => $shape)->graph->as_png;
exit;
}
examples/calculator.pl view on Meta::CPAN
my $model = mx->mod->Module(
symbol => $sym,
context => mx->cpu(),
);
$model->fit($train_iter,
eval_data => $eval_iter,
optimizer => 'adam',
optimizer_params => {
learning_rate => $args{lr}//0.01,
rescale_grad => 1/$batch_size,
lr_scheduler => AI::MXNet::FactorScheduler->new(
examples/calculator.pl view on Meta::CPAN
);
# refit the model for calling on 1 sample at a time
my $iter = mx->io->NDArrayIter(
batch_size => 1,
data => PDL->pdl([[ 0, 0 ]]),
label => PDL->pdl([[ 0 ]]),
);
$model->reshape(
data_shapes => $iter->provide_data,
label_shapes => $iter->provide_label,
);
# wrap a helper around making predictions
my ($arg_params) = $model->get_params;
examples/calculator.pl view on Meta::CPAN
}
return sub {
my($n, $m) = @_;
return $model->predict(mx->io->NDArrayIter(
batch_size => 1,
data => PDL->new([[ $n, $m ]]),
))->aspdl->list;
};
}
my $add = learn_function(func => sub {
view all matches for this distribution
view release on metacpan or search on metacpan
typedef MXSymbol *SymbolHandle;
/*! \brief handle to a AtomicSymbol */
typedef MXAtomicSymbol *AtomicSymbolHandle;
/*! \brief handle to an Executor */
typedef MXExecutor *ExecutorHandle;
/*! \brief handle a dataiter creator */
typedef MXDataIterCreator *DataIterCreator;
/*! \brief handle to a DataIterator */
typedef MXDataIter *DataIterHandle;
/*! \brief handle to KVStore */
typedef MXKVStore *KVStoreHandle;
int dev_id,
int delay_alloc,
NDArrayHandle *out);
/*!
* \brief create a NDArray with specified shape and data type
* \param shape the pointer to the shape
* \param ndim the dimension of the shape
* \param dev_type device type, specify device we want to take
* \param dev_id the device id of the specific device
* \param delay_alloc whether to delay allocation until
* the ndarray is first mutated
* \param dtype data type of created array
* \param out the returning handle
* \return 0 when success, -1 when failure happens
*/
int MXNDArrayCreateEx(const mx_uint *in,
mx_uint ndim,
const char*** out_array);
/*!
* \brief Perform a synchronize copy from a continugous CPU memory region.
*
* This function will call WaitToWrite before the copy is performed.
* This is useful to copy data from existing memory region that are
* not wrapped by NDArray(thus dependency not being tracked).
*
* \param handle the NDArray handle
* \param data the data source to copy from.
* \param size the memory size we want to copy from.
*/
int MXNDArraySyncCopyFromCPU(NDArrayHandle handle,
const void *in,
size_t size);
/*!
* \brief Perform a synchronize copy to a continugous CPU memory region.
*
* This function will call WaitToRead before the copy is performed.
* This is useful to copy data from existing memory region that are
* not wrapped by NDArray(thus dependency not being tracked).
*
* \param handle the NDArray handle
* \param data the data source to copy into.
* \param size the memory size we want to copy into.
*/
int MXNDArraySyncCopyToCPU(NDArrayHandle handle,
void *in,
size_t size);
/*!
* \brief Wait until all the pending writes with respect NDArray are finished.
* Always call this before read data out synchronizely.
* \param handle the NDArray handle
* \return 0 when success, -1 when failure happens
*/
int MXNDArrayWaitToRead(NDArrayHandle handle);
/*!
* \brief Wait until all the pending read/write with respect NDArray are finished.
* Always call this before write data into NDArray synchronizely.
* \param handle the NDArray handle
* \return 0 when success, -1 when failure happens
*/
int MXNDArrayWaitToWrite(NDArrayHandle handle);
/*!
NDArrayHandle *out);
/*!
* \brief get the shape of the array
* \param handle the handle to the ndarray
* \param out_dim the output dimension
* \param out_pdata pointer holder to get data pointer of the shape
* \return 0 when success, -1 when failure happens
*/
int MXNDArrayGetShape(NDArrayHandle handle,
mx_uint *out_dim,
const mx_uint **out_pdata);
/*!
* \brief get the content of the data in NDArray
* \param handle the handle to the ndarray
* \param out_pdata pointer holder to get pointer of data
* \return 0 when success, -1 when failure happens
*/
int MXNDArrayGetData(NDArrayHandle handle,
void **out_pdata);
/*!
* \brief get the type of the data in NDArray
* \param handle the handle to the ndarray
* \param out_dtype pointer holder to get type of data
* \return 0 when success, -1 when failure happens
*/
int MXNDArrayGetDType(NDArrayHandle handle,
int *out);
/*!
mx_uint num_wrt,
const char** in,
SymbolHandle* out);
/*!
* \brief infer shape of unknown input shapes given the known one.
* The shapes are packed into a CSR matrix represented by arg_ind_ptr and arg_shape_data
* The call will be treated as a kwargs call if key != nullptr or num_args==0, otherwise it is positional.
*
* \param sym symbol handle
* \param num_args numbe of input arguments.
* \param keys the key of keyword args (optional)
* \param arg_ind_ptr the head pointer of the rows in CSR
* \param arg_shape_data the content of the CSR
* \param in_shape_size sizeof the returning array of in_shapes
* \param in_shape_ndim returning array of shape dimensions of eachs input shape.
* \param in_shape_data returning array of pointers to head of the input shape.
* \param out_shape_size sizeof the returning array of out_shapes
* \param out_shape_ndim returning array of shape dimensions of eachs input shape.
* \param out_shape_data returning array of pointers to head of the input shape.
* \param aux_shape_size sizeof the returning array of aux_shapes
* \param aux_shape_ndim returning array of shape dimensions of eachs auxiliary shape.
* \param aux_shape_data returning array of pointers to head of the auxiliary shape.
* \param complete whether infer shape completes or more information is needed.
* \return 0 when success, -1 when failure happens
*/
int MXSymbolInferShape(SymbolHandle sym,
mx_uint num_args,
const char** in,
const mx_uint *in,
const mx_uint *in,
mx_uint *in_shape_size,
const mx_uint **in_shape_ndim,
const mx_uint ***in_shape_data,
mx_uint *out_shape_size,
const mx_uint **out_shape_ndim,
const mx_uint ***out_shape_data,
mx_uint *aux_shape_size,
const mx_uint **aux_shape_ndim,
const mx_uint ***aux_shape_data,
int *out);
/*!
* \brief partially infer shape of unknown input shapes given the known one.
*
* Return partially inferred results if not all shapes could be inferred.
* The shapes are packed into a CSR matrix represented by arg_ind_ptr and arg_shape_data
* The call will be treated as a kwargs call if key != nullptr or num_args==0, otherwise it is positional.
*
* \param sym symbol handle
* \param num_args numbe of input arguments.
* \param keys the key of keyword args (optional)
* \param arg_ind_ptr the head pointer of the rows in CSR
* \param arg_shape_data the content of the CSR
* \param in_shape_size sizeof the returning array of in_shapes
* \param in_shape_ndim returning array of shape dimensions of eachs input shape.
* \param in_shape_data returning array of pointers to head of the input shape.
* \param out_shape_size sizeof the returning array of out_shapes
* \param out_shape_ndim returning array of shape dimensions of eachs input shape.
* \param out_shape_data returning array of pointers to head of the input shape.
* \param aux_shape_size sizeof the returning array of aux_shapes
* \param aux_shape_ndim returning array of shape dimensions of eachs auxiliary shape.
* \param aux_shape_data returning array of pointers to head of the auxiliary shape.
* \param complete whether infer shape completes or more information is needed.
* \return 0 when success, -1 when failure happens
*/
int MXSymbolInferShapePartial(SymbolHandle sym,
mx_uint num_args,
const char** in,
const mx_uint *in,
const mx_uint *in,
mx_uint *in_shape_size,
const mx_uint **in_shape_ndim,
const mx_uint ***in_shape_data,
mx_uint *out_shape_size,
const mx_uint **out_shape_ndim,
const mx_uint ***out_shape_data,
mx_uint *aux_shape_size,
const mx_uint **aux_shape_ndim,
const mx_uint ***aux_shape_data,
int *out);
/*!
* \brief infer type of unknown input types given the known one.
* The types are packed into a CSR matrix represented by arg_ind_ptr and arg_type_data
* The call will be treated as a kwargs call if key != nullptr or num_args==0, otherwise it is positional.
*
* \param sym symbol handle
* \param num_args numbe of input arguments.
* \param keys the key of keyword args (optional)
* \param arg_type_data the content of the CSR
* \param in_type_size sizeof the returning array of in_types
* \param in_type_data returning array of pointers to head of the input type.
* \param out_type_size sizeof the returning array of out_types
* \param out_type_data returning array of pointers to head of the input type.
* \param aux_type_size sizeof the returning array of aux_types
* \param aux_type_data returning array of pointers to head of the auxiliary type.
* \param complete whether infer type completes or more information is needed.
* \return 0 when success, -1 when failure happens
*/
int MXSymbolInferType(SymbolHandle sym,
mx_uint num_args,
const char** in,
const int *in,
mx_uint *in_type_size,
const int **in_type_data,
mx_uint *out_type_size,
const int **out_type_data,
mx_uint *aux_type_size,
const int **aux_type_data,
int *out);
//--------------------------------------------
// Part 4: Executor interface
//--------------------------------------------
/*!
const mx_uint provided_grad_req_list_len,
const char** in, // provided_grad_req_names,
const char** in, // provided_grad_req_types,
const mx_uint num_provided_arg_shapes,
const char** in, // provided_arg_shape_names,
const mx_uint* in, // provided_arg_shape_data,
const mx_uint* in, // provided_arg_shape_idx,
const mx_uint num_provided_arg_dtypes,
const char** in, // provided_arg_dtype_names,
const int* in, // provided_arg_dtypes,
const mx_uint num_shared_arg_names,
mx_uint num_param,
const char **keys,
const char **vals,
DataIterHandle *out);
/*!
* \brief Get the detailed information about data iterator.
* \param creator the DataIterCreator.
* \param name The returned name of the creator.
* \param description The returned description of the symbol.
* \param num_args Number of arguments.
* \param arg_names Name of the arguments.
const char ***arg_names,
const char ***arg_type_infos,
const char ***arg_descriptions);
/*!
* \brief Free the handle to the IO module
* \param handle the handle pointer to the data iterator
* \return 0 when success, -1 when failure happens
*/
int MXDataIterFree(DataIterHandle handle);
/*!
* \brief Move iterator to next position
* \return 0 when success, -1 when failure happens
*/
int MXDataIterBeforeFirst(DataIterHandle handle);
/*!
* \brief Get the handle to the NDArray of underlying data
* \param handle the handle pointer to the data iterator
* \param out handle to underlying data NDArray
* \return 0 when success, -1 when failure happens
*/
int MXDataIterGetData(DataIterHandle handle,
NDArrayHandle *out);
/*!
* \brief Get the image index by array.
* \param handle the handle pointer to the data iterator
* \param out_index output index of the array.
* \param out_size output size of the array.
* \return 0 when success, -1 when failure happens
*/
int MXDataIterGetIndex(DataIterHandle handle,
uint64_t **out_index,
uint64_t *out_size);
/*!
* \brief Get the padding number in current data batch
* \param handle the handle pointer to the data iterator
* \param pad pad number ptr
* \return 0 when success, -1 when failure happens
*/
int MXDataIterGetPadNum(DataIterHandle handle,
int *out);
/*!
* \brief Get the handle to the NDArray of underlying label
* \param handle the handle pointer to the data iterator
* \param out the handle to underlying label NDArray
* \return 0 when success, -1 when failure happens
*/
int MXDataIterGetLabel(DataIterHandle handle,
NDArrayHandle *out);
view all matches for this distribution
view release on metacpan or search on metacpan
inc/Module/Install/Metadata.pm view on Meta::CPAN
#line 1
package Module::Install::Metadata;
use strict 'vars';
use Module::Install::Base;
use vars qw{$VERSION $ISCORE @ISA};
inc/Module/Install/Metadata.pm view on Meta::CPAN
sub read {
my $self = shift;
$self->include_deps( 'YAML', 0 );
require YAML;
my $data = YAML::LoadFile('META.yml');
# Call methods explicitly in case user has already set some values.
while ( my ( $key, $value ) = each %$data ) {
next unless $self->can($key);
if ( ref $value eq 'HASH' ) {
while ( my ( $module, $version ) = each %$value ) {
$self->can($key)->($self, $module => $version );
}
view all matches for this distribution
view release on metacpan or search on metacpan
0.08 = 0.07_01 2015-04-12
0.07_01 Apr 14 2012
- mention Hailo.pm in docs
- use 'unsigned int' as 32 bit data type
- mingw64 supported
0.07 = 0.06_01 Jul 12 2008
0.06_01 Jan 24 2008
- corrected documentation (typo found by ZOFFIX)
view all matches for this distribution
view release on metacpan or search on metacpan
bin/from-folder.pl view on Meta::CPAN
p @{[keys %$files,reverse @ARGV,$storage]};
__DATA__
our $c = AI::MicroStructure::Context->new(@ARGV);
$c->retrieveIndex($PWD."/t/docs"); #"/home/santex/data-hub/data-hub" structures=0 text=1 json=1
my $style = {};
$style->{explicit} = 1;
view all matches for this distribution