From 32baa520bf7efcb426883f44c69a33b06062aa81 Mon Sep 17 00:00:00 2001 From: G-Dragon-Liu <1294693043@qq.com> Date: Thu, 19 Aug 2021 10:23:15 +0000 Subject: [PATCH] [feat][assistant][I3J6V2] add new data operator EMnist --- .../ccsrc/minddata/dataset/api/datasets.cc | 28 + .../engine/ir/datasetops/source/bindings.cc | 12 + .../engine/datasetops/source/CMakeLists.txt | 1 + .../engine/datasetops/source/emnist_op.cc | 146 ++++++ .../engine/datasetops/source/emnist_op.h | 84 +++ .../engine/ir/datasetops/dataset_node.h | 1 + .../ir/datasetops/source/CMakeLists.txt | 3 +- .../ir/datasetops/source/emnist_node.cc | 121 +++++ .../engine/ir/datasetops/source/emnist_node.h | 111 ++++ .../dataset/include/dataset/datasets.h | 87 ++++ .../dataset/include/dataset/samplers.h | 1 + mindspore/dataset/engine/datasets.py | 134 ++++- mindspore/dataset/engine/validators.py | 35 +- tests/ut/cpp/dataset/CMakeLists.txt | 1 + .../cpp/dataset/c_api_dataset_emnist_test.cc | 368 ++++++++++++++ .../emnist-byclass-train-images-idx3-ubyte | Bin 0 -> 7856 bytes .../emnist-byclass-train-labels-idx1-ubyte | Bin 0 -> 18 bytes .../emnist-mnist-test-images-idx3-ubyte | Bin 0 -> 7856 bytes .../emnist-mnist-test-labels-idx1-ubyte | Bin 0 -> 18 bytes .../emnist-mnist-train-images-idx3-ubyte | Bin 0 -> 7856 bytes .../emnist-mnist-train-labels-idx1-ubyte | Bin 0 -> 18 bytes .../ut/python/dataset/test_datasets_emnist.py | 481 ++++++++++++++++++ 22 files changed, 1611 insertions(+), 3 deletions(-) create mode 100644 mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc create mode 100644 mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.h create mode 100644 mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/emnist_node.cc create mode 100644 mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/emnist_node.h create mode 100644 tests/ut/cpp/dataset/c_api_dataset_emnist_test.cc create mode 100644 tests/ut/data/dataset/testEMnistDataset/emnist-byclass-train-images-idx3-ubyte create mode 100644 tests/ut/data/dataset/testEMnistDataset/emnist-byclass-train-labels-idx1-ubyte create mode 100644 tests/ut/data/dataset/testEMnistDataset/emnist-mnist-test-images-idx3-ubyte create mode 100644 tests/ut/data/dataset/testEMnistDataset/emnist-mnist-test-labels-idx1-ubyte create mode 100644 tests/ut/data/dataset/testEMnistDataset/emnist-mnist-train-images-idx3-ubyte create mode 100644 tests/ut/data/dataset/testEMnistDataset/emnist-mnist-train-labels-idx1-ubyte create mode 100644 tests/ut/python/dataset/test_datasets_emnist.py diff --git a/mindspore/ccsrc/minddata/dataset/api/datasets.cc b/mindspore/ccsrc/minddata/dataset/api/datasets.cc index 639641d711..8c78c7b45f 100644 --- a/mindspore/ccsrc/minddata/dataset/api/datasets.cc +++ b/mindspore/ccsrc/minddata/dataset/api/datasets.cc @@ -96,6 +96,7 @@ #include "minddata/dataset/engine/ir/datasetops/source/coco_node.h" #include "minddata/dataset/engine/ir/datasetops/source/csv_node.h" #include "minddata/dataset/engine/ir/datasetops/source/div2k_node.h" +#include "minddata/dataset/engine/ir/datasetops/source/emnist_node.h" #include "minddata/dataset/engine/ir/datasetops/source/flickr_node.h" #include "minddata/dataset/engine/ir/datasetops/source/image_folder_node.h" #include "minddata/dataset/engine/ir/datasetops/source/random_node.h" @@ -1042,6 +1043,33 @@ DIV2KDataset::DIV2KDataset(const std::vector &dataset_dir, const std::vect ir_node_ = std::static_pointer_cast(ds); } +EMnistDataset::EMnistDataset(const std::vector &dataset_dir, const std::vector &name, + const std::vector &usage, const std::shared_ptr &sampler, + const std::shared_ptr &cache) { + auto sampler_obj = sampler ? sampler->Parse() : nullptr; + auto ds = std::make_shared(CharToString(dataset_dir), CharToString(name), CharToString(usage), + sampler_obj, cache); + ir_node_ = std::static_pointer_cast(ds); +} + +EMnistDataset::EMnistDataset(const std::vector &dataset_dir, const std::vector &name, + const std::vector &usage, const Sampler *sampler, + const std::shared_ptr &cache) { + auto sampler_obj = sampler ? sampler->Parse() : nullptr; + auto ds = std::make_shared(CharToString(dataset_dir), CharToString(name), CharToString(usage), + sampler_obj, cache); + ir_node_ = std::static_pointer_cast(ds); +} + +EMnistDataset::EMnistDataset(const std::vector &dataset_dir, const std::vector &name, + const std::vector &usage, const std::reference_wrapper sampler, + const std::shared_ptr &cache) { + auto sampler_obj = sampler.get().Parse(); + auto ds = std::make_shared(CharToString(dataset_dir), CharToString(name), CharToString(usage), + sampler_obj, cache); + ir_node_ = std::static_pointer_cast(ds); +} + FlickrDataset::FlickrDataset(const std::vector &dataset_dir, const std::vector &annotation_file, bool decode, const std::shared_ptr &sampler, const std::shared_ptr &cache) { diff --git a/mindspore/ccsrc/minddata/dataset/api/python/bindings/dataset/engine/ir/datasetops/source/bindings.cc b/mindspore/ccsrc/minddata/dataset/api/python/bindings/dataset/engine/ir/datasetops/source/bindings.cc index 903d378826..121da63ee8 100644 --- a/mindspore/ccsrc/minddata/dataset/api/python/bindings/dataset/engine/ir/datasetops/source/bindings.cc +++ b/mindspore/ccsrc/minddata/dataset/api/python/bindings/dataset/engine/ir/datasetops/source/bindings.cc @@ -33,6 +33,7 @@ #include "minddata/dataset/engine/ir/datasetops/source/coco_node.h" #include "minddata/dataset/engine/ir/datasetops/source/csv_node.h" #include "minddata/dataset/engine/ir/datasetops/source/div2k_node.h" +#include "minddata/dataset/engine/ir/datasetops/source/emnist_node.h" #include "minddata/dataset/engine/ir/datasetops/source/flickr_node.h" #include "minddata/dataset/engine/ir/datasetops/source/generator_node.h" #include "minddata/dataset/engine/ir/datasetops/source/image_folder_node.h" @@ -152,6 +153,17 @@ PYBIND_REGISTER(DIV2KNode, 2, ([](const py::module *m) { })); })); +PYBIND_REGISTER(EMnistNode, 2, ([](const py::module *m) { + (void)py::class_>(*m, "EMnistNode", + "to create an EMnistNode") + .def(py::init([](std::string dataset_dir, std::string name, std::string usage, py::handle sampler) { + auto emnist = + std::make_shared(dataset_dir, name, usage, toSamplerObj(sampler), nullptr); + THROW_IF_ERROR(emnist->ValidateParams()); + return emnist; + })); + })); + PYBIND_REGISTER( FlickrNode, 2, ([](const py::module *m) { (void)py::class_>(*m, "FlickrNode", "to create a FlickrNode") diff --git a/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/CMakeLists.txt b/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/CMakeLists.txt index 07ad602463..43e1e9974a 100644 --- a/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/CMakeLists.txt +++ b/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/CMakeLists.txt @@ -22,6 +22,7 @@ set(DATASET_ENGINE_DATASETOPS_SOURCE_SRC_FILES div2k_op.cc flickr_op.cc qmnist_op.cc + emnist_op.cc ) set(DATASET_ENGINE_DATASETOPS_SOURCE_SRC_FILES diff --git a/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc b/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc new file mode 100644 index 0000000000..1812b089e9 --- /dev/null +++ b/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.cc @@ -0,0 +1,146 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "minddata/dataset/engine/datasetops/source/emnist_op.h" + +#include +#include +#include +#include +#include + +#include "debug/common.h" +#include "minddata/dataset/core/config_manager.h" +#include "minddata/dataset/core/tensor_shape.h" +#include "minddata/dataset/engine/datasetops/source/sampler/sequential_sampler.h" +#include "minddata/dataset/engine/execution_tree.h" +#include "utils/file_utils.h" +#include "utils/ms_utils.h" + +namespace mindspore { +namespace dataset { +EMnistOp::EMnistOp(const std::string &name, const std::string &usage, int32_t num_workers, + const std::string &folder_path, int32_t queue_size, std::unique_ptr data_schema, + std::shared_ptr sampler) + : MnistOp(usage, num_workers, folder_path, queue_size, std::move(data_schema), std::move(sampler)), name_(name) {} + +void EMnistOp::Print(std::ostream &out, bool show_all) const { + if (!show_all) { + // Call the super class for displaying any common 1-liner info. + ParallelOp::Print(out, show_all); + // Then show any custom derived-internal 1-liner info for this op. + out << "\n"; + } else { + // Call the super class for displaying any common detailed info. + ParallelOp::Print(out, show_all); + // Then show any custom derived-internal stuff. + out << "\nNumber of rows:" << num_rows_ << "\n" + << DatasetName(true) << " directory: " << folder_path_ << "\nName: " << name_ << "\nUsage: " << usage_ + << "\n\n"; + } +} + +Status EMnistOp::WalkAllFiles() { + const std::string img_ext = "-images-idx3-ubyte"; + const std::string lbl_ext = "-labels-idx1-ubyte"; + const std::string train_prefix = "-train"; + const std::string test_prefix = "-test"; + auto realpath = FileUtils::GetRealPath(folder_path_.data()); + CHECK_FAIL_RETURN_UNEXPECTED(realpath.has_value(), "Get real path failed: " + folder_path_); + Path dir(realpath.value()); + auto dir_it = Path::DirIterator::OpenDirectory(&dir); + if (dir_it == nullptr) { + RETURN_STATUS_UNEXPECTED("Invalid path, failed to open directory: " + dir.ToString()); + } + std::string prefix; + prefix = "emnist-" + name_; // used to match usage == "all". + if (usage_ == "train" || usage_ == "test") { + prefix += (usage_ == "test" ? test_prefix : train_prefix); + } + if (dir_it != nullptr) { + while (dir_it->HasNext()) { + Path file = dir_it->Next(); + std::string fname = file.Basename(); // name of the emnist file. + if ((fname.find(prefix) != std::string::npos) && (fname.find(img_ext) != std::string::npos)) { + image_names_.push_back(file.ToString()); + MS_LOG(INFO) << DatasetName(true) << " operator found image file at " << fname << "."; + } else if ((fname.find(prefix) != std::string::npos) && (fname.find(lbl_ext) != std::string::npos)) { + label_names_.push_back(file.ToString()); + MS_LOG(INFO) << DatasetName(true) << " operator found label file at " << fname << "."; + } + } + } else { + MS_LOG(WARNING) << DatasetName(true) << " operator unable to open directory " << dir.ToString() << "."; + } + + std::sort(image_names_.begin(), image_names_.end()); + std::sort(label_names_.begin(), label_names_.end()); + CHECK_FAIL_RETURN_UNEXPECTED(image_names_.size() == label_names_.size(), + "Invalid data, num of images does not equal to num of labels."); + + return Status::OK(); +} + +Status EMnistOp::CountTotalRows(const std::string &dir, const std::string &name, const std::string &usage, + int64_t *count) { + // the logic of counting the number of samples is copied from ParseEMnistData() and uses CheckReader(). + RETURN_UNEXPECTED_IF_NULL(count); + *count = 0; + + const int64_t num_samples = 0; + const int64_t start_index = 0; + auto sampler = std::make_shared(start_index, num_samples); + auto schema = std::make_unique(); + RETURN_IF_NOT_OK(schema->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kCv, 1))); + TensorShape scalar = TensorShape::CreateScalar(); + RETURN_IF_NOT_OK( + schema->AddColumn(ColDescriptor("label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &scalar))); + std::shared_ptr cfg = GlobalContext::config_manager(); + int32_t num_workers = cfg->num_parallel_workers(); + int32_t op_connect_size = cfg->op_connector_size(); + auto op = + std::make_shared(name, usage, num_workers, dir, op_connect_size, std::move(schema), std::move(sampler)); + + RETURN_IF_NOT_OK(op->WalkAllFiles()); + + for (size_t i = 0; i < op->image_names_.size(); ++i) { + std::ifstream image_reader; + image_reader.open(op->image_names_[i], std::ios::binary); + CHECK_FAIL_RETURN_UNEXPECTED(image_reader.is_open(), + "Invalid file, failed to open image file: " + op->image_names_[i]); + std::ifstream label_reader; + label_reader.open(op->label_names_[i], std::ios::binary); + CHECK_FAIL_RETURN_UNEXPECTED(label_reader.is_open(), + "Invalid file, failed to open label file: " + op->label_names_[i]); + uint32_t num_images; + Status s = op->CheckImage(op->image_names_[i], &image_reader, &num_images); + image_reader.close(); + RETURN_IF_NOT_OK(s); + + uint32_t num_labels; + s = op->CheckLabel(op->label_names_[i], &label_reader, &num_labels); + label_reader.close(); + RETURN_IF_NOT_OK(s); + + CHECK_FAIL_RETURN_UNEXPECTED((num_images == num_labels), + "Invalid data, num of images is not equal to num of labels."); + *count = *count + num_images; + } + + return Status::OK(); +} + +} // namespace dataset +} // namespace mindspore diff --git a/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.h b/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.h new file mode 100644 index 0000000000..352a589099 --- /dev/null +++ b/mindspore/ccsrc/minddata/dataset/engine/datasetops/source/emnist_op.h @@ -0,0 +1,84 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_EMNIST_OP_H_ +#define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_EMNIST_OP_H_ + +#include +#include +#include +#include +#include +#include + +#include "minddata/dataset/engine/datasetops/source/mnist_op.h" + +namespace mindspore { +namespace dataset { +// Forward declares +template +class Queue; + +class EMnistOp : public MnistOp { + public: + // Constructor. + // @param const std::string &name - Class of this dataset, can be + // "byclass","bymerge","balanced","letters","digits","mnist". + // @param const std::string &usage - Usage of this dataset, can be 'train', 'test' or 'all'. + // @param int32_t num_workers - Number of workers reading images in parallel. + // @param const std::string &folder_path - Dir directory of emnist. + // @param int32_t queue_size - Connector queue size. + // @param std::unique_ptr data_schema - The schema of the Emnist dataset. + // @param std::shared_ptr sampler - Sampler tells EMnistOp what to read. + EMnistOp(const std::string &name, const std::string &usage, int32_t num_workers, const std::string &folder_path, + int32_t queue_size, std::unique_ptr data_schema, std::shared_ptr sampler); + + // Destructor. + ~EMnistOp() = default; + + // A print method typically used for debugging. + // @param std::ostream &out - Out stream. + // @param bool show_all - Whether to show all information. + void Print(std::ostream &out, bool show_all) const override; + + // Function to count the number of samples in the EMNIST dataset. + // @param const std::string &dir - Path to the EMNIST directory. + // @param const std::string &name - Class of this dataset, can be + // "byclass","bymerge","balanced","letters","digits","mnist". + // @param const std::string &usage - Usage of this dataset, can be 'train', 'test' or 'all'. + // @param int64_t *count - Output arg that will hold the minimum of the actual dataset size and numSamples. + // @return Status The status code returned. + static Status CountTotalRows(const std::string &dir, const std::string &name, const std::string &usage, + int64_t *count); + + // Op name getter. + // @return Name of the current Op. + std::string Name() const override { return "EMnistOp"; } + + // DatasetName name getter. + // \return DatasetName of the current Op. + std::string DatasetName(bool upper = false) const override { return upper ? "EMnist" : "emnist"; } + + private: + // Read all files in the directory. + // @return Status The status code returned. + Status WalkAllFiles() override; + + const std::string name_; // can be "byclass", "bymerge", "balanced", "letters", "digits", "mnist". +}; + +} // namespace dataset +} // namespace mindspore +#endif // MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_EMNIST_OP_H_ diff --git a/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.h b/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.h index e69f9d17a9..9b7f853d60 100644 --- a/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.h +++ b/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/dataset_node.h @@ -83,6 +83,7 @@ constexpr char kCLUENode[] = "CLUEDataset"; constexpr char kCocoNode[] = "CocoDataset"; constexpr char kCSVNode[] = "CSVDataset"; constexpr char kDIV2KNode[] = "DIV2KDataset"; +constexpr char kEMnistNode[] = "EMnistDataset"; constexpr char kFlickrNode[] = "FlickrDataset"; constexpr char kGeneratorNode[] = "GeneratorDataset"; constexpr char kImageFolderNode[] = "ImageFolderDataset"; diff --git a/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/CMakeLists.txt b/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/CMakeLists.txt index 6144e87b54..8c6107943e 100644 --- a/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/CMakeLists.txt +++ b/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/CMakeLists.txt @@ -12,6 +12,7 @@ set(DATASET_ENGINE_IR_DATASETOPS_SOURCE_SRC_FILES coco_node.cc csv_node.cc div2k_node.cc + emnist_node.cc flickr_node.cc image_folder_node.cc manifest_node.cc @@ -33,4 +34,4 @@ if(ENABLE_PYTHON) ) endif() -add_library(engine-ir-datasetops-source OBJECT ${DATASET_ENGINE_IR_DATASETOPS_SOURCE_SRC_FILES}) \ No newline at end of file +add_library(engine-ir-datasetops-source OBJECT ${DATASET_ENGINE_IR_DATASETOPS_SOURCE_SRC_FILES}) diff --git a/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/emnist_node.cc b/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/emnist_node.cc new file mode 100644 index 0000000000..d04c4a4bca --- /dev/null +++ b/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/emnist_node.cc @@ -0,0 +1,121 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "minddata/dataset/engine/ir/datasetops/source/emnist_node.h" + +#include +#include +#include +#include + +#include "minddata/dataset/engine/datasetops/source/emnist_op.h" +#include "minddata/dataset/util/status.h" + +namespace mindspore { +namespace dataset { +EMnistNode::EMnistNode(const std::string &dataset_dir, const std::string &name, const std::string &usage, + std::shared_ptr sampler, std::shared_ptr cache) + : MappableSourceNode(std::move(cache)), dataset_dir_(dataset_dir), name_(name), usage_(usage), sampler_(sampler) {} + +std::shared_ptr EMnistNode::Copy() { + std::shared_ptr sampler = (sampler_ == nullptr) ? nullptr : sampler_->SamplerCopy(); + auto node = std::make_shared(dataset_dir_, name_, usage_, sampler, cache_); + return node; +} + +void EMnistNode::Print(std::ostream &out) const { + out << (Name() + "(cache: " + ((cache_ != nullptr) ? "true" : "false") + ")"); +} + +Status EMnistNode::ValidateParams() { + RETURN_IF_NOT_OK(DatasetNode::ValidateParams()); + RETURN_IF_NOT_OK(ValidateDatasetDirParam("EMnistNode", dataset_dir_)); + + RETURN_IF_NOT_OK(ValidateDatasetSampler("EMnistNode", sampler_)); + + RETURN_IF_NOT_OK(ValidateStringValue("EMnistNode", usage_, {"train", "test", "all"})); + + RETURN_IF_NOT_OK( + ValidateStringValue("EMnistNode", name_, {"byclass", "bymerge", "balanced", "letters", "digits", "mnist"})); + + return Status::OK(); +} + +Status EMnistNode::Build(std::vector> *const node_ops) { + // Do internal Schema generation. + auto schema = std::make_unique(); + RETURN_IF_NOT_OK(schema->AddColumn(ColDescriptor("image", DataType(DataType::DE_UINT8), TensorImpl::kCv, 1))); + TensorShape scalar = TensorShape::CreateScalar(); + RETURN_IF_NOT_OK( + schema->AddColumn(ColDescriptor("label", DataType(DataType::DE_UINT32), TensorImpl::kFlexible, 0, &scalar))); + std::shared_ptr sampler_rt = nullptr; + RETURN_IF_NOT_OK(sampler_->SamplerBuild(&sampler_rt)); + + auto op = std::make_shared(name_, usage_, num_workers_, dataset_dir_, connector_que_size_, + std::move(schema), std::move(sampler_rt)); + op->SetTotalRepeats(GetTotalRepeats()); + op->SetNumRepeatsPerEpoch(GetNumRepeatsPerEpoch()); + node_ops->push_back(op); + + return Status::OK(); +} + +// Get the shard id of node. +Status EMnistNode::GetShardId(int32_t *shard_id) { + *shard_id = sampler_->ShardId(); + + return Status::OK(); +} + +// Get Dataset size. +Status EMnistNode::GetDatasetSize(const std::shared_ptr &size_getter, bool estimate, + int64_t *dataset_size) { + if (dataset_size_ > 0) { + *dataset_size = dataset_size_; + return Status::OK(); + } + int64_t num_rows, sample_size; + RETURN_IF_NOT_OK(EMnistOp::CountTotalRows(dataset_dir_, name_, usage_, &num_rows)); + std::shared_ptr sampler_rt = nullptr; + RETURN_IF_NOT_OK(sampler_->SamplerBuild(&sampler_rt)); + sample_size = sampler_rt->CalculateNumSamples(num_rows); + if (sample_size == -1) { + RETURN_IF_NOT_OK(size_getter->DryRun(shared_from_this(), &sample_size)); + } + *dataset_size = sample_size; + dataset_size_ = *dataset_size; + return Status::OK(); +} + +Status EMnistNode::to_json(nlohmann::json *out_json) { + nlohmann::json args, sampler_args; + RETURN_IF_NOT_OK(sampler_->to_json(&sampler_args)); + args["sampler"] = sampler_args; + args["num_parallel_workers"] = num_workers_; + args["dataset_dir"] = dataset_dir_; + args["name"] = name_; + args["usage"] = usage_; + if (cache_ != nullptr) { + nlohmann::json cache_args; + RETURN_IF_NOT_OK(cache_->to_json(&cache_args)); + args["cache"] = cache_args; + } + *out_json = args; + return Status::OK(); +} + +} // namespace dataset +} // namespace mindspore diff --git a/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/emnist_node.h b/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/emnist_node.h new file mode 100644 index 0000000000..000f82dfcb --- /dev/null +++ b/mindspore/ccsrc/minddata/dataset/engine/ir/datasetops/source/emnist_node.h @@ -0,0 +1,111 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_IR_DATASETOPS_SOURCE_EMNIST_NODE_H_ +#define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_IR_DATASETOPS_SOURCE_EMNIST_NODE_H_ + +#include +#include +#include + +#include "minddata/dataset/engine/ir/datasetops/dataset_node.h" + +namespace mindspore { +namespace dataset { +class EMnistNode : public MappableSourceNode { + public: + /// \brief Constructor. + /// \param[in] dataset_dir Dataset directory of emnist. + /// \param[in] name Class of this dataset, can be "byclass", "bymerge", "balanced", "letters", "digits", "mnist". + /// \param[in] usage Usage of this dataset, can be 'train', 'test' or 'all'. + /// \param[in] sampler Tells EMnistOp what to read. + /// \param[in] cache Tensor cache to use. + EMnistNode(const std::string &dataset_dir, const std::string &name, const std::string &usage, + std::shared_ptr sampler, std::shared_ptr cache); + + /// \brief Destructor. + ~EMnistNode() = default; + + /// \brief Node name getter. + /// \return Name of the current node. + std::string Name() const override { return "EMnistNode"; } + + /// \brief Print the description. + /// \param[in] out The output stream to write output to. + void Print(std::ostream &out) const override; + + /// \brief Copy the node to a new object. + /// \return A shared pointer to the new copy. + std::shared_ptr Copy() override; + + /// \brief A base class override function to create the required runtime dataset op objects for this class. + /// \param[in] node_ops A vector containing shared pointer to the Dataset Ops that this object will create. + /// \return Status Status::OK() if build successfully. + Status Build(std::vector> *const node_ops) override; + + /// \brief Parameters validation. + /// \return Status Status::OK() if all the parameters are valid. + Status ValidateParams() override; + + /// \brief Get the shard id of node. + /// \param[in] shard_id The shard id. + /// \return Status Status::OK() if get shard id successfully. + Status GetShardId(int32_t *shard_id) override; + + /// \brief Base-class override for GetDatasetSize. + /// \param[in] size_getter Shared pointer to DatasetSizeGetter. + /// \param[in] estimate This is only supported by some of the ops and it's used to speed up the process of getting + /// dataset size at the expense of accuracy. + /// \param[out] dataset_size The size of the dataset. + /// \return Status of the function. + Status GetDatasetSize(const std::shared_ptr &size_getter, bool estimate, + int64_t *dataset_size) override; + + /// \brief Getter functions. + /// \return Dataset direction. + const std::string &DatasetDir() const { return dataset_dir_; } + + /// \brief Getter functions. + /// \return Usage. + const std::string &Usage() const { return usage_; } + + /// \brief Getter functions. + /// \return Name. + const std::string &GetName() const { return name_; } + + /// \brief Get the arguments of node. + /// \param[out] out_json JSON string of all attributes. + /// \return Status of the function. + Status to_json(nlohmann::json *out_json) override; + + /// \brief Sampler getter. + /// \return SamplerObj of the current node. + std::shared_ptr Sampler() override { return sampler_; } + + /// \brief Sampler setter. + /// \param[in] sampler Tells EMnistOp what to read. + void SetSampler(std::shared_ptr sampler) override { sampler_ = sampler; } + + private: + std::string dataset_dir_; + std::string name_; + std::string usage_; + std::shared_ptr sampler_; +}; + +} // namespace dataset +} // namespace mindspore +#endif // MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_IR_DATASETOPS_SOURCE_EMNIST_NODE_H_ diff --git a/mindspore/ccsrc/minddata/dataset/include/dataset/datasets.h b/mindspore/ccsrc/minddata/dataset/include/dataset/datasets.h index d632c62614..423ec07ed0 100644 --- a/mindspore/ccsrc/minddata/dataset/include/dataset/datasets.h +++ b/mindspore/ccsrc/minddata/dataset/include/dataset/datasets.h @@ -1628,6 +1628,93 @@ inline std::shared_ptr DIV2K(const std::string &dataset_dir, const decode, sampler, cache); } +/// \class EMnistDataset +/// \brief A source dataset for reading and parsing EMnist dataset. +class EMnistDataset : public Dataset { + public: + /// \brief Constructor of EMnistDataset. + /// \param[in] dataset_dir Path to the root directory that contains the dataset. + /// \param[in] name Name of splits for EMNIST, can be "byclass", "bymerge", "balanced", "letters", "digits" + /// or "mnist". + /// \param[in] usage Part of dataset of EMNIST, can be "train", "test" or "all". + /// \param[in] sampler Shared pointer to a sampler object used to choose samples from the dataset. If sampler is not + /// given, a `RandomSampler` will be used to randomly iterate the entire dataset. + /// \param[in] cache Tensor cache to use. + explicit EMnistDataset(const std::vector &dataset_dir, const std::vector &name, + const std::vector &usage, const std::shared_ptr &sampler, + const std::shared_ptr &cache); + + /// \brief Constructor of EMnistDataset. + /// \param[in] dataset_dir Path to the root directory that contains the dataset. + /// \param[in] name Name of splits for EMNIST, can be "byclass", "bymerge", "balanced", "letters", "digits" + /// or "mnist". + /// \param[in] usage Part of dataset of EMNIST, can be "train", "test" or "all". + /// \param[in] sampler Raw pointer to a sampler object used to choose samples from the dataset. + /// \param[in] cache Tensor cache to use. + explicit EMnistDataset(const std::vector &dataset_dir, const std::vector &name, + const std::vector &usage, const Sampler *sampler, + const std::shared_ptr &cache); + + /// \brief Constructor of EMnistDataset. + /// \param[in] dataset_dir Path to the root directory that contains the dataset. + /// \param[in] name Name of splits for EMNIST, can be "byclass", "bymerge", "balanced", "letters", "digits" + /// or "mnist". + /// \param[in] usage Part of dataset of EMNIST, can be "train", "test" or "all". + /// \param[in] sampler Sampler object used to choose samples from the dataset. + /// \param[in] cache Tensor cache to use. + explicit EMnistDataset(const std::vector &dataset_dir, const std::vector &name, + const std::vector &usage, const std::reference_wrapper sampler, + const std::shared_ptr &cache); + ~EMnistDataset() = default; +}; + +/// \brief Function to create a EMnistDataset. +/// \notes The generated dataset has two columns ["image", "label"]. +/// \param[in] dataset_dir Path to the root directory that contains the dataset. +/// \param[in] name Name of splits for EMNIST, can be "byclass", "bymerge", "balanced", "letters", "digits" or "mnist". +/// \param[in] usage Usage of EMNIST, can be "train", "test" or "all" (default = "all"). +/// \param[in] sampler Shared pointer to a sampler object used to choose samples from the dataset. If sampler is not. +/// given, a `RandomSampler` will be used to randomly iterate the entire dataset (default = RandomSampler()). +/// \param[in] cache Tensor cache to use. (default=nullptr which means no cache is used). +/// \return Shared pointer to the current EMnistDataset. +inline std::shared_ptr EMnist( + const std::string &dataset_dir, const std::string &name, const std::string &usage = "all", + const std::shared_ptr &sampler = std::make_shared(), + const std::shared_ptr &cache = nullptr) { + return std::make_shared(StringToChar(dataset_dir), StringToChar(name), StringToChar(usage), sampler, + cache); +} + +/// \brief Function to create a EMnistDataset. +/// \notes The generated dataset has two columns ["image", "label"]. +/// \param[in] dataset_dir Path to the root directory that contains the dataset +/// \param[in] name Name of splits for EMNIST, can be "byclass", "bymerge", "balanced", "letters", "digits" or "mnist". +/// \param[in] usage Usage of EMNIST, can be "train", "test" or "all". +/// \param[in] sampler Raw pointer to a sampler object used to choose samples from the dataset. +/// \param[in] cache Tensor cache to use. (default=nullptr which means no cache is used). +/// \return Shared pointer to the current EMnistDataset. +inline std::shared_ptr EMnist(const std::string &dataset_dir, const std::string &usage, + const std::string &name, const Sampler *sampler, + const std::shared_ptr &cache = nullptr) { + return std::make_shared(StringToChar(dataset_dir), StringToChar(name), StringToChar(usage), sampler, + cache); +} + +/// \brief Function to create a EMnistDataset. +/// \notes The generated dataset has two columns ["image", "label"]. +/// \param[in] dataset_dir Path to the root directory that contains the dataset. +/// \param[in] name Name of splits for EMNIST, can be "byclass", "bymerge", "balanced", "letters", "digits" or "mnist". +/// \param[in] usage Usage of EMNIST, can be "train", "test" or "all". +/// \param[in] sampler Sampler object used to choose samples from the dataset. +/// \param[in] cache Tensor cache to use. (default=nullptr which means no cache is used). +/// \return Shared pointer to the current EMnistDataset. +inline std::shared_ptr EMnist(const std::string &dataset_dir, const std::string &name, + const std::string &usage, const std::reference_wrapper sampler, + const std::shared_ptr &cache = nullptr) { + return std::make_shared(StringToChar(dataset_dir), StringToChar(name), StringToChar(usage), sampler, + cache); +} + /// \class FlickrDataset /// \brief A source dataset for reading and parsing Flickr dataset. class FlickrDataset : public Dataset { diff --git a/mindspore/ccsrc/minddata/dataset/include/dataset/samplers.h b/mindspore/ccsrc/minddata/dataset/include/dataset/samplers.h index 902307a896..fd48b5a2ec 100644 --- a/mindspore/ccsrc/minddata/dataset/include/dataset/samplers.h +++ b/mindspore/ccsrc/minddata/dataset/include/dataset/samplers.h @@ -39,6 +39,7 @@ class Sampler : std::enable_shared_from_this { friend class CocoDataset; friend class CSVDataset; friend class DIV2KDataset; + friend class EMnistDataset; friend class FlickrDataset; friend class ImageFolderDataset; friend class ManifestDataset; diff --git a/mindspore/dataset/engine/datasets.py b/mindspore/dataset/engine/datasets.py index ba530d0d0b..28808f1380 100644 --- a/mindspore/dataset/engine/datasets.py +++ b/mindspore/dataset/engine/datasets.py @@ -66,7 +66,7 @@ from .validators import check_batch, check_shuffle, check_map, check_filter, che check_bucket_batch_by_length, check_cluedataset, check_save, check_csvdataset, check_paddeddataset, \ check_tuple_iterator, check_dict_iterator, check_schema, check_to_device_send, check_flickr_dataset, \ check_sb_dataset, check_flowers102dataset, check_cityscapes_dataset, check_usps_dataset, check_div2k_dataset, \ - check_sbu_dataset, check_qmnist_dataset + check_sbu_dataset, check_qmnist_dataset, check_emnist_dataset from ..core.config import get_callback_timeout, _init_device_info, get_enable_shared_mem, get_num_parallel_workers, \ get_prefetch_size from ..core.datatypes import mstype_to_detype, mstypelist_to_detypelist @@ -6350,6 +6350,138 @@ class PaddedDataset(GeneratorDataset): self.padded_samples = padded_samples +class EMnistDataset(MappableDataset): + """ + A source dataset for reading and parsing the EMNIST dataset. + + The generated dataset has two columns :py:obj:`[image, label]`. + The tensor of column :py:obj:`image` is of the uint8 type. + The tensor of column :py:obj:`label` is a scalar of the uint32 type. + + Args: + dataset_dir (str): Path to the root directory that contains the dataset. + name (str): Name of splits for this dataset, can be "byclass", "bymerge", "balanced", "letters", "digits" + or "mnist". + usage (str, optional): Usage of this dataset, can be "train", "test" or "all". + (default=None, will read all samples). + num_samples (int, optional): The number of images to be included in the dataset + (default=None, will read all images). + num_parallel_workers (int, optional): Number of workers to read the data + (default=None, will use value set in the config). + shuffle (bool, optional): Whether or not to perform shuffle on the dataset + (default=None, expected order behavior shown in the table). + sampler (Sampler, optional): Object used to choose samples from the + dataset (default=None, expected order behavior shown in the table). + num_shards (int, optional): Number of shards that the dataset will be divided into (default=None). + When this argument is specified, `num_samples` reflects the max sample number of per shard. + shard_id (int, optional): The shard ID within `num_shards` (default=None). This + argument can only be specified when `num_shards` is also specified. + cache (DatasetCache, optional): Use tensor caching service to speed up dataset processing. + (default=None, which means no cache is used). + + Raises: + RuntimeError: If sampler and shuffle are specified at the same time. + RuntimeError: If sampler and sharding are specified at the same time. + RuntimeError: If num_shards is specified but shard_id is None. + RuntimeError: If shard_id is specified but num_shards is None. + ValueError: If shard_id is invalid (< 0 or >= num_shards). + + Note: + - This dataset can take in a `sampler`. `sampler` and `shuffle` are mutually exclusive. + The table below shows what input arguments are allowed and their expected behavior. + + .. list-table:: Expected Order Behavior of Using `sampler` and `shuffle` + :widths: 25 25 50 + :header-rows: 1 + + * - Parameter `sampler` + - Parameter `shuffle` + - Expected Order Behavior + * - None + - None + - random order + * - None + - True + - random order + * - None + - False + - sequential order + * - Sampler object + - None + - order defined by sampler + * - Sampler object + - True + - not allowed + * - Sampler object + - False + - not allowed + + Examples: + >>> emnist_dataset_dir = "/path/to/emnist_dataset_directory" + >>> + >>> # Read 3 samples from EMNIST dataset + >>> dataset = ds.EMnistDataset(dataset_dir=emnist_dataset_dir, name="mnist", num_samples=3) + >>> + >>> # Note: In emnist_dataset dataset, each dictionary has keys "image" and "label" + + About EMNIST dataset: + + The EMNIST dataset is a set of handwritten character digits derived from the NIST Special + Database 19 and converted to a 28x28 pixel image format and dataset structure that directly + matches the MNIST dataset. Further information on the dataset contents and conversion process + can be found in the paper available at https://arxiv.org/abs/1702.05373v1. + + The numbers of characters and classes of each split of EMNIST are as follows: + + By Class: 814,255 characters and 62 unbalanced classes. + By Merge: 814,255 characters and 47 unbalanced classes. + Balanced: 131,600 characters and 47 balanced classes. + Letters: 145,600 characters and 26 balanced classes. + Digits: 280,000 characters and 10 balanced classes. + MNIST: 70,000 characters and 10 balanced classes. + + Here is the original EMNIST dataset structure. + You can unzip the dataset files into this directory structure and read by MindSpore's API. + + .. code-block:: + + . + └── mnist_dataset_dir + ├── emnist-mnist-train-images-idx3-ubyte + ├── emnist-mnist-train-labels-idx1-ubyte + ├── emnist-mnist-test-images-idx3-ubyte + ├── emnist-mnist-test-labels-idx1-ubyte + ├── ... + + Citation: + + .. code-block:: + + @article{cohen_afshar_tapson_schaik_2017, + title = {EMNIST: Extending MNIST to handwritten letters}, + DOI = {10.1109/ijcnn.2017.7966217}, + journal = {2017 International Joint Conference on Neural Networks (IJCNN)}, + author = {Cohen, Gregory and Afshar, Saeed and Tapson, Jonathan and Schaik, Andre Van}, + year = {2017}, + howpublished = {https://www.westernsydney.edu.au/icns/reproducible_research/ + publication_support_materials/emnist} + } + """ + + @check_emnist_dataset + def __init__(self, dataset_dir, name, usage=None, num_samples=None, num_parallel_workers=None, + shuffle=None, sampler=None, num_shards=None, shard_id=None, cache=None): + super().__init__(num_parallel_workers=num_parallel_workers, sampler=sampler, num_samples=num_samples, + shuffle=shuffle, num_shards=num_shards, shard_id=shard_id, cache=cache) + + self.dataset_dir = dataset_dir + self.name = name + self.usage = replace_none(usage, "all") + + def parse(self, children=None): + return cde.EMnistNode(self.dataset_dir, self.name, self.usage, self.sampler) + + class FlickrDataset(MappableDataset): """ A source dataset for reading and parsing Flickr8k and Flickr30k dataset. diff --git a/mindspore/dataset/engine/validators.py b/mindspore/dataset/engine/validators.py index efc76657ce..46738b134a 100644 --- a/mindspore/dataset/engine/validators.py +++ b/mindspore/dataset/engine/validators.py @@ -1,4 +1,4 @@ -# Copyright 2019 Huawei Technologies Co., Ltd +# Copyright 2019-2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -1463,6 +1463,39 @@ def check_to_device_send(method): return new_method +def check_emnist_dataset(method): + """A wrapper that wraps a parameter checker emnist dataset""" + + @wraps(method) + def new_method(self, *args, **kwargs): + _, param_dict = parse_user_args(method, *args, **kwargs) + + nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id'] + nreq_param_bool = ['shuffle'] + + validate_dataset_param_value(nreq_param_int, param_dict, int) + validate_dataset_param_value(nreq_param_bool, param_dict, bool) + + dataset_dir = param_dict.get('dataset_dir') + check_dir(dataset_dir) + + name = param_dict.get('name') + check_valid_str(name, ["byclass", "bymerge", "balanced", "letters", "digits", "mnist"], "name") + + usage = param_dict.get('usage') + if usage is not None: + check_valid_str(usage, ["train", "test", "all"], "usage") + + check_sampler_shuffle_shard_options(param_dict) + + cache = param_dict.get('cache') + check_cache_option(cache) + + return method(self, *args, **kwargs) + + return new_method + + def check_flickr_dataset(method): """A wrapper that wraps a parameter checker around the original Dataset(Flickr8k, Flickr30k).""" diff --git a/tests/ut/cpp/dataset/CMakeLists.txt b/tests/ut/cpp/dataset/CMakeLists.txt index 7d93ecc2c8..0480badf89 100644 --- a/tests/ut/cpp/dataset/CMakeLists.txt +++ b/tests/ut/cpp/dataset/CMakeLists.txt @@ -23,6 +23,7 @@ SET(DE_UT_SRCS c_api_dataset_config_test.cc c_api_dataset_csv_test.cc c_api_dataset_div2k_test.cc + c_api_dataset_emnist_test.cc c_api_dataset_flickr_test.cc c_api_dataset_iterator_test.cc c_api_dataset_manifest_test.cc diff --git a/tests/ut/cpp/dataset/c_api_dataset_emnist_test.cc b/tests/ut/cpp/dataset/c_api_dataset_emnist_test.cc new file mode 100644 index 0000000000..61c0d60dd6 --- /dev/null +++ b/tests/ut/cpp/dataset/c_api_dataset_emnist_test.cc @@ -0,0 +1,368 @@ +/** + * Copyright 2021 Huawei Technologies Co., Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "common/common.h" + +#include "minddata/dataset/include/dataset/datasets.h" + +using namespace mindspore::dataset; +using mindspore::dataset::DataType; +using mindspore::dataset::Tensor; +using mindspore::dataset::TensorShape; + +class MindDataTestPipeline : public UT::DatasetOpTesting { + protected: +}; + +TEST_F(MindDataTestPipeline, TestEMnistTrainDataset) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistTrainDataset."; + + // Create a EMnist Train Dataset + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + + std::shared_ptr ds = EMnist(folder_path, "mnist", "train", std::make_shared(false, 5)); + + EXPECT_NE(ds, nullptr); + + // Create an iterator over the result of the above dataset + // This will trigger the creation of the Execution Tree and launch it. + std::shared_ptr iter = ds->CreateIterator(); + EXPECT_NE(iter, nullptr); + + // Iterate the dataset and get each row + std::unordered_map row; + ASSERT_OK(iter->GetNextRow(&row)); + + EXPECT_NE(row.find("image"), row.end()); + EXPECT_NE(row.find("label"), row.end()); + + uint64_t i = 0; + while (row.size() != 0) { + i++; + auto image = row["image"]; + MS_LOG(INFO) << "Tensor image shape: " << image.Shape(); + ASSERT_OK(iter->GetNextRow(&row)); + } + + EXPECT_EQ(i, 5); + // Manually terminate the pipeline + iter->Stop(); +} + +TEST_F(MindDataTestPipeline, TestEMnistTestDataset) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistTestDataset."; + + // Create a EMNIST Test Dataset + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + std::shared_ptr ds = EMnist(folder_path, "mnist", "train", std::make_shared(false, 5)); + + EXPECT_NE(ds, nullptr); + + // Create an iterator over the result of the above dataset + // This will trigger the creation of the Execution Tree and launch it. + std::shared_ptr iter = ds->CreateIterator(); + EXPECT_NE(iter, nullptr); + + // Iterate the dataset and get each row + std::unordered_map row; + ASSERT_OK(iter->GetNextRow(&row)); + + EXPECT_NE(row.find("image"), row.end()); + EXPECT_NE(row.find("label"), row.end()); + + uint64_t i = 0; + while (row.size() != 0) { + i++; + auto image = row["image"]; + MS_LOG(INFO) << "Tensor image shape: " << image.Shape(); + ASSERT_OK(iter->GetNextRow(&row)); + } + + EXPECT_EQ(i, 5); + + // Manually terminate the pipeline + iter->Stop(); +} + +TEST_F(MindDataTestPipeline, TestEMnistTrainDatasetWithPipeline) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistTrainDatasetWithPipeline."; + + // Create two Emnist Train Dataset + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + + std::shared_ptr ds1 = EMnist(folder_path, "mnist", "train", std::make_shared(false, 5)); + std::shared_ptr ds2 = EMnist(folder_path, "byclass", "train", std::make_shared(false, 5)); + EXPECT_NE(ds1, nullptr); + EXPECT_NE(ds2, nullptr); + + // Create two Repeat operation on ds + int32_t repeat_num = 1; + ds1 = ds1->Repeat(repeat_num); + EXPECT_NE(ds1, nullptr); + repeat_num = 1; + ds2 = ds2->Repeat(repeat_num); + EXPECT_NE(ds2, nullptr); + + // Create two Project operation on ds + std::vector column_project = {"image", "label"}; + ds1 = ds1->Project(column_project); + EXPECT_NE(ds1, nullptr); + ds2 = ds2->Project(column_project); + EXPECT_NE(ds2, nullptr); + + // Create a Concat operation on the ds + ds1 = ds1->Concat({ds2}); + EXPECT_NE(ds1, nullptr); + + // Create an iterator over the result of the above dataset + // This will trigger the creation of the Execution Tree and launch it. + std::shared_ptr iter = ds1->CreateIterator(); + EXPECT_NE(iter, nullptr); + + // Iterate the dataset and get each row + std::unordered_map row; + ASSERT_OK(iter->GetNextRow(&row)); + + EXPECT_NE(row.find("image"), row.end()); + EXPECT_NE(row.find("label"), row.end()); + + uint64_t i = 0; + while (row.size() != 0) { + i++; + auto image = row["image"]; + MS_LOG(INFO) << "Tensor image shape: " << image.Shape(); + ASSERT_OK(iter->GetNextRow(&row)); + } + + EXPECT_EQ(i, 10); + + // Manually terminate the pipeline + iter->Stop(); +} + +TEST_F(MindDataTestPipeline, TestEMnistTestDatasetWithPipeline) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistTestDatasetWithPipeline."; + + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + + // Create two EMnist Test Dataset + std::shared_ptr ds1 = EMnist(folder_path, "mnist", "test", std::make_shared(false, 5)); + std::shared_ptr ds2 = EMnist(folder_path, "mnist", "test", std::make_shared(false, 5)); + EXPECT_NE(ds1, nullptr); + EXPECT_NE(ds2, nullptr); + + // Create two Repeat operation on ds + int32_t repeat_num = 1; + ds1 = ds1->Repeat(repeat_num); + EXPECT_NE(ds1, nullptr); + repeat_num = 1; + ds2 = ds2->Repeat(repeat_num); + EXPECT_NE(ds2, nullptr); + + // Create two Project operation on ds + std::vector column_project = {"image", "label"}; + ds1 = ds1->Project(column_project); + EXPECT_NE(ds1, nullptr); + ds2 = ds2->Project(column_project); + EXPECT_NE(ds2, nullptr); + + // Create a Concat operation on the ds + ds1 = ds1->Concat({ds2}); + EXPECT_NE(ds1, nullptr); + + // Create an iterator over the result of the above dataset + // This will trigger the creation of the Execution Tree and launch it. + std::shared_ptr iter = ds1->CreateIterator(); + EXPECT_NE(iter, nullptr); + + // Iterate the dataset and get each row + std::unordered_map row; + ASSERT_OK(iter->GetNextRow(&row)); + + EXPECT_NE(row.find("image"), row.end()); + EXPECT_NE(row.find("label"), row.end()); + + uint64_t i = 0; + while (row.size() != 0) { + i++; + auto image = row["image"]; + MS_LOG(INFO) << "Tensor image shape: " << image.Shape(); + ASSERT_OK(iter->GetNextRow(&row)); + } + + EXPECT_EQ(i, 10); + + // Manually terminate the pipeline + iter->Stop(); +} + +TEST_F(MindDataTestPipeline, TestGetEMnistTrainDatasetSize) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestGetEMnistTrainDatasetSize."; + + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + // Create a EMnist Train Dataset + std::shared_ptr ds = EMnist(folder_path, "mnist", "train"); + EXPECT_NE(ds, nullptr); + + EXPECT_EQ(ds->GetDatasetSize(), 10); + + std::shared_ptr ds2 = EMnist(folder_path, "byclass", "train"); + EXPECT_NE(ds2, nullptr); + + EXPECT_EQ(ds2->GetDatasetSize(), 10); +} + +TEST_F(MindDataTestPipeline, TestGetEMnistTestDatasetSize) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestGetEMnistTestDatasetSize."; + + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + + // Create a EMnist Test Dataset + std::shared_ptr ds = EMnist(folder_path, "mnist", "test"); + EXPECT_NE(ds, nullptr); + + EXPECT_EQ(ds->GetDatasetSize(), 10); +} + +TEST_F(MindDataTestPipeline, TestEMnistTrainDatasetGetters) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistTrainDatasetGetters."; + + // Create a EMnist Train Dataset + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + std::shared_ptr ds = EMnist(folder_path, "mnist", "train"); + EXPECT_NE(ds, nullptr); + + EXPECT_EQ(ds->GetDatasetSize(), 10); + std::vector types = ToDETypes(ds->GetOutputTypes()); + std::vector shapes = ToTensorShapeVec(ds->GetOutputShapes()); + std::vector column_names = {"image", "label"}; + int64_t num_classes = ds->GetNumClasses(); + EXPECT_EQ(types.size(), 2); + EXPECT_EQ(types[0].ToString(), "uint8"); + EXPECT_EQ(types[1].ToString(), "uint32"); + EXPECT_EQ(shapes.size(), 2); + EXPECT_EQ(shapes[0].ToString(), "<28,28,1>"); + EXPECT_EQ(shapes[1].ToString(), "<>"); + EXPECT_EQ(num_classes, -1); + EXPECT_EQ(ds->GetBatchSize(), 1); + EXPECT_EQ(ds->GetRepeatCount(), 1); + + EXPECT_EQ(ds->GetDatasetSize(), 10); + EXPECT_EQ(ToDETypes(ds->GetOutputTypes()), types); + EXPECT_EQ(ToTensorShapeVec(ds->GetOutputShapes()), shapes); + EXPECT_EQ(ds->GetNumClasses(), -1); + + EXPECT_EQ(ds->GetColumnNames(), column_names); + EXPECT_EQ(ds->GetDatasetSize(), 10); + EXPECT_EQ(ToDETypes(ds->GetOutputTypes()), types); + EXPECT_EQ(ToTensorShapeVec(ds->GetOutputShapes()), shapes); + EXPECT_EQ(ds->GetBatchSize(), 1); + EXPECT_EQ(ds->GetRepeatCount(), 1); + EXPECT_EQ(ds->GetNumClasses(), -1); + EXPECT_EQ(ds->GetDatasetSize(), 10); +} + +TEST_F(MindDataTestPipeline, TestEMnistTestDatasetGetters) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistTestDatasetGetters."; + + // Create a EMnist Test Dataset + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + std::shared_ptr ds = EMnist(folder_path, "mnist", "test"); + EXPECT_NE(ds, nullptr); + + EXPECT_EQ(ds->GetDatasetSize(), 10); + std::vector types = ToDETypes(ds->GetOutputTypes()); + std::vector shapes = ToTensorShapeVec(ds->GetOutputShapes()); + std::vector column_names = {"image", "label"}; + int64_t num_classes = ds->GetNumClasses(); + EXPECT_EQ(types.size(), 2); + EXPECT_EQ(types[0].ToString(), "uint8"); + EXPECT_EQ(types[1].ToString(), "uint32"); + EXPECT_EQ(shapes.size(), 2); + EXPECT_EQ(shapes[0].ToString(), "<28,28,1>"); + EXPECT_EQ(shapes[1].ToString(), "<>"); + EXPECT_EQ(num_classes, -1); + EXPECT_EQ(ds->GetBatchSize(), 1); + EXPECT_EQ(ds->GetRepeatCount(), 1); + + EXPECT_EQ(ds->GetDatasetSize(), 10); + EXPECT_EQ(ToDETypes(ds->GetOutputTypes()), types); + EXPECT_EQ(ToTensorShapeVec(ds->GetOutputShapes()), shapes); + EXPECT_EQ(ds->GetNumClasses(), -1); + + EXPECT_EQ(ds->GetColumnNames(), column_names); + EXPECT_EQ(ds->GetDatasetSize(), 10); + EXPECT_EQ(ToDETypes(ds->GetOutputTypes()), types); + EXPECT_EQ(ToTensorShapeVec(ds->GetOutputShapes()), shapes); + EXPECT_EQ(ds->GetBatchSize(), 1); + EXPECT_EQ(ds->GetRepeatCount(), 1); + EXPECT_EQ(ds->GetNumClasses(), -1); + EXPECT_EQ(ds->GetDatasetSize(), 10); +} + +TEST_F(MindDataTestPipeline, TestEMnistDatasetWithInvalidDir) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistDatasetWithInvalidDir."; + + // Create a EMnist Dataset + std::shared_ptr ds = EMnist("", "mnist", "train", std::make_shared(false, 5)); + EXPECT_NE(ds, nullptr); + + // Create an iterator over the result of the above dataset + std::shared_ptr iter = ds->CreateIterator(); + // Expect failure: invalid EMnist input + EXPECT_EQ(iter, nullptr); +} + +TEST_F(MindDataTestPipeline, TestEMnistDatasetWithInvalidUsage) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistDatasetWithInvalidUsage."; + + // Create a EMnist Dataset + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + std::shared_ptr ds = EMnist(folder_path, "mnist", "validation"); + EXPECT_NE(ds, nullptr); + + // Create an iterator over the result of the above dataset + std::shared_ptr iter = ds->CreateIterator(); + // Expect failure: invalid EMnist input, validation is not a valid usage + EXPECT_EQ(iter, nullptr); +} + +TEST_F(MindDataTestPipeline, TestEMnistDatasetWithInvalidName) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistDatasetWithInvalidName."; + + // Create a EMnist Dataset + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + std::shared_ptr ds = EMnist(folder_path, "validation", "train"); + EXPECT_NE(ds, nullptr); + + // Create an iterator over the result of the above dataset + std::shared_ptr iter = ds->CreateIterator(); + // Expect failure: invalid EMnist input, validation is not a valid name + EXPECT_EQ(iter, nullptr); +} + +TEST_F(MindDataTestPipeline, TestEMnistDatasetWithNullSampler) { + MS_LOG(INFO) << "Doing MindDataTestPipeline-TestEMnistDatasetWithNullSampler."; + + // Create a EMnist Dataset + std::string folder_path = datasets_root_path_ + "/testEMnistDataset"; + std::shared_ptr ds = EMnist(folder_path, "mnist", "train", nullptr); + EXPECT_NE(ds, nullptr); + + // Create an iterator over the result of the above dataset + std::shared_ptr iter = ds->CreateIterator(); + // Expect failure: invalid EMnist input, sampler cannot be nullptr + EXPECT_EQ(iter, nullptr); +} diff --git a/tests/ut/data/dataset/testEMnistDataset/emnist-byclass-train-images-idx3-ubyte b/tests/ut/data/dataset/testEMnistDataset/emnist-byclass-train-images-idx3-ubyte new file mode 100644 index 0000000000000000000000000000000000000000..a6a44ce5a4689934dfc4565f59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ot}?c8f@Flq^qh_Hrn>-*tjE+TX(kz_Tr*wJqO z?clb}zEeWXxlli75pGsgQc8d#IjEiy0mZRUbq9OQD%d&1p&pw_9jo>iB(w+g;m^df zE*Tt5;Lu0p9~44L-m+Mn2OZ-ySy5v(+i;z82?efUx?|Gk0RE~og324IPox8b;pesu z#v3RyrG|rTX*)06bZG!5iPEkO*t;({e{FZKN%Q%b#7i8zOT%&|WiWmB1O8dm1`fWF zPZZ8#$DY$=gkNP=ea;^wbDDp^QJRnp=QC! zbUOt051hl!uY3-+VT@ zY@zeYFIZXmF?Z5hVZ6cdM62d)`D0vk9(Iw>DJ6%{%C%m{HIHuTx=+DU_i-d;g+{*f4g(lEUjck6wsOo{dlgGnjl%PCDuJ6AW->d05&*&tHW%A=u+!?-Yi2$=V$ei4ek0W+9Iak ztsGfi@T&OK5X&>G$cWrLg$LjwPt2?b*%no`xh0lT{koYavLc7+*Ct0dIX&fKZtyUB z-QngrrAY*HsT6>;X}r?)GDz64p=ei6+sl!al@JKDeM@4|%JY{Yv78B<~P9eXE%A>W{fhOZEGy0g?xt-c8yDG`O zLW++}@n*_V!d1aU4fqZy*Yw=tWA-;T9@E;M92pd7>d4H5PK@P=h9)o0$AGLt`8kyj1$}xzO~v}Fz!OgR9v9Tsb|C$6OcYWf+n(-!^)DkHO+S!UPY!8^lRVGa9Z z4u7YHR?KxLLU2(tC_kHgp<%?sY3RN4EExM>?2As9ZOI>DaSQ(_H{8&6_Z@ZXX6q_K O(nU>FrS}Pj8ckbN3_)iA literal 0 HcmV?d00001 diff --git a/tests/ut/data/dataset/testEMnistDataset/emnist-byclass-train-labels-idx1-ubyte b/tests/ut/data/dataset/testEMnistDataset/emnist-byclass-train-labels-idx1-ubyte new file mode 100644 index 0000000000000000000000000000000000000000..88ac148288d1d100004a617cfc95a25ec29d7b14 GIT binary patch literal 18 VcmZQz;9z86VBlh41X3Wx2mk>n02u%P literal 0 HcmV?d00001 diff --git a/tests/ut/data/dataset/testEMnistDataset/emnist-mnist-test-images-idx3-ubyte b/tests/ut/data/dataset/testEMnistDataset/emnist-mnist-test-images-idx3-ubyte new file mode 100644 index 0000000000000000000000000000000000000000..78ee56be2635b1bcbe75c919363999d3ae7294d6 GIT binary patch literal 7856 zcmV;h9#7!_00;vB000UA000~S0010EFmB}E7beTfjSXgtFQe$ao2H932re5E*$dNA z0-4#vDCH_%d2eAokPg3BNh88@=9yevgkI0|fs@!W{&myF`a(9VVo@MHAV30Q28!_x zW65U<7uL6j6C9~$9Qi$KXn8#=y}Itt*Fnk{U1`ECgD%u26>IlR#=+$ zjD3xE%TvkI>X`j>xP<6R$1nbDS-V}Sk?q7>T6DqR(oYpoVtvvf5!?#ty8(rkW8#u! zqm$-;rV@xEifwY+q}pNRs=ipuB2nr8g5L}huyfS)yK5gBe1654;pjWg0SXK1mNHjM zgFJ({8HCJOkP2NYf6Lq?7GUx&cb(El)dG$af7j3GN4M*}j(OwwvH8s| z#AFbR`(?N=j83TM1{fFvEW+0B$9;-%r%9nJfQSw+dx@EfpftH$43zh@L1=E27Os

