AI-MXNet
view release on metacpan or search on metacpan
lib/AI/MXNet/Initializer.pm view on Meta::CPAN
forget_bias: float,a bias for the forget gate.
Jozefowicz et al. 2015 recommends setting this to 1.0.
=cut
use Mouse;
extends 'AI::MXNet::Initializer';
has 'forget_bias' => (is => 'ro', isa => 'Num', required => 1);
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
$arr .= 0;
# in the case of LSTMCell the forget gate is the second
# gate of the 4 LSTM gates, we modify the according values.
my $num_hidden = int($arr->shape->[0] / 4);
$arr->slice([$num_hidden, 2*$num_hidden-1]) .= $self->forget_bias;
}
__PACKAGE__->register;
package AI::MXNet::FusedRNN;
use Mouse;
use JSON::PP;
extends 'AI::MXNet::Initializer';
=head1 NAME
AI::MXNet::FusedRNN - Custom initializer for fused RNN cells.
=cut
=head1 DESCRIPTION
Initializes parameters for fused rnn layer.
Parameters
----------
init : Initializer
initializer applied to unpacked weights.
All parameters below must be exactly the same as ones passed to the
FusedRNNCell constructor.
num_hidden : int
num_layers : int
mode : str
bidirectional : bool
forget_bias : float
=cut
has 'init' => (is => 'rw', isa => 'Str|AI::MXNet::Initializer', required => 1);
has 'forget_bias' => (is => 'ro', isa => 'Num', default => 1);
has [qw/num_hidden
num_layers/] => (is => 'ro', isa => 'Int', required => 1);
has 'mode' => (is => 'ro', isa => 'Str', required => 1);
has 'bidirectional' => (is => 'ro', isa => 'Bool', default => 0);
sub BUILD
{
my $self = shift;
if(not blessed $self->init)
{
my ($klass, $kwargs);
eval {
($klass, $kwargs) = @{ decode_json($self->init) };
};
confess("FusedRNN failed to init $@") if $@;
$self->init($self->get_init_registry->{ lc $klass }->new(%$kwargs));
}
}
method _init_weight($name, $arr)
{
my $cell = AI::MXNet::RNN::FusedCell->new(
num_hidden => $self->num_hidden,
num_layers => $self->num_layers,
mode => $self->mode,
bidirectional => $self->bidirectional,
forget_bias => $self->forget_bias,
prefix => ''
);
my $args = $cell->unpack_weights({ parameters => $arr });
for my $name (keys %{ $args })
{
my $desc = AI::MXNet::InitDesc->new(name => $name);
# for lstm bias, we use a custom initializer
# which adds a bias to the forget gate
if($self->mode eq 'lstm' and $name =~ /f_bias$/)
{
$args->{$name} .= $self->forget_bias;
}
else
{
&{$self->init}($desc, $args->{$name});
}
}
$arr .= $cell->pack_weights($args)->{parameters};
}
__PACKAGE__->register;
1;
( run in 0.755 second using v1.01-cache-2.11-cpan-acf6aa7dc9e )