| 1 | # Licensed to the Apache Software Foundation (ASF) under one | ||
| 2 | # or more contributor license agreements. See the NOTICE file | ||
| 3 | # distributed with this work for additional information | ||
| 4 | # regarding copyright ownership. The ASF licenses this file | ||
| 5 | # to you under the Apache License, Version 2.0 (the | ||
| 6 | # "License"); you may not use this file except in compliance | ||
| 7 | # with the License. You may obtain a copy of the License at | ||
| 8 | # | ||
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
| 10 | # | ||
| 11 | # Unless required by applicable law or agreed to in writing, | ||
| 12 | # software distributed under the License is distributed on an | ||
| 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| 14 | # KIND, either express or implied. See the License for the | ||
| 15 | # specific language governing permissions and limitations | ||
| 16 | # under the License. | ||
| 17 | |||
| 18 | package AI::MXNet::Gluon::Data::Vision; | ||
| 19 | use AI::MXNet::NS; | ||
| 20 | |||
| 21 | package AI::MXNet::Gluon::Data::Vision::DownloadedDataSet; | ||
| 22 | use strict; | ||
| 23 | use warnings; | ||
| 24 | use File::Path qw(make_path); | ||
| 25 | use Archive::Tar; | ||
| 26 | use IO::Zlib; | ||
| 27 | use IO::File; | ||
| 28 | use Mouse; | ||
| 29 | use AI::MXNet::Function::Parameters; | ||
| 30 | has 'root' => (is => 'ro', isa => 'Str', required => 1); | ||
| 31 | has 'train' => (is => 'ro', isa => 'Bool', required => 1); | ||
| 32 | has 'transform' => (is => 'ro', isa => 'Maybe[CodeRef]'); | ||
| 33 | has [qw(data label)] => (is => 'rw', init_arg => undef); | ||
| 34 | extends 'AI::MXNet::Gluon::Data::Set'; | ||
| 35 | method python_constructor_arguments() { ['root', 'train', 'transform'] } | ||
| 36 | |||
| 37 | sub BUILD | ||
| 38 | { | ||
| 39 | my $self = shift; | ||
| 40 | my $root = $self->root; | ||
| 41 | $root =~ s/~/$ENV{HOME}/; | ||
| 42 | if(not -d $root) | ||
| 43 | { | ||
| 44 | make_path($root); | ||
| 45 | } | ||
| 46 | $self->_get_data; | ||
| 47 | } | ||
| 48 | |||
| 49 | method at(Index $idx) | ||
| 50 | { | ||
| 51 | if(defined $self->transform) | ||
| 52 | { | ||
| 53 | return [$self->transform->($self->data->at($idx), $self->label->at($idx))]; | ||
| 54 | } | ||
| 55 | return [$self->data->at($idx), $self->label->at($idx)]; | ||
| 56 | } | ||
| 57 | |||
| 58 | method len() { $self->label->len } | ||
| 59 | method _get_data() { confess("Not Implemented") } | ||
| 60 | |||
| 61 | package AI::MXNet::Gluon::Data::Vision::DownloadedDataSet::MNIST; | ||
| 62 | use Mouse; | ||
| 63 | use AI::MXNet::Gluon::Utils qw(download); | ||
| 64 | use AI::MXNet::Base; | ||
| 65 | extends 'AI::MXNet::Gluon::Data::Vision::DownloadedDataSet'; | ||
| 66 | |||
| 67 | =head1 NAME | ||
| 68 | |||
| 69 | AI::MXNet::Gluon::Data::Vision::DownloadedDataSet::MNIST | ||
| 70 | =cut | ||
| 71 | |||
| 72 | =head1 DESCRIPTION | ||
| 73 | |||
| 74 | MNIST handwritten digits dataset from `http://yann.lecun.com/exdb/mnist`_. | ||
| 75 | |||
| 76 | Each sample is an image (in 3D NDArray) with shape (28, 28, 1). | ||
| 77 | |||
| 78 | Parameters | ||
| 79 | ---------- | ||
| 80 | root : str | ||
| 81 | Path to temp folder for storing data. | ||
| 82 | Defaults to ~/.mxnet/datasets/mnist | ||
| 83 | train : bool | ||
| 84 | Whether to load the training or testing set. | ||
| 85 | Defaults to True | ||
| 86 | transform : function | ||
| 87 | A user defined callback that transforms each instance. For example: | ||
| 88 | |||
| 89 | transform => sub { my ($data, $label) = @_; return ($data->astype('float32')/255, $label) } | ||
| 90 | =cut | ||
| 91 | |||
| 92 | has [qw/_base_url _train_data _train_label _test_data _test_label/] => (is => 'rw'); | ||
| 93 | has '+root' => (default => '~/.mxnet/datasets/mnist'); | ||
| 94 | has '+train' => (default => 1); | ||
| 95 | has '_base_url' => (is => 'ro', default => 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/dataset/mnist/'); | ||
| 96 | has '_train_data' => (is => 'ro', default => sub { ['train-images-idx3-ubyte.gz', | ||
| 97 | '6c95f4b05d2bf285e1bfb0e7960c31bd3b3f8a7d'] }); | ||
| 98 | has '_train_label' => (is => 'ro', default => sub { ['train-labels-idx1-ubyte.gz', | ||
| 99 | '2a80914081dc54586dbdf242f9805a6b8d2a15fc'] }); | ||
| 100 | has '_test_data' => (is => 'ro', default => sub { ['t10k-images-idx3-ubyte.gz', | ||
| 101 | 'c3a25af1f52dad7f726cce8cacb138654b760d48'] }); | ||
| 102 | has '_test_label' => (is => 'ro', default => sub { ['t10k-labels-idx1-ubyte.gz', | ||
| 103 | '763e7fa3757d93b0cdec073cef058b2004252c17'] }); | ||
| 104 | |||
| 105 | method _get_data() | ||
| 106 | { | ||
| 107 | my ($data, $label); | ||
| 108 | if($self->train) | ||
| 109 | { | ||
| 110 | ($data, $label) = ($self->_train_data, $self->_train_label); | ||
| 111 | } | ||
| 112 | else | ||
| 113 | { | ||
| 114 | ($data, $label) = ($self->_test_data, $self->_test_label); | ||
| 115 | } | ||
| 116 | my $data_file = download($self->_base_url . $data->[0], path => $self->root, | ||
| 117 | sha1_hash => $data->[1]); | ||
| 118 | my $label_file = download($self->_base_url . $label->[0], path => $self->root, | ||
| 119 | sha1_hash => $label->[1]); | ||
| 120 | my $fh = new IO::Zlib; | ||
| 121 | my ($l, $d); | ||
| 122 | if ($fh->open($label_file, "rb")) | ||
| 123 | { | ||
| 124 | $fh->read($l, 100_000_000); | ||
| 125 | $l = substr($l, 8); | ||
| 126 | my $p = PDL->new_from_specification(PDL::Type->new(0), length($l)); | ||
| 127 | ${$p->get_dataref} = $l; | ||
| 128 | $p->upd_data; | ||
| 129 | $l = $p; | ||
| 130 | $fh->close; | ||
| 131 | $l = AI::MXNet::NDArray->array($l, dtype => 'int32')->aspdl; | ||
| 132 | } | ||
| 133 | if ($fh->open($data_file, "rb")) | ||
| 134 | { | ||
| 135 | $fh->read($d, 100_000_000); | ||
| 136 | $d = substr($d, 16); | ||
| 137 | my $p = PDL->new_from_specification(PDL::Type->new(0), length($d)); | ||
| 138 | ${$p->get_dataref} = $d; | ||
| 139 | $p->upd_data; | ||
| 140 | $d = $p; | ||
| 141 | $fh->close; | ||
| 142 | $d->reshape(1, 28, 28, $l->dim(-1)); | ||
| 143 | } | ||
| 144 | $self->data(AI::MXNet::NDArray->array($d, dtype => 'uint8')); | ||
| 145 | $self->label($l); | ||
| 146 | } | ||
| 147 | |||
| 148 | __PACKAGE__->register('AI::MXNet::Gluon::Data::Vision'); | ||
| 149 | |||
| 150 | package AI::MXNet::Gluon::Data::Vision::DownloadedDataSet::FashionMNIST; | ||
| 151 | use Mouse; | ||
| 152 | |||
| 153 | =head1 NAME | ||
| 154 | |||
| 155 | AI::MXNet::Gluon::Data::Vision::DownloadedDataSet::FashionMNIST | ||
| 156 | =cut | ||
| 157 | |||
| 158 | =head1 DESCRIPTION | ||
| 159 | |||
| 160 | A dataset of Zalando's article images consisting of fashion products, | ||
| 161 | a drop-in replacement of the original MNIST dataset from | ||
| 162 | `https://github.com/zalandoresearch/fashion-mnist`_. | ||
| 163 | |||
| 164 | Each sample is an image (in 3D NDArray) with shape (28, 28, 1). | ||
| 165 | |||
| 166 | Parameters | ||
| 167 | ---------- | ||
| 168 | root : str | ||
| 169 | Path to temp folder for storing data. | ||
| 170 | Defaults to ~/.mxnet/datasets/mnist | ||
| 171 | train : bool | ||
| 172 | Whether to load the training or testing set. | ||
| 173 | Defaults to True | ||
| 174 | transform : function | ||
| 175 | A user defined callback that transforms each instance. For example: | ||
| 176 | |||
| 177 | transform => sub { my ($data, $label) = @_; return ($data->astype('float32')/255, $label) } | ||
| 178 | =cut | ||
| 179 | |||
| 180 | extends 'AI::MXNet::Gluon::Data::Vision::DownloadedDataSet::MNIST'; | ||
| 181 | has '+root' => (default => '~/.mxnet/datasets/fashion-mnist'); | ||
| 182 | has '+_base_url' => (default => 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/dataset/fashion-mnist/'); | ||
| 183 | has '+_train_data' => (default => sub { ['train-images-idx3-ubyte.gz', | ||
| 184 | '0cf37b0d40ed5169c6b3aba31069a9770ac9043d'] }); | ||
| 185 | has '+_train_label' => (default => sub { ['train-labels-idx1-ubyte.gz', | ||
| 186 | '236021d52f1e40852b06a4c3008d8de8aef1e40b'] }); | ||
| 187 | has '+_test_data' => (default => sub { ['t10k-images-idx3-ubyte.gz', | ||
| 188 | '626ed6a7c06dd17c0eec72fa3be1740f146a2863'] }); | ||
| 189 | has '+_test_label' => (default => sub { ['t10k-labels-idx1-ubyte.gz', | ||
| 190 | '17f9ab60e7257a1620f4ad76bbbaf857c3920701'] }); | ||
| 191 | |||
| 192 | __PACKAGE__->register('AI::MXNet::Gluon::Data::Vision'); | ||
| 193 | |||
| 194 | package AI::MXNet::Gluon::Data::Vision::DownloadedDataSet::CIFAR10; | ||
| 195 | use Mouse; | ||
| 196 | use AI::MXNet::Gluon::Utils qw(download); | ||
| 197 | use AI::MXNet::Base; | ||
| 198 | use Cwd; | ||
| 199 | extends 'AI::MXNet::Gluon::Data::Vision::DownloadedDataSet'; | ||
| 200 | |||
| 201 | =head1 NAME | ||
| 202 | |||
| 203 | AI::MXNet::Gluon::Data::Vision::DownloadedDataSet::CIFAR10 | ||
| 204 | =cut | ||
| 205 | |||
| 206 | =head1 DESCRIPTION | ||
| 207 | |||
| 208 | CIFAR10 image classification dataset from `https://www.cs.toronto.edu/~kriz/cifar.html`_. | ||
| 209 | |||
| 210 | Each sample is an image (in 3D NDArray) with shape (32, 32, 1). | ||
| 211 | |||
| 212 | Parameters | ||
| 213 | ---------- | ||
| 214 | root : str | ||
| 215 | Path to temp folder for storing data. | ||
| 216 | train : bool | ||
| 217 | Whether to load the training or testing set. | ||
| 218 | transform : function | ||
| 219 | A user defined callback that transforms each instance. For example: | ||
| 220 | |||
| 221 | transform => sub { my ($data, $label) = @_; return ($data->astype('float32')/255, $label) } | ||
| 222 | =cut | ||
| 223 | has '+root' => (default => '~/.mxnet/datasets/cifar10'); | ||
| 224 | has '+train' => (default => 1); | ||
| 225 | has '_file_hashes' => (is => 'ro', default => sub { +{ | ||
| 226 | qw/data_batch_1.bin aadd24acce27caa71bf4b10992e9e7b2d74c2540 | ||
| 227 | data_batch_2.bin c0ba65cce70568cd57b4e03e9ac8d2a5367c1795 | ||
| 228 | data_batch_3.bin 1dd00a74ab1d17a6e7d73e185b69dbf31242f295 | ||
| 229 | data_batch_4.bin aab85764eb3584312d3c7f65fd2fd016e36a258e | ||
| 230 | data_batch_5.bin 26e2849e66a845b7f1e4614ae70f4889ae604628 | ||
| 231 | test_batch.bin 67eb016db431130d61cd03c7ad570b013799c88c/ | ||
| 232 | } }); | ||
| 233 | |||
| 234 | method _read_batch(Str $filename) | ||
| 235 | { | ||
| 236 | my $data = join('', IO::File->new($filename)->getlines); | ||
| 237 | $data = PDL->new_from_specification(PDL::Type->new(0), length($data))->reshape(3073, length($data)/3073); | ||
| 238 | $data = AI::MXNet::NDArray->array($data, dtype => 'uint8'); | ||
| 239 | return ( | ||
| 240 | $data->slice('X', [1, -1])->sever->reshape([-1, 3, 32, 32])->transpose([0, 2, 3, 1]), | ||
| 241 | $data->slice('X', 0)->astype('int32') | ||
| 242 | ); | ||
| 243 | } | ||
| 244 | |||
| 245 | method _get_data() | ||
| 246 | { | ||
| 247 | my @file_paths = map { [$_, join('/', $self->root, 'cifar-10-batches-bin/', $_)] } keys %{ $self->_file_hashes }; | ||
| 248 | if(grep { not -f $_->[1] or not check_sha1($_->[1], $self->_file_hashes->{ $_->[0] }) } @file_paths) | ||
| 249 | { | ||
| 250 | my $filename = download( | ||
| 251 | 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/dataset/cifar10/cifar-10-binary.tar.gz', | ||
| 252 | path => $self->root, | ||
| 253 | sha1_hash => 'fab780a1e191a7eda0f345501ccd62d20f7ed891' | ||
| 254 | ); | ||
| 255 | my $tar = Archive::Tar->new($filename); | ||
| 256 | my $cwd = cwd(); | ||
| 257 | chdir($self->root); | ||
| 258 | $tar->extract; | ||
| 259 | chdir($cwd); | ||
| 260 | } | ||
| 261 | my ($data, $label); | ||
| 262 | if($self->train) | ||
| 263 | { | ||
| 264 | my (@data, @label); | ||
| 265 | for my $i (1..5) | ||
| 266 | { | ||
| 267 | my $filename = join('/', $self->root, "data_batch_$i.bin"); | ||
| 268 | my ($data, $label) = $self->_read_batch($filename); | ||
| 269 | push @data, $data; | ||
| 270 | push @label, $label; | ||
| 271 | } | ||
| 272 | $data = AI::MXNet::NDArray->concatenate(\@data); | ||
| 273 | $label = AI::MXNet::NDArray->concatenate(\@label); | ||
| 274 | } | ||
| 275 | else | ||
| 276 | { | ||
| 277 | my $filename = join('/', $self->root, "test_batch.bin"); | ||
| 278 | ($data, $label) = $self->_read_batch($filename); | ||
| 279 | } | ||
| 280 | $self->data(\@{$data}); | ||
| 281 | $self->label($label->aspdl); | ||
| 282 | } | ||
| 283 | |||
| 284 | __PACKAGE__->register('AI::MXNet::Gluon::Data::Vision'); | ||
| 285 | |||
| 286 | package AI::MXNet::Gluon::Data::Vision::RecordFileSet::ImageRecordDataset; | ||
| 287 | use Mouse; | ||
| 288 | extends 'AI::MXNet::Gluon::Data::RecordFileSet'; | ||
| 289 | =head1 NAME | ||
| 290 | |||
| 291 | AI::MXNet::Gluon::Data::Vision::RecordFileSet::ImageRecordDataset | ||
| 292 | =cut | ||
| 293 | |||
| 294 | =head1 DESCRIPTION | ||
| 295 | |||
| 296 | A dataset wrapping over a RecordIO file containing images. | ||
| 297 | |||
| 298 | Each sample is an image and its corresponding label. | ||
| 299 | |||
| 300 | Parameters | ||
| 301 | ---------- | ||
| 302 | filename : str | ||
| 303 | Path to rec file. | ||
| 304 | flag : {0, 1}, default 1 | ||
| 305 | If 0, always convert images to greyscale. | ||
| 306 | |||
| 307 | If 1, always convert images to colored (RGB). | ||
| 308 | transform : function | ||
| 309 | A user defined callback that transforms each instance. For example: | ||
| 310 | =cut | ||
| 311 | has 'flag' => (is => 'rw', isa => 'Bool', default => 1); | ||
| 312 | has 'transform' => (is => 'rw', isa => 'Maybe[CodeRef]'); | ||
| 313 | |||
| 314 | method at(Int $idx) | ||
| 315 | { | ||
| 316 | my $record = $self->SUPER::at($idx); | ||
| 317 | my ($header, $img) = AI::MXNet::RecordIO->unpack($record); | ||
| 318 | if(defined $self->transform) | ||
| 319 | { | ||
| 320 | my $data = [AI::MXNet::Image->imdecode($img)]; | ||
| 321 | return [$self->transform->( | ||
| 322 | AI::MXNet::Image->imdecode($img, flag => $self->flag), $header->label | ||
| 323 | )]; | ||
| 324 | } | ||
| 325 | return [AI::MXNet::Image->imdecode($img, flag => $self->flag), $header->label]; | ||
| 326 | } | ||
| 327 | |||
| 328 | __PACKAGE__->register('AI::MXNet::Gluon::Data::Vision'); | ||
| 329 | |||
| 330 | package AI::MXNet::Gluon::Data::Vision::Set::ImageFolderDataset; | ||
| 331 | use Mouse; | ||
| 332 | extends 'AI::MXNet::Gluon::Data::Set'; | ||
| 333 | =head1 NAME | ||
| 334 | |||
| 335 | AI::MXNet::Gluon::Data::Vision::ImageFolderDataset | ||
| 336 | =cut | ||
| 337 | |||
| 338 | =head1 DESCRIPTION | ||
| 339 | |||
| 340 | A dataset for loading image files stored in a folder structure like:: | ||
| 341 | |||
| 342 | root/car/0001.jpg | ||
| 343 | root/car/xxxa.jpg | ||
| 344 | root/car/yyyb.jpg | ||
| 345 | root/bus/123.jpg | ||
| 346 | root/bus/023.jpg | ||
| 347 | root/bus/wwww.jpg | ||
| 348 | |||
| 349 | Parameters | ||
| 350 | ---------- | ||
| 351 | root : str | ||
| 352 | Path to root directory. | ||
| 353 | flag : {0, 1}, default 1 | ||
| 354 | If 0, always convert loaded images to greyscale (1 channel). | ||
| 355 | If 1, always convert loaded images to colored (3 channels). | ||
| 356 | transform : callable | ||
| 357 | A function that takes data and label and transforms them:: | ||
| 358 | |||
| 359 | transform = lambda data, label: (data.astype(np.float32)/255, label) | ||
| 360 | |||
| 361 | Attributes | ||
| 362 | ---------- | ||
| 363 | synsets : list | ||
| 364 | List of class names. `synsets[i]` is the name for the integer label `i` | ||
| 365 | items : list of tuples | ||
| 366 | List of all images in (filename, label) pairs. | ||
| 367 | =cut | ||
| 368 | has 'root' => (is => 'rw', isa => 'Str'); | ||
| 369 | has 'flag' => (is => 'rw', isa => 'Bool', default => 1); | ||
| 370 | has 'transform' => (is => 'rw', isa => 'Maybe[CodeRef]'); | ||
| 371 | has [qw/exts | ||
| 372 | synsets | ||
| 373 | items/] => (is => 'rw', init_arg => undef); | ||
| 374 | method python_constructor_arguments() { ['root', 'flag', 'transform'] } | ||
| 375 | |||
| 376 | sub BUILD | ||
| 377 | { | ||
| 378 | my $self = shift; | ||
| 379 | my $root = $self->root; | ||
| 380 | $root =~ s/~/$ENV{HOME}/; | ||
| 381 | $self->root($root); | ||
| 382 | $self->exts({'.jpg', 1, '.jpeg', 1, '.png', 1}); | ||
| 383 | $self->list_images($self->root); | ||
| 384 | } | ||
| 385 | |||
| 386 | method list_images(Str $root) | ||
| 387 | { | ||
| 388 | $self->synsets([]); | ||
| 389 | $self->items([]); | ||
| 390 | |||
| 391 | for my $path (sort(glob("$root/*"))) | ||
| 392 | { | ||
| 393 | my $folder = $path; | ||
| 394 | $folder =~ s,^.+/,,; | ||
| 395 | if(not -d $path) | ||
| 396 | { | ||
| 397 | AI::MXNet::Logging->warning("Ignoring %s, which is not a directory.", $folder); | ||
| 398 | next; | ||
| 399 | } | ||
| 400 | my $label = @{ $self->synsets }; | ||
| 401 | push @{ $self->synsets }, $folder; | ||
| 402 | for my $filename (sort(glob("$path/*"))) | ||
| 403 | { | ||
| 404 | my ($ext) = $filename =~ /(\.[^\.]+)$/; | ||
| 405 | if(not $ext or not exists $self->exts->{lc $ext}) | ||
| 406 | { | ||
| 407 | AI::MXNet::Logging->warning( | ||
| 408 | 'Ignoring %s of type %s. Only support .jpg, .jpeg, .png', | ||
| 409 | $filename, $ext//'undef' | ||
| 410 | ); | ||
| 411 | next; | ||
| 412 | } | ||
| 413 | push @{ $self->items }, [$filename, AI::MXNet::NDArray->array([$label], dtype => 'int32')->aspdl]; | ||
| 414 | } | ||
| 415 | } | ||
| 416 | } | ||
| 417 | |||
| 418 | method at(Int $idx) | ||
| 419 | { | ||
| 420 | my $img = AI::MXNet::Image->imread($self->items->[$idx][0], flag => $self->flag); | ||
| 421 | my $label = $self->items->[$idx][1]; | ||
| 422 | if(defined $self->transform) | ||
| 423 | { | ||
| 424 | return [$self->transform->($img, $label)]; | ||
| 425 | } | ||
| 426 | return [$img, $label]; | ||
| 427 | } | ||
| 428 | |||
| 429 | method len() | ||
| 430 | { | ||
| 431 | return scalar(@{ $self->items }); | ||
| 432 | } | ||
| 433 | |||
| 434 | __PACKAGE__->register('AI::MXNet::Gluon::Data::Vision'); | ||
| 435 | |||
| 436 | 1; |