g+kjHoVt1)k%V-37!spDtWKp{@;{_fhs>tOs)^$y zEaJ(bS9>vH^B~{)F~}4xp9Lh5xYJ`#q(>gJE{kZ#x=i1DA#g#2rIbyt+nOUExb`h- zZc#;%qUuiDI`WjOhyk^2-5w};CfYQV&?VbSgQb2}$rLxWsgWcHxi6!?N6v$i{k$$n zr#Sr%ZpjNncRx8KKmnE-02z<$A~lbFq*f@ymuSh#wZ)}e`OK!(scymAbmp9!IbcTl z#kG$9ifS)Bdb&@m!u6c4Di+6=-&kHLn+NBO1nf8->N`_dEx?K&Z1P>43xS+33IbjxH-*iu3g zb3^mCK-&C@nr)!NMcRfb06b?UX(BJ}?1`xPWzs0(k}!7=(sB=F2bB#iEoc~K>k8vO z+BBkffqEB|-1^0Yw7&I}N}Uhw&V-VnXcR_@|7Gim07KL4aDN?dhUnaYP%{HtCNF{r zl5LVf{N-D8OkoMer||PoL|JPAF@_uGS*{p%v!oV8_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i%|`lek*A=KvjAkl!HNQfvQW<+K*;p{vr*-`7^K2>9C*)Trk0ZvBz9n)QkAQ z1=hTc`MNT()shXXGMEg(37t}4C?M83ZXlg`9lGu$SNI;Y9@uoJ@!CR z$asUW!&p6mNFX?63Ezr6HkM?L8O0D>Tmm?}AnoBJPYc@Nld(?N11nQfguN)*s*Syg z=c|Au^65vL)?AA|lR}fbBT0kcW@Nu?jmgv-#~iL;s}l!e 0] = 255 # Perform binarization to maintain consistency with our API + images.append(image) + with open(label_path[i], 'rb') as label_file: + label_file.read(8) + label = np.fromfile(label_file, dtype=np.uint8) + labels.append(label) + + images = np.concatenate(images, 0) + labels = np.concatenate(labels, 0) + + return images, labels + + +def visualize_dataset(images, labels): + """ + Helper function to visualize the dataset samples + """ + num_samples = len(images) + for i in range(num_samples): + plt.subplot(1, num_samples, i + 1) + plt.imshow(images[i].squeeze(), cmap=plt.cm.gray) + plt.title(labels[i]) + plt.show() + + +def test_emnist_content_check(): + """ + Validate EMnistDataset image readings + """ + logger.info("Test EMnistDataset Op with content check") + # train mnist + train_data = ds.EMnistDataset(DATA_DIR, name="mnist", usage="train", num_samples=10, shuffle=False) + images, labels = load_emnist(DATA_DIR, "train", "mnist") + num_iter = 0 + # in this example, each dictionary has keys "image" and "label" + image_list, label_list = [], [] + for i, data in enumerate(train_data.create_dict_iterator(num_epochs=1, output_numpy=True)): + image_list.append(data["image"]) + label_list.append("label {}".format(data["label"])) + np.testing.assert_array_equal(data["image"], images[i]) + np.testing.assert_array_equal(data["label"], labels[i]) + num_iter += 1 + assert num_iter == 10 + + # train byclass + train_data = ds.EMnistDataset(DATA_DIR, name="byclass", usage="train", num_samples=10, shuffle=False) + images, labels = load_emnist(DATA_DIR, "train", "byclass") + num_iter = 0 + # in this example, each dictionary has keys "image" and "label" + image_list, label_list = [], [] + for i, data in enumerate(train_data.create_dict_iterator(num_epochs=1, output_numpy=True)): + image_list.append(data["image"]) + label_list.append("label {}".format(data["label"])) + np.testing.assert_array_equal(data["image"], images[i]) + np.testing.assert_array_equal(data["label"], labels[i]) + num_iter += 1 + assert num_iter == 10 + + # test + test_data = ds.EMnistDataset(DATA_DIR, name="mnist", usage="test", num_samples=10, shuffle=False) + images, labels = load_emnist(DATA_DIR, "test", "mnist") + num_iter = 0 + # in this example, each dictionary has keys "image" and "label" + image_list, label_list = [], [] + for i, data in enumerate(test_data.create_dict_iterator(num_epochs=1, output_numpy=True)): + image_list.append(data["image"]) + label_list.append("label {}".format(data["label"])) + np.testing.assert_array_equal(data["image"], images[i]) + np.testing.assert_array_equal(data["label"], labels[i]) + num_iter += 1 + assert num_iter == 10 + + +def test_emnist_basic(): + """ + Validate EMnistDataset + """ + logger.info("Test EMnistDataset Op") + + # case 1: test loading whole dataset + train_data = ds.EMnistDataset(DATA_DIR, "mnist", "train") + num_iter1 = 0 + for _ in train_data.create_dict_iterator(num_epochs=1): + num_iter1 += 1 + assert num_iter1 == 10 + + test_data = ds.EMnistDataset(DATA_DIR, "mnist", "test") + num_iter = 0 + for _ in test_data.create_dict_iterator(num_epochs=1): + num_iter += 1 + assert num_iter == 10 + + # case 2: test num_samples + train_data = ds.EMnistDataset(DATA_DIR, "byclass", "train", num_samples=5) + num_iter2 = 0 + for _ in train_data.create_dict_iterator(num_epochs=1): + num_iter2 += 1 + assert num_iter2 == 5 + + test_data = ds.EMnistDataset(DATA_DIR, "mnist", "test", num_samples=5) + num_iter2 = 0 + for _ in test_data.create_dict_iterator(num_epochs=1): + num_iter2 += 1 + assert num_iter2 == 5 + + # case 3: test repeat + train_data = ds.EMnistDataset(DATA_DIR, "byclass", "train", num_samples=2) + train_data = train_data.repeat(5) + num_iter3 = 0 + for _ in train_data.create_dict_iterator(num_epochs=1): + num_iter3 += 1 + assert num_iter3 == 10 + + test_data = ds.EMnistDataset(DATA_DIR, "mnist", "test", num_samples=2) + test_data = test_data.repeat(5) + num_iter3 = 0 + for _ in test_data.create_dict_iterator(num_epochs=1): + num_iter3 += 1 + assert num_iter3 == 10 + + # case 4: test batch with drop_remainder=False + train_data = ds.EMnistDataset(DATA_DIR, "byclass", "train", num_samples=10) + assert train_data.get_dataset_size() == 10 + assert train_data.get_batch_size() == 1 + + train_data = train_data.batch(batch_size=7) # drop_remainder is default to be False + assert train_data.get_dataset_size() == 2 + assert train_data.get_batch_size() == 7 + num_iter4 = 0 + for _ in train_data.create_dict_iterator(num_epochs=1): + num_iter4 += 1 + assert num_iter4 == 2 + + test_data = ds.EMnistDataset(DATA_DIR, "mnist", "test", num_samples=10) + assert test_data.get_dataset_size() == 10 + assert test_data.get_batch_size() == 1 + + test_data = test_data.batch( + batch_size=7) # drop_remainder is default to be False + assert test_data.get_dataset_size() == 2 + assert test_data.get_batch_size() == 7 + num_iter4 = 0 + for _ in test_data.create_dict_iterator(num_epochs=1): + num_iter4 += 1 + assert num_iter4 == 2 + + # case 5: test batch with drop_remainder=True + train_data = ds.EMnistDataset(DATA_DIR, "byclass", "train", num_samples=10) + assert train_data.get_dataset_size() == 10 + assert train_data.get_batch_size() == 1 + train_data = train_data.batch(batch_size=7, drop_remainder=True) # the rest of incomplete batch will be dropped + assert train_data.get_dataset_size() == 1 + assert train_data.get_batch_size() == 7 + num_iter5 = 0 + for _ in train_data.create_dict_iterator(num_epochs=1): + num_iter5 += 1 + assert num_iter5 == 1 + + test_data = ds.EMnistDataset(DATA_DIR, "mnist", "test", num_samples=10) + assert test_data.get_dataset_size() == 10 + assert test_data.get_batch_size() == 1 + test_data = test_data.batch(batch_size=7, drop_remainder=True) # the rest of incomplete batch will be dropped + assert test_data.get_dataset_size() == 1 + assert test_data.get_batch_size() == 7 + num_iter5 = 0 + for _ in test_data.create_dict_iterator(num_epochs=1): + num_iter5 += 1 + assert num_iter5 == 1 + + # case 6: test get_col_names + dataset = ds.EMnistDataset(DATA_DIR, "mnist", "test", num_samples=10) + assert dataset.get_col_names() == ["image", "label"] + + +def test_emnist_pk_sampler(): + """ + Test EMnistDataset with PKSampler + """ + logger.info("Test EMnistDataset Op with PKSampler") + golden = [0, 0, 0, 1, 1, 1] + + sampler = ds.PKSampler(3) + train_data = ds.EMnistDataset(DATA_DIR, "mnist", "train", sampler=sampler) + num_iter = 0 + label_list = [] + for item in train_data.create_dict_iterator(num_epochs=1, output_numpy=True): + label_list.append(item["label"]) + num_iter += 1 + np.testing.assert_array_equal(golden, label_list) + assert num_iter == 6 + + sampler = ds.PKSampler(3) + test_data = ds.EMnistDataset(DATA_DIR, "mnist", "train", sampler=sampler) + num_iter = 0 + label_list = [] + for item in test_data.create_dict_iterator(num_epochs=1, output_numpy=True): + label_list.append(item["label"]) + num_iter += 1 + np.testing.assert_array_equal(golden, label_list) + assert num_iter == 6 + + +def test_emnist_sequential_sampler(): + """ + Test EMnistDataset with SequentialSampler + """ + logger.info("Test EMnistDataset Op with SequentialSampler") + num_samples = 10 + sampler = ds.SequentialSampler(num_samples=num_samples) + train_data1 = ds.EMnistDataset(DATA_DIR, "mnist", "train", sampler=sampler) + train_data2 = ds.EMnistDataset(DATA_DIR, "mnist", "train", shuffle=False, num_samples=num_samples) + label_list1, label_list2 = [], [] + num_iter = 0 + for item1, item2 in zip(train_data1.create_dict_iterator(num_epochs=1), + train_data2.create_dict_iterator(num_epochs=1)): + label_list1.append(item1["label"].asnumpy()) + label_list2.append(item2["label"].asnumpy()) + num_iter += 1 + np.testing.assert_array_equal(label_list1, label_list2) + assert num_iter == num_samples + + num_samples = 10 + sampler = ds.SequentialSampler(num_samples=num_samples) + test_data1 = ds.EMnistDataset(DATA_DIR, "mnist", "test", sampler=sampler) + test_data2 = ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, num_samples=num_samples) + label_list1, label_list2 = [], [] + num_iter = 0 + for item1, item2 in zip(test_data1.create_dict_iterator(num_epochs=1), + test_data2.create_dict_iterator(num_epochs=1)): + label_list1.append(item1["label"].asnumpy()) + label_list2.append(item2["label"].asnumpy()) + num_iter += 1 + np.testing.assert_array_equal(label_list1, label_list2) + assert num_iter == num_samples + + +def test_emnist_exception(): + """ + Test error cases for EMnistDataset + """ + logger.info("Test error cases for EMnistDataset") + error_msg_1 = "sampler and shuffle cannot be specified at the same time" + with pytest.raises(RuntimeError, match=error_msg_1): + ds.EMnistDataset(DATA_DIR, "byclass", "train", shuffle=False, sampler=ds.PKSampler(3)) + ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, sampler=ds.PKSampler(3)) + + error_msg_2 = "sampler and sharding cannot be specified at the same time" + with pytest.raises(RuntimeError, match=error_msg_2): + ds.EMnistDataset(DATA_DIR, "mnist", "train", sampler=ds.PKSampler(3), num_shards=2, shard_id=0) + ds.EMnistDataset(DATA_DIR, "mnist", "test", sampler=ds.PKSampler(3), num_shards=2, shard_id=0) + + error_msg_3 = "num_shards is specified and currently requires shard_id as well" + with pytest.raises(RuntimeError, match=error_msg_3): + ds.EMnistDataset(DATA_DIR, "byclass", "train", num_shards=10) + ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=10) + + error_msg_4 = "shard_id is specified but num_shards is not" + with pytest.raises(RuntimeError, match=error_msg_4): + ds.EMnistDataset(DATA_DIR, "mnist", "train", shard_id=0) + ds.EMnistDataset(DATA_DIR, "mnist", "test", shard_id=0) + + error_msg_5 = "Input shard_id is not within the required interval" + with pytest.raises(ValueError, match=error_msg_5): + ds.EMnistDataset(DATA_DIR, "byclass", "train", num_shards=5, shard_id=-1) + ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=5, shard_id=-1) + with pytest.raises(ValueError, match=error_msg_5): + ds.EMnistDataset(DATA_DIR, "mnist", "train", num_shards=5, shard_id=5) + ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=5, shard_id=5) + with pytest.raises(ValueError, match=error_msg_5): + ds.EMnistDataset(DATA_DIR, "byclass", "train", num_shards=2, shard_id=5) + ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=2, shard_id=5) + + error_msg_6 = "num_parallel_workers exceeds" + with pytest.raises(ValueError, match=error_msg_6): + ds.EMnistDataset(DATA_DIR, "mnist", "train", shuffle=False, num_parallel_workers=0) + ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, num_parallel_workers=0) + with pytest.raises(ValueError, match=error_msg_6): + ds.EMnistDataset(DATA_DIR, "byclass", "train", shuffle=False, num_parallel_workers=256) + ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, num_parallel_workers=256) + with pytest.raises(ValueError, match=error_msg_6): + ds.EMnistDataset(DATA_DIR, "mnist", "train", shuffle=False, num_parallel_workers=-2) + ds.EMnistDataset(DATA_DIR, "mnist", "test", shuffle=False, num_parallel_workers=-2) + + error_msg_7 = "Argument shard_id" + with pytest.raises(TypeError, match=error_msg_7): + ds.EMnistDataset(DATA_DIR, "mnist", "train", num_shards=2, shard_id="0") + ds.EMnistDataset(DATA_DIR, "mnist", "test", num_shards=2, shard_id="0") + + def exception_func(item): + raise Exception("Error occur!") + + error_msg_8 = "The corresponding data files" + with pytest.raises(RuntimeError, match=error_msg_8): + data = ds.EMnistDataset(DATA_DIR, "mnist", "train") + data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1) + for _ in data.__iter__(): + pass + with pytest.raises(RuntimeError, match=error_msg_8): + data = ds.EMnistDataset(DATA_DIR, "mnist", "train") + data = data.map(operations=vision.Decode(), input_columns=["image"], num_parallel_workers=1) + data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1) + for _ in data.__iter__(): + pass + with pytest.raises(RuntimeError, match=error_msg_8): + data = ds.EMnistDataset(DATA_DIR, "mnist", "train") + data = data.map(operations=exception_func, input_columns=["label"], num_parallel_workers=1) + for _ in data.__iter__(): + pass + + +def test_emnist_visualize(plot=False): + """ + Visualize EMnistDataset results + """ + logger.info("Test EMnistDataset visualization") + + train_data = ds.EMnistDataset(DATA_DIR, "mnist", "train", num_samples=10, shuffle=False) + num_iter = 0 + image_list, label_list = [], [] + for item in train_data.create_dict_iterator(num_epochs=1, output_numpy=True): + image = item["image"] + label = item["label"] + image_list.append(image) + label_list.append("label {}".format(label)) + assert isinstance(image, np.ndarray) + assert image.shape == (28, 28, 1) + assert image.dtype == np.uint8 + assert label.dtype == np.uint32 + num_iter += 1 + assert num_iter == 10 + if plot: + visualize_dataset(image_list, label_list) + + test_data = ds.EMnistDataset(DATA_DIR, "mnist", "test", num_samples=10, shuffle=False) + num_iter = 0 + image_list, label_list = [], [] + for item in test_data.create_dict_iterator(num_epochs=1, output_numpy=True): + image = item["image"] + label = item["label"] + image_list.append(image) + label_list.append("label {}".format(label)) + assert isinstance(image, np.ndarray) + assert image.shape == (28, 28, 1) + assert image.dtype == np.uint8 + assert label.dtype == np.uint32 + num_iter += 1 + assert num_iter == 10 + if plot: + visualize_dataset(image_list, label_list) + + +def test_emnist_usage(): + """ + Validate EMnistDataset image readings + """ + logger.info("Test EMnistDataset usage flag") + + def test_config(usage, emnist_path=None): + emnist_path = DATA_DIR if emnist_path is None else emnist_path + try: + data = ds.EMnistDataset(emnist_path, "mnist", usage=usage, shuffle=False) + num_rows = 0 + for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True): + num_rows += 1 + except (ValueError, TypeError, RuntimeError) as e: + return str(e) + return num_rows + + assert test_config("train") == 10 + assert test_config("test") == 10 + assert test_config("all") == 20 + + assert "usage is not within the valid set of ['train', 'test', 'all']" in test_config("invalid") + assert "Argument usage with value ['list'] is not of type []" in test_config(["list"]) + + # change this directory to the folder that contains all emnist files + all_files_path = None + + # the following tests on the entire datasets + if all_files_path is not None: + assert test_config("train", all_files_path) == 10000 + assert test_config("test", all_files_path) == 60000 + assert test_config("all", all_files_path) == 70000 + assert ds.EMnistDataset(all_files_path, "mnist", usage="test").get_dataset_size() == 10000 + assert ds.EMnistDataset(all_files_path, "mnist", usage="test").get_dataset_size() == 60000 + assert ds.EMnistDataset(all_files_path, "mnist", usage="all").get_dataset_size() == 70000 + + +def test_emnist_name(): + """ + Validate EMnistDataset image readings + """ + def test_config(name, usage, emnist_path=None): + emnist_path = DATA_DIR if emnist_path is None else emnist_path + try: + data = ds.EMnistDataset(emnist_path, name, usage=usage, shuffle=False) + num_rows = 0 + for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True): + num_rows += 1 + except (ValueError, TypeError, RuntimeError) as e: + return str(e) + return num_rows + + assert test_config("mnist", "train") == 10 + assert test_config("mnist", "test") == 10 + assert test_config("byclass", "train") == 10 + assert "name is not within the valid set of " + \ + "['byclass', 'bymerge', 'balanced', 'letters', 'digits', 'mnist']" in test_config("invalid", "train") + assert "Argument name with value ['list'] is not of type []" in test_config(["list"], "train") + + +if __name__ == '__main__': + test_emnist_content_check() + test_emnist_basic() + test_emnist_pk_sampler() + test_emnist_sequential_sampler() + test_emnist_exception() + test_emnist_visualize(plot=True) + test_emnist_usage() + test_emnist_name